blob: 1d7b4ea667035577d17ac48d649ac69751c1fa3b [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
Steve Antondcc3c022017-12-22 16:02:54 -080016#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080017#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080018#include <utility>
19#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000020
Steve Anton64b626b2019-01-28 17:25:26 -080021#include "absl/algorithm/container.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020028#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020029#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070030#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "logging/rtc_event_log/ice_logger.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Bjorn A Mellemb689af42019-08-21 10:44:59 -070059#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/trace_event.h"
61#include "system_wrappers/include/clock.h"
62#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070063#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080071using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080072using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080074using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080075using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080076using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080079using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070080using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080082
Steve Antonba818672017-11-06 10:21:57 -080083namespace webrtc {
84
Steve Anton75737c02017-11-06 10:37:17 -080085// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080089const char kInvalidCandidates[] = "Description contains invalid candidates.";
90const char kInvalidSdp[] = "Invalid session description.";
91const char kMlineMismatchInAnswer[] =
92 "The order of m-lines in answer doesn't match order in offer. Rejecting "
93 "answer.";
94const char kMlineMismatchInSubsequentOffer[] =
95 "The order of m-lines in subsequent offer doesn't match order from "
96 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080097const char kSdpWithoutDtlsFingerprint[] =
98 "Called with SDP without DTLS fingerprint.";
99const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
100const char kSdpWithoutIceUfragPwd[] =
101 "Called with SDP without ice-ufrag and ice-pwd.";
102const char kSessionError[] = "Session error code: ";
103const char kSessionErrorDesc[] = "Session error description: ";
104const char kDtlsSrtpSetupFailureRtp[] =
105 "Couldn't set up DTLS-SRTP on RTP channel.";
106const char kDtlsSrtpSetupFailureRtcp[] =
107 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108
Steve Anton75737c02017-11-06 10:37:17 -0800109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700111// Field trials.
112// Controls datagram transport support.
113const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700114// Controls datagram transport data channel support.
115const char kDatagramTransportDataChannelFieldTrial[] =
116 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700117
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800118// UMA metric names.
119const char kSimulcastVersionApplyLocalDescription[] =
120 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
121const char kSimulcastVersionApplyRemoteDescription[] =
122 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
123const char kSimulcastNumberOfEncodings[] =
124 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
125const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
126
Seth Hampson845e8782018-03-02 11:34:10 -0800127static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800128static const char kDefaultAudioSenderId[] = "defaulta0";
129static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700130
zhihuang8f65cdf2016-05-06 18:40:30 -0700131// The length of RTCP CNAMEs.
132static const int kRtcpCnameLength = 16;
133
Steve Antonad182762018-09-05 20:22:40 +0000134enum {
135 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
136 MSG_SET_SESSIONDESCRIPTION_FAILED,
137 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
138 MSG_GETSTATS,
139 MSG_FREE_DATACHANNELS,
140 MSG_REPORT_USAGE_PATTERN,
141};
142
Harald Alvestrand19793842018-06-25 12:03:50 +0200143static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
144
Steve Antonad182762018-09-05 20:22:40 +0000145struct SetSessionDescriptionMsg : public rtc::MessageData {
146 explicit SetSessionDescriptionMsg(
147 webrtc::SetSessionDescriptionObserver* observer)
148 : observer(observer) {}
149
150 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
151 RTCError error;
152};
153
154struct CreateSessionDescriptionMsg : public rtc::MessageData {
155 explicit CreateSessionDescriptionMsg(
156 webrtc::CreateSessionDescriptionObserver* observer)
157 : observer(observer) {}
158
159 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
160 RTCError error;
161};
162
163struct GetStatsMsg : public rtc::MessageData {
164 GetStatsMsg(webrtc::StatsObserver* observer,
165 webrtc::MediaStreamTrackInterface* track)
166 : observer(observer), track(track) {}
167 rtc::scoped_refptr<webrtc::StatsObserver> observer;
168 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
169};
170
deadbeefab9b2d12015-10-14 11:33:11 -0700171// Check if we can send |new_stream| on a PeerConnection.
172bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
173 webrtc::MediaStreamInterface* new_stream) {
174 if (!new_stream || !current_streams) {
175 return false;
176 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700177 if (current_streams->find(new_stream->id()) != nullptr) {
178 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700180 return false;
181 }
182 return true;
183}
184
deadbeef5e97fb52015-10-15 12:49:08 -0700185// If the direction is "recvonly" or "inactive", treat the description
186// as containing no streams.
187// See: https://code.google.com/p/webrtc/issues/detail?id=5054
188std::vector<cricket::StreamParams> GetActiveStreams(
189 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800190 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700191 ? desc->streams()
192 : std::vector<cricket::StreamParams>();
193}
194
deadbeefab9b2d12015-10-14 11:33:11 -0700195bool IsValidOfferToReceiveMedia(int value) {
196 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
197 return (value >= Options::kUndefined) &&
198 (value <= Options::kMaxOfferToReceiveMedia);
199}
200
zhihuang1c378ed2017-08-17 14:10:50 -0700201// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800202void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700203 const std::vector<rtc::scoped_refptr<
204 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700205 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200206 cricket::MediaDescriptionOptions* video_media_description_options,
207 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700208 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
210 if (audio_media_description_options) {
211 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700212 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 } else {
215 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
216 if (video_media_description_options) {
217 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800218 sender->id(), sender->internal()->stream_ids(), {},
219 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700220 }
221 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700222 }
zhihuang1c378ed2017-08-17 14:10:50 -0700223}
olka3c747662017-08-17 06:50:32 -0700224
zhihuang1c378ed2017-08-17 14:10:50 -0700225// Add options to |session_options| from |rtp_data_channels|.
226void AddRtpDataChannelOptions(
227 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
228 rtp_data_channels,
229 cricket::MediaDescriptionOptions* data_media_description_options) {
230 if (!data_media_description_options) {
231 return;
232 }
deadbeefab9b2d12015-10-14 11:33:11 -0700233 // Check for data channels.
234 for (const auto& kv : rtp_data_channels) {
235 const DataChannel* channel = kv.second;
236 if (channel->state() == DataChannel::kConnecting ||
237 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700238 // Legacy RTP data channels are signaled with the track/stream ID set to
239 // the data channel's label.
240 data_media_description_options->AddRtpDataChannel(channel->label(),
241 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700242 }
243 }
244}
245
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246uint32_t ConvertIceTransportTypeToCandidateFilter(
247 PeerConnectionInterface::IceTransportsType type) {
248 switch (type) {
249 case PeerConnectionInterface::kNone:
250 return cricket::CF_NONE;
251 case PeerConnectionInterface::kRelay:
252 return cricket::CF_RELAY;
253 case PeerConnectionInterface::kNoHost:
254 return (cricket::CF_ALL & ~cricket::CF_HOST);
255 case PeerConnectionInterface::kAll:
256 return cricket::CF_ALL;
257 default:
nissec80e7412017-01-11 05:56:46 -0800258 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700259 }
260 return cricket::CF_NONE;
261}
262
Steve Antonba818672017-11-06 10:21:57 -0800263std::string GetSignalingStateString(
264 PeerConnectionInterface::SignalingState state) {
265 switch (state) {
266 case PeerConnectionInterface::kStable:
267 return "kStable";
268 case PeerConnectionInterface::kHaveLocalOffer:
269 return "kHaveLocalOffer";
270 case PeerConnectionInterface::kHaveLocalPrAnswer:
271 return "kHavePrAnswer";
272 case PeerConnectionInterface::kHaveRemoteOffer:
273 return "kHaveRemoteOffer";
274 case PeerConnectionInterface::kHaveRemotePrAnswer:
275 return "kHaveRemotePrAnswer";
276 case PeerConnectionInterface::kClosed:
277 return "kClosed";
278 }
279 RTC_NOTREACHED();
280 return "";
281}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282
Steve Anton75737c02017-11-06 10:37:17 -0800283IceCandidatePairType GetIceCandidatePairCounter(
284 const cricket::Candidate& local,
285 const cricket::Candidate& remote) {
286 const auto& l = local.type();
287 const auto& r = remote.type();
288 const auto& host = LOCAL_PORT_TYPE;
289 const auto& srflx = STUN_PORT_TYPE;
290 const auto& relay = RELAY_PORT_TYPE;
291 const auto& prflx = PRFLX_PORT_TYPE;
292 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 bool local_hostname =
294 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
295 bool remote_hostname = !remote.address().hostname().empty() &&
296 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800297 bool local_private = IPIsPrivate(local.address().ipaddr());
298 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800299 if (local_hostname) {
300 if (remote_hostname) {
301 return kIceCandidatePairHostNameHostName;
302 } else if (remote_private) {
303 return kIceCandidatePairHostNameHostPrivate;
304 } else {
305 return kIceCandidatePairHostNameHostPublic;
306 }
307 } else if (local_private) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostPrivateHostName;
310 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800311 return kIceCandidatePairHostPrivateHostPrivate;
312 } else {
313 return kIceCandidatePairHostPrivateHostPublic;
314 }
315 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800316 if (remote_hostname) {
317 return kIceCandidatePairHostPublicHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPublicHostPrivate;
320 } else {
321 return kIceCandidatePairHostPublicHostPublic;
322 }
323 }
324 }
325 if (l == host && r == srflx)
326 return kIceCandidatePairHostSrflx;
327 if (l == host && r == relay)
328 return kIceCandidatePairHostRelay;
329 if (l == host && r == prflx)
330 return kIceCandidatePairHostPrflx;
331 if (l == srflx && r == host)
332 return kIceCandidatePairSrflxHost;
333 if (l == srflx && r == srflx)
334 return kIceCandidatePairSrflxSrflx;
335 if (l == srflx && r == relay)
336 return kIceCandidatePairSrflxRelay;
337 if (l == srflx && r == prflx)
338 return kIceCandidatePairSrflxPrflx;
339 if (l == relay && r == host)
340 return kIceCandidatePairRelayHost;
341 if (l == relay && r == srflx)
342 return kIceCandidatePairRelaySrflx;
343 if (l == relay && r == relay)
344 return kIceCandidatePairRelayRelay;
345 if (l == relay && r == prflx)
346 return kIceCandidatePairRelayPrflx;
347 if (l == prflx && r == host)
348 return kIceCandidatePairPrflxHost;
349 if (l == prflx && r == srflx)
350 return kIceCandidatePairPrflxSrflx;
351 if (l == prflx && r == relay)
352 return kIceCandidatePairPrflxRelay;
353 return kIceCandidatePairMax;
354}
355
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800356// Logic to decide if an m= section can be recycled. This means that the new
357// m= section is not rejected, but the old local or remote m= section is
358// rejected. |old_content_one| and |old_content_two| refer to the m= section
359// of the old remote and old local descriptions in no particular order.
360// We need to check both the old local and remote because either
361// could be the most current from the latest negotation.
362bool IsMediaSectionBeingRecycled(SdpType type,
363 const ContentInfo& content,
364 const ContentInfo* old_content_one,
365 const ContentInfo* old_content_two) {
366 return type == SdpType::kOffer && !content.rejected &&
367 ((old_content_one && old_content_one->rejected) ||
368 (old_content_two && old_content_two->rejected));
369}
370
Steve Anton75737c02017-11-06 10:37:17 -0800371// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372// |current_desc|. The number of m= sections in |new_desc| should be no
373// less than |current_desc|. In the case of checking an answer's
374// |new_desc|, the |current_desc| is the last offer that was set as the
375// local or remote. In the case of checking an offer's |new_desc| we
376// check against the local and remote descriptions stored from the last
377// negotiation, because either of these could be the most up to date for
378// possible rejected m sections. These are the |current_desc| and
379// |secondary_current_desc|.
380bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
381 const SessionDescription* secondary_current_desc,
382 const SessionDescription& new_desc,
383 const SdpType type) {
384 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800385 return false;
386 }
387
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
389 const cricket::ContentInfo* secondary_content_info = nullptr;
390 if (secondary_current_desc &&
391 i < secondary_current_desc->contents().size()) {
392 secondary_content_info = &secondary_current_desc->contents()[i];
393 }
394 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
395 &current_desc.contents()[i],
396 secondary_content_info)) {
397 // For new offer descriptions, if the media section can be recycled, it's
398 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800399 continue;
400 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800402 return false;
403 }
404 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800405 new_desc.contents()[i].media_description();
406 const MediaContentDescription* current_desc_mdesc =
407 current_desc.contents()[i].media_description();
408 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800409 return false;
410 }
411 }
412 return true;
413}
414
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800415bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
416 const SessionDescription& desc2) {
417 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800418}
419
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700420void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
421 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200422 // Array of structs needed to map {KeyExchangeProtocolType,
423 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
424 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
425 static constexpr struct {
426 KeyExchangeProtocolType protocol_type;
427 cricket::MediaType media_type;
428 KeyExchangeProtocolMedia protocol_media;
429 } kEnumCounterKeyProtocolMediaMap[] = {
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
434 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeDtlsData},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
437 kEnumCounterKeyProtocolMediaTypeSdesAudio},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
439 kEnumCounterKeyProtocolMediaTypeSdesVideo},
440 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
441 kEnumCounterKeyProtocolMediaTypeSdesData},
442 };
443
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
445 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100446
Mirko Bonadeiab499822018-09-11 10:43:20 +0200447 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
448 if (i.protocol_type == protocol_type && i.media_type == media_type) {
449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
450 i.protocol_media,
451 kEnumCounterKeyProtocolMediaTypeMax);
452 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100453 }
454}
455
Harald Alvestrand76829d72018-07-18 23:24:36 +0200456void NoteAddIceCandidateResult(int result) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
458 kAddIceCandidateMax);
459}
460
Steve Anton75737c02017-11-06 10:37:17 -0800461// Checks that each non-rejected content has SDES crypto keys or a DTLS
462// fingerprint, unless it's in a BUNDLE group, in which case only the
463// BUNDLE-tag section (first media section/description in the BUNDLE group)
464// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
465// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
466// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700467RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 const cricket::ContentGroup* bundle =
469 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800470 for (const cricket::ContentInfo& content_info : desc->contents()) {
471 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800472 continue;
473 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100474 // Note what media is used with each crypto protocol, for all sections.
475 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
476 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700477 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800478 const std::string& mid = content_info.name;
479 if (bundle && bundle->HasContentName(mid) &&
480 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 // This isn't the first media section in the BUNDLE group, so it's not
482 // required to have crypto attributes, since only the crypto attributes
483 // from the first section actually get used.
484 continue;
485 }
486
487 // If the content isn't rejected or bundled into another m= section, crypto
488 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800489 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800490 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (!media || !tinfo) {
492 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800494 }
495 if (dtls_enabled) {
496 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_WARNING)
498 << "Session description must have DTLS fingerprint if "
499 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError(RTCErrorType::INVALID_PARAMETER,
501 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 } else {
504 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800506 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800507 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800508 }
509 }
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800512}
513
514// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
515// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
516// media section/description in the BUNDLE group) needs a ufrag and pwd.
517bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
518 const cricket::ContentGroup* bundle =
519 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800520 for (const cricket::ContentInfo& content_info : desc->contents()) {
521 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 continue;
523 }
Steve Anton8a006912017-12-04 15:25:56 -0800524 const std::string& mid = content_info.name;
525 if (bundle && bundle->HasContentName(mid) &&
526 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 // This isn't the first media section in the BUNDLE group, so it's not
528 // required to have ufrag/password, since only the ufrag/password from
529 // the first section actually get used.
530 continue;
531 }
532
533 // If the content isn't rejected or bundled into another m= section,
534 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800535 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800536 if (!tinfo) {
537 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 if (tinfo->description.ice_ufrag.empty() ||
542 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 }
547 return true;
548}
549
Steve Anton75737c02017-11-06 10:37:17 -0800550// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
551bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
552 const SessionDescriptionInterface* new_desc,
553 const std::string& content_name) {
554 if (!old_desc) {
555 return false;
556 }
557 const SessionDescription* new_sd = new_desc->description();
558 const SessionDescription* old_sd = old_desc->description();
559 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
560 if (!cinfo || cinfo->rejected) {
561 return false;
562 }
563 // If the content isn't rejected, check if ufrag and password has changed.
564 const cricket::TransportDescription* new_transport_desc =
565 new_sd->GetTransportDescriptionByName(content_name);
566 const cricket::TransportDescription* old_transport_desc =
567 old_sd->GetTransportDescriptionByName(content_name);
568 if (!new_transport_desc || !old_transport_desc) {
569 // No transport description exists. This is not an ICE restart.
570 return false;
571 }
572 if (cricket::IceCredentialsChanged(
573 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
574 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
576 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800577 return true;
578 }
579 return false;
580}
581
Steve Anton80dd7b52018-02-16 17:08:42 -0800582// Generates a string error message for SetLocalDescription/SetRemoteDescription
583// from an RTCError.
584std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
585 SdpType type,
586 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200587 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800588 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
589 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200590 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800591}
592
Seth Hampson5b4f0752018-04-02 16:31:36 -0700593std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
594 std::string output = "streams=[";
595 const char* separator = "";
596 for (const auto& stream_id : stream_ids) {
597 output.append(separator).append(stream_id);
598 separator = ", ";
599 }
600 output.append("]");
601 return output;
602}
603
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200604absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700605 int rtc_configuration_parameter) {
606 if (rtc_configuration_parameter ==
607 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200608 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700609 }
610 return rtc_configuration_parameter;
611}
612
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800613void ReportSimulcastApiVersion(const char* name,
614 const SessionDescription& session) {
615 bool has_legacy = false;
616 bool has_spec_compliant = false;
617 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200618 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800619 continue;
620 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200621 has_spec_compliant |= content.media_description()->HasSimulcast();
622 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800623 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
624 }
625 }
626
627 if (has_legacy) {
628 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
629 kSimulcastApiVersionMax);
630 }
631 if (has_spec_compliant) {
632 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
633 kSimulcastApiVersionMax);
634 }
635 if (!has_legacy && !has_spec_compliant) {
636 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
637 kSimulcastApiVersionMax);
638 }
639}
640
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200641const ContentInfo* FindTransceiverMSection(
642 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
643 const SessionDescriptionInterface* session_description) {
644 return transceiver->mid()
645 ? session_description->description()->GetContentByName(
646 *transceiver->mid())
647 : nullptr;
648}
649
Henrik Boströma3728d32019-10-28 12:09:49 +0100650// Wraps a CreateSessionDescriptionObserver and an OperationsChain operation
651// complete callback. When the observer is invoked, the wrapped observer is
652// invoked followed by invoking the completion callback.
653class CreateSessionDescriptionObserverOperationWrapper
654 : public CreateSessionDescriptionObserver {
655 public:
656 CreateSessionDescriptionObserverOperationWrapper(
657 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer,
658 std::function<void()> operation_complete_callback)
659 : observer_(std::move(observer)),
660 operation_complete_callback_(std::move(operation_complete_callback)) {
661 RTC_DCHECK(observer_);
662 }
663 ~CreateSessionDescriptionObserverOperationWrapper() override {
664 RTC_DCHECK(was_called_);
665 }
666
667 void OnSuccess(SessionDescriptionInterface* desc) override {
668 RTC_DCHECK(!was_called_);
669#ifdef RTC_DCHECK_IS_ON
670 was_called_ = true;
671#endif // RTC_DCHECK_IS_ON
672 // Completing the operation before invoking the observer allows the observer
673 // to execute SetLocalDescription() without delay.
674 operation_complete_callback_();
675 observer_->OnSuccess(desc);
676 }
677
678 void OnFailure(RTCError error) override {
679 RTC_DCHECK(!was_called_);
680#ifdef RTC_DCHECK_IS_ON
681 was_called_ = true;
682#endif // RTC_DCHECK_IS_ON
683 operation_complete_callback_();
684 observer_->OnFailure(std::move(error));
685 }
686
687 private:
688#ifdef RTC_DCHECK_IS_ON
689 bool was_called_ = false;
690#endif // RTC_DCHECK_IS_ON
691 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer_;
692 std::function<void()> operation_complete_callback_;
693};
694
Steve Anton75737c02017-11-06 10:37:17 -0800695} // namespace
696
Henrik Boström4e196702019-10-30 10:35:50 +0100697// Used by parameterless SetLocalDescription() to create an offer or answer.
698// Upon completion of creating the session description, SetLocalDescription() is
699// invoked with the result.
700// For consistency with DoSetLocalDescription(), if the PeerConnection is
701// destroyed midst operation, we DO NOT inform the
702// |set_local_description_observer| that the operation failed.
703// TODO(hbos): If/when we process SLD messages in ~PeerConnection, the
704// consistent thing would be to inform the observer here.
705class PeerConnection::ImplicitCreateSessionDescriptionObserver
706 : public CreateSessionDescriptionObserver {
707 public:
708 ImplicitCreateSessionDescriptionObserver(
709 rtc::WeakPtr<PeerConnection> pc,
710 rtc::scoped_refptr<SetSessionDescriptionObserver>
711 set_local_description_observer)
712 : pc_(std::move(pc)),
713 set_local_description_observer_(
714 std::move(set_local_description_observer)) {}
715 ~ImplicitCreateSessionDescriptionObserver() override {
716 RTC_DCHECK(was_called_);
717 }
718
719 void SetOperationCompleteCallback(
720 std::function<void()> operation_complete_callback) {
721 operation_complete_callback_ = std::move(operation_complete_callback);
722 }
723
724 bool was_called() const { return was_called_; }
725
726 void OnSuccess(SessionDescriptionInterface* desc_ptr) override {
727 RTC_DCHECK(!was_called_);
728 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
729 was_called_ = true;
730
731 // Abort early if |pc_| is no longer valid.
732 if (!pc_) {
733 operation_complete_callback_();
734 return;
735 }
736 // DoSetLocalDescription() is currently implemented as a synchronous
737 // operation but where the |set_local_description_observer_|'s callbacks are
738 // invoked asynchronously in a post to PeerConnection::OnMessage().
739 pc_->DoSetLocalDescription(std::move(desc),
740 std::move(set_local_description_observer_));
741 // For backwards-compatability reasons, we declare the operation as
742 // completed here (rather than in PeerConnection::OnMessage()). This ensures
743 // that subsequent offer/answer operations can start immediately (without
744 // waiting for OnMessage()).
745 operation_complete_callback_();
746 }
747
748 void OnFailure(RTCError error) override {
749 RTC_DCHECK(!was_called_);
750 was_called_ = true;
751
752 // Abort early if |pc_| is no longer valid.
753 if (!pc_) {
754 operation_complete_callback_();
755 return;
756 }
757 // DoSetLocalDescription() reports its failures in a post. We do the
758 // same thing here for consistency.
759 pc_->PostSetSessionDescriptionFailure(
760 set_local_description_observer_,
761 RTCError(error.type(),
762 std::string("SetLocalDescription failed to create "
763 "session description - ") +
764 error.message()));
765 operation_complete_callback_();
766 }
767
768 private:
769 bool was_called_ = false;
770 rtc::WeakPtr<PeerConnection> pc_;
771 rtc::scoped_refptr<SetSessionDescriptionObserver>
772 set_local_description_observer_;
773 std::function<void()> operation_complete_callback_;
774};
775
Henrik Boström79b69802019-07-18 11:16:56 +0200776class PeerConnection::LocalIceCredentialsToReplace {
777 public:
778 // Sets the ICE credentials that need restarting to the ICE credentials of
779 // the current and pending descriptions.
780 void SetIceCredentialsFromLocalDescriptions(
781 const SessionDescriptionInterface* current_local_description,
782 const SessionDescriptionInterface* pending_local_description) {
783 ice_credentials_.clear();
784 if (current_local_description) {
785 AppendIceCredentialsFromSessionDescription(*current_local_description);
786 }
787 if (pending_local_description) {
788 AppendIceCredentialsFromSessionDescription(*pending_local_description);
789 }
790 }
791
792 void ClearIceCredentials() { ice_credentials_.clear(); }
793
794 // Returns true if we have ICE credentials that need restarting.
795 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
796
797 // Returns true if |local_description| shares no ICE credentials with the
798 // ICE credentials that need restarting.
799 bool SatisfiesIceRestart(
800 const SessionDescriptionInterface& local_description) const {
801 for (const auto& transport_info :
802 local_description.description()->transport_infos()) {
803 if (ice_credentials_.find(std::make_pair(
804 transport_info.description.ice_ufrag,
805 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
806 return false;
807 }
808 }
809 return true;
810 }
811
812 private:
813 void AppendIceCredentialsFromSessionDescription(
814 const SessionDescriptionInterface& desc) {
815 for (const auto& transport_info : desc.description()->transport_infos()) {
816 ice_credentials_.insert(
817 std::make_pair(transport_info.description.ice_ufrag,
818 transport_info.description.ice_pwd));
819 }
820 }
821
822 std::set<std::pair<std::string, std::string>> ice_credentials_;
823};
824
Henrik Boström31638672017-11-23 17:48:32 +0100825// Upon completion, posts a task to execute the callback of the
826// SetSessionDescriptionObserver asynchronously on the same thread. At this
827// point, the state of the peer connection might no longer reflect the effects
828// of the SetRemoteDescription operation, as the peer connection could have been
829// modified during the post.
830// TODO(hbos): Remove this class once we remove the version of
831// PeerConnectionInterface::SetRemoteDescription() that takes a
832// SetSessionDescriptionObserver as an argument.
833class PeerConnection::SetRemoteDescriptionObserverAdapter
834 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
835 public:
836 SetRemoteDescriptionObserverAdapter(
837 rtc::scoped_refptr<PeerConnection> pc,
838 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
839 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
840
841 // SetRemoteDescriptionObserverInterface implementation.
842 void OnSetRemoteDescriptionComplete(RTCError error) override {
843 if (error.ok())
844 pc_->PostSetSessionDescriptionSuccess(wrapper_);
845 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100846 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100847 }
848
849 private:
850 rtc::scoped_refptr<PeerConnection> pc_;
851 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
852};
853
deadbeef293e9262017-01-11 12:28:30 -0800854bool PeerConnectionInterface::RTCConfiguration::operator==(
855 const PeerConnectionInterface::RTCConfiguration& o) const {
856 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700857 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800858 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000859 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700860 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800861 BundlePolicy bundle_policy;
862 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700863 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
864 int ice_candidate_pool_size;
865 bool disable_ipv6;
866 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700867 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100868 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700869 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200870 absl::optional<int> screencast_min_bitrate;
871 absl::optional<bool> combined_audio_video_bwe;
872 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800873 TcpCandidatePolicy tcp_candidate_policy;
874 CandidateNetworkPolicy candidate_network_policy;
875 int audio_jitter_buffer_max_packets;
876 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100877 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100878 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800879 int ice_connection_receiving_timeout;
880 int ice_backup_candidate_pair_ping_interval;
881 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800882 bool prioritize_most_likely_ice_candidate_pairs;
883 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800884 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700885 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 12:28:30 -0800886 bool presume_writable_when_fully_relayed;
887 bool enable_ice_renomination;
888 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700889 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200890 absl::optional<int> ice_check_interval_strong_connectivity;
891 absl::optional<int> ice_check_interval_weak_connectivity;
892 absl::optional<int> ice_check_min_interval;
893 absl::optional<int> ice_unwritable_timeout;
894 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800895 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200896 absl::optional<int> stun_candidate_keepalive_interval;
897 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200898 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800899 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200900 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700901 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700902 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700903 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700904 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700905 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700906 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700907 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100908 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200909 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 18:29:44 +0300910 bool enable_implicit_rollback;
philipel16cec3b2019-10-25 12:23:02 +0200911 absl::optional<bool> allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800912 };
913 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
914 "Did you add something to RTCConfiguration and forget to "
915 "update operator==?");
916 return type == o.type && servers == o.servers &&
917 bundle_policy == o.bundle_policy &&
918 rtcp_mux_policy == o.rtcp_mux_policy &&
919 tcp_candidate_policy == o.tcp_candidate_policy &&
920 candidate_network_policy == o.candidate_network_policy &&
921 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
922 audio_jitter_buffer_fast_accelerate ==
923 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100924 audio_jitter_buffer_min_delay_ms ==
925 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100926 audio_jitter_buffer_enable_rtx_handling ==
927 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800928 ice_connection_receiving_timeout ==
929 o.ice_connection_receiving_timeout &&
930 ice_backup_candidate_pair_ping_interval ==
931 o.ice_backup_candidate_pair_ping_interval &&
932 continual_gathering_policy == o.continual_gathering_policy &&
933 certificates == o.certificates &&
934 prioritize_most_likely_ice_candidate_pairs ==
935 o.prioritize_most_likely_ice_candidate_pairs &&
936 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800937 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700938 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100939 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800940 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800941 screencast_min_bitrate == o.screencast_min_bitrate &&
942 combined_audio_video_bwe == o.combined_audio_video_bwe &&
943 enable_dtls_srtp == o.enable_dtls_srtp &&
944 ice_candidate_pool_size == o.ice_candidate_pool_size &&
945 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700946 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 12:28:30 -0800947 presume_writable_when_fully_relayed ==
948 o.presume_writable_when_fully_relayed &&
949 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800950 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700951 surface_ice_candidates_on_ice_transport_type_changed ==
952 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800953 ice_check_interval_strong_connectivity ==
954 o.ice_check_interval_strong_connectivity &&
955 ice_check_interval_weak_connectivity ==
956 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700957 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700958 ice_unwritable_timeout == o.ice_unwritable_timeout &&
959 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800960 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800961 stun_candidate_keepalive_interval ==
962 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200963 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800964 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800965 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700966 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700967 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700968 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700969 use_media_transport_for_data_channels ==
970 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700971 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700972 use_datagram_transport_for_data_channels ==
973 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700974 use_datagram_transport_for_data_channels_receive_only ==
975 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100976 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200977 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 18:29:44 +0300978 turn_logging_id == o.turn_logging_id &&
philipel16cec3b2019-10-25 12:23:02 +0200979 enable_implicit_rollback == o.enable_implicit_rollback &&
980 allow_codec_switching == o.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800981}
982
983bool PeerConnectionInterface::RTCConfiguration::operator!=(
984 const PeerConnectionInterface::RTCConfiguration& o) const {
985 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800986}
987
zhihuang8f65cdf2016-05-06 18:40:30 -0700988// Generate a RTCP CNAME when a PeerConnection is created.
989std::string GenerateRtcpCname() {
990 std::string cname;
991 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100992 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800993 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700994 }
995 return cname;
996}
997
zhihuang1c378ed2017-08-17 14:10:50 -0700998bool ValidateOfferAnswerOptions(
999 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
1000 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
1001 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -07001002}
1003
zhihuang1c378ed2017-08-17 14:10:50 -07001004// From |rtc_options|, fill parts of |session_options| shared by all generated
1005// m= sections (in other words, nothing that involves a map/array).
1006void ExtractSharedMediaSessionOptions(
1007 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1008 cricket::MediaSessionOptions* session_options) {
1009 session_options->vad_enabled = rtc_options.voice_activity_detection;
1010 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +02001011 session_options->raw_packetization_for_video =
1012 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -07001013}
zhihuanga77e6bb2017-08-14 18:17:48 -07001014
zhihuang38ede132017-06-15 12:52:32 -07001015PeerConnection::PeerConnection(PeerConnectionFactory* factory,
1016 std::unique_ptr<RtcEventLog> event_log,
1017 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -07001019 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +01001020 event_log_ptr_(event_log_.get()),
Henrik Boströma3728d32019-10-28 12:09:49 +01001021 operations_chain_(rtc::OperationsChain::Create()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001022 datagram_transport_config_(
1023 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001024 datagram_transport_data_channel_config_(
1025 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -07001026 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -07001027 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -07001028 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001029 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +02001030 call_ptr_(call_.get()),
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001031 data_channel_transport_(nullptr),
Henrik Boströma3728d32019-10-28 12:09:49 +01001032 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()),
1033 weak_ptr_factory_(this) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034
1035PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001036 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -08001037 RTC_DCHECK_RUN_ON(signaling_thread());
1038
Henrik Boströma3728d32019-10-28 12:09:49 +01001039 weak_ptr_factory_.InvalidateWeakPtrs();
1040
Steve Anton8af21862017-12-15 11:20:13 -08001041 // Need to stop transceivers before destroying the stats collector because
1042 // AudioRtpSender has a reference to the StatsCollector it will update when
1043 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +01001044 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08001045 transceiver->Stop();
1046 }
Steve Anton4171afb2017-11-20 10:20:22 -08001047
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001048 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -08001049 if (stats_collector_) {
1050 stats_collector_->WaitForPendingRequest();
1051 stats_collector_ = nullptr;
1052 }
Steve Anton75737c02017-11-06 10:37:17 -08001053
Steve Anton8af21862017-12-15 11:20:13 -08001054 // Don't destroy BaseChannels until after stats has been cleaned up so that
1055 // the last stats request can still read from the channels.
1056 DestroyAllChannels();
1057
Mirko Bonadei675513b2017-11-09 11:09:25 +01001058 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -08001059
1060 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001061 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001062 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001063 transport_controller_.reset();
1064
deadbeef91dd5672016-05-18 16:55:30 -07001065 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001066 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1067 RTC_DCHECK_RUN_ON(network_thread());
1068 port_allocator_.reset();
1069 });
eladalon248fd4f2017-09-06 05:18:15 -07001070 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -07001071 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01001072 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07001073 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -08001074 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -07001075 event_log_.reset();
1076 });
Henrik Boströma3728d32019-10-28 12:09:49 +01001077
1078 // Process all pending notifications in the message queue. If we don't do
1079 // this, requests will linger and not know they succeeded or failed.
1080 rtc::MessageList list;
1081 signaling_thread()->Clear(this, rtc::MQID_ANY, &list);
1082 for (auto& msg : list) {
1083 if (msg.message_id == MSG_CREATE_SESSIONDESCRIPTION_FAILED) {
1084 // Processing CreateOffer() and CreateAnswer() messages ensures their
1085 // observers are invoked even if the PeerConnection is destroyed early.
1086 OnMessage(&msg);
1087 } else {
1088 // TODO(hbos): Consider processing all pending messages. This would mean
1089 // that SetLocalDescription() and SetRemoteDescription() observers are
1090 // informed of successes and failures; this is currently NOT the case.
1091 delete msg.pdata;
1092 }
1093 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094}
1095
Steve Anton8af21862017-12-15 11:20:13 -08001096void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -08001097 // Destroy video channels first since they may have a pointer to a voice
1098 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +01001099 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001100 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001101 DestroyTransceiverChannel(transceiver);
1102 }
1103 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01001104 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001105 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001106 DestroyTransceiverChannel(transceiver);
1107 }
1108 }
1109 DestroyDataChannel();
1110}
1111
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001113 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -07001114 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001115 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01001116 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01001117 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -07001118
1119 RTCError config_error = ValidateConfiguration(configuration);
1120 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001121 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -07001122 return false;
1123 }
1124
Benjamin Wrightcab58882018-05-02 15:12:47 -07001125 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001126 RTC_LOG(LS_ERROR)
1127 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001128 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001129 return false;
1130 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001131
Benjamin Wrightcab58882018-05-02 15:12:47 -07001132 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001133 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001134 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001135 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001136 return false;
1137 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001138
Benjamin Wrightcab58882018-05-02 15:12:47 -07001139 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001140 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001141 port_allocator_ = std::move(dependencies.allocator);
Qingsi Wang25ec8882019-11-15 12:33:05 -08001142 ice_transport_factory_ = std::move(dependencies.ice_transport_factory);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001143 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001144
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001145 cricket::ServerAddresses stun_servers;
1146 std::vector<cricket::RelayServerConfig> turn_servers;
1147
1148 RTCErrorType parse_error =
1149 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1150 if (parse_error != RTCErrorType::NONE) {
1151 return false;
1152 }
1153
Jonas Oreland3c028422019-08-22 16:16:35 +02001154 // Add the turn logging id to all turn servers
1155 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1156 turn_server.turn_logging_id = configuration.turn_logging_id;
1157 }
1158
deadbeef91dd5672016-05-18 16:55:30 -07001159 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001160 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001161 const auto pa_result =
1162 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001163 RTC_FROM_HERE,
1164 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001165 stun_servers, turn_servers, configuration));
1166
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001167 // If initialization was successful, note if STUN or TURN servers
1168 // were supplied.
1169 if (!stun_servers.empty()) {
1170 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1171 }
1172 if (!turn_servers.empty()) {
1173 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1174 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001176 // Send information about IPv4/IPv6 status.
1177 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001178 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001179 address_family = kPeerConnection_IPv6;
1180 } else {
1181 address_family = kPeerConnection_IPv4;
1182 }
1183 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1184 kPeerConnectionAddressFamilyCounter_Max);
1185
Zhi Huange830e682018-03-30 10:48:35 -07001186 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1187
Steve Anton75737c02017-11-06 10:37:17 -08001188 // RFC 3264: The numeric value of the session id and version in the
1189 // o line MUST be representable with a "64 bit signed integer".
1190 // Due to this constraint session id |session_id_| is max limited to
1191 // LLONG_MAX.
1192 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001193 JsepTransportController::Config config;
1194 config.redetermine_role_on_ice_restart =
1195 configuration.redetermine_role_on_ice_restart;
1196 config.ssl_max_version = factory_->options().ssl_max_version;
1197 config.disable_encryption = options.disable_encryption;
1198 config.bundle_policy = configuration.bundle_policy;
1199 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001200 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1201 // stub.
1202 config.crypto_options = configuration.crypto_options.has_value()
1203 ? *configuration.crypto_options
1204 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001205 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001206 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1207 // since the JsepTransportController instance is owned by this PeerConnection
1208 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1209 // pointer.
1210 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1211 int64_t packet_time_us) {
1212 RTC_DCHECK_RUN_ON(network_thread());
1213 rtcp_invoker_.AsyncInvoke<void>(
1214 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1215 RTC_DCHECK_RUN_ON(worker_thread());
1216 // |call_| is reset on the worker thread in the PeerConnection
1217 // destructor, so we check that it's still valid before propagating
1218 // the packet.
1219 if (call_) {
1220 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1221 packet_time_us);
1222 }
1223 });
1224 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001225 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001226#if defined(ENABLE_EXTERNAL_AUTH)
1227 config.enable_external_auth = true;
1228#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001229 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001230
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001231 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001232 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001233 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001234 use_datagram_transport_for_data_channels_ =
1235 datagram_transport_data_channel_config_.enabled &&
1236 configuration.use_datagram_transport_for_data_channels.value_or(
1237 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001238 use_datagram_transport_for_data_channels_receive_only_ =
1239 configuration.use_datagram_transport_for_data_channels_receive_only
1240 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001241 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1242 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001243 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001244 if (!factory_->media_transport_factory()) {
1245 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001246 << "PeerConnecton is initialized with use_media_transport = true or "
1247 << "use_media_transport_for_data_channels = true "
1248 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001249 return false;
1250 }
1251
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001252 if (configuration.use_media_transport ||
1253 configuration.use_media_transport_for_data_channels) {
1254 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1255 // RTP media transport is introduced. But until then, we require SDES to
1256 // be enabled.
1257 if (configuration.enable_dtls_srtp.has_value() &&
1258 configuration.enable_dtls_srtp.value()) {
1259 RTC_LOG(LS_WARNING)
1260 << "When media transport is used, SDES must be enabled. Set "
1261 "configuration.enable_dtls_srtp to false. use_media_transport="
1262 << configuration.use_media_transport
1263 << ", use_media_transport_for_data_channels="
1264 << configuration.use_media_transport_for_data_channels;
1265 return false;
1266 }
1267 }
1268
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001269 config.use_media_transport_for_media = configuration.use_media_transport;
1270 config.use_media_transport_for_data_channels =
1271 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001272 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001273 config.use_datagram_transport_for_data_channels =
1274 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001275 config.use_datagram_transport_for_data_channels_receive_only =
1276 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001277 config.media_transport_factory = factory_->media_transport_factory();
1278 }
1279
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001280 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1281 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1282 if (!configuration.certificates.empty()) {
1283 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1284 // just picking the first one. The decision should be made based on the DTLS
1285 // handshake. The DTLS negotiations need to know about all certificates.
1286 certificate = configuration.certificates[0];
1287 }
1288
1289 if (options.disable_encryption) {
1290 dtls_enabled_ = false;
1291 } else {
1292 // Enable DTLS by default if we have an identity store or a certificate.
1293 dtls_enabled_ = (dependencies.cert_generator || certificate);
1294 // |configuration| can override the default |dtls_enabled_| value.
1295 if (configuration.enable_dtls_srtp) {
1296 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1297 }
1298 }
1299
1300 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1301
1302 if (use_datagram_transport_for_data_channels_) {
1303 if (configuration.enable_rtp_data_channel) {
1304 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1305 "use_datagram_transport_for_data_channels are "
1306 "incompatible and cannot both be set to true";
1307 return false;
1308 }
1309 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1310 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1311 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1312 } else {
1313 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1314 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1315 config.sctp_factory = sctp_factory_.get();
1316 }
1317 } else if (configuration.use_media_transport_for_data_channels) {
1318 if (configuration.enable_rtp_data_channel) {
1319 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1320 "use_media_transport_for_data_channels are "
1321 "incompatible and cannot both be set to true";
1322 return false;
1323 }
1324 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1325 } else if (configuration.enable_rtp_data_channel) {
1326 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1327 // set. It takes precendence over the disable_sctp_data_channels
1328 // PeerConnectionFactoryInterface::Options.
1329 data_channel_type_ = cricket::DCT_RTP;
1330 } else {
1331 // DTLS has to be enabled to use SCTP.
1332 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1333 data_channel_type_ = cricket::DCT_SCTP;
1334 config.sctp_factory = sctp_factory_.get();
1335 }
1336 }
1337
Qingsi Wang25ec8882019-11-15 12:33:05 -08001338 config.ice_transport_factory = ice_transport_factory_.get();
1339
Zhi Huange830e682018-03-30 10:48:35 -07001340 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001341 signaling_thread(), network_thread(), port_allocator_.get(),
1342 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001343 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001344 this, &PeerConnection::OnTransportControllerConnectionState);
1345 transport_controller_->SignalStandardizedIceConnectionState.connect(
1346 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001347 transport_controller_->SignalConnectionState.connect(
1348 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001349 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001350 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001351 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001352 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001353 transport_controller_->SignalIceCandidateError.connect(
1354 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001355 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001356 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1357 transport_controller_->SignalDtlsHandshakeError.connect(
1358 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001359 transport_controller_->SignalIceCandidatePairChanged.connect(
1360 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001361
deadbeefab9b2d12015-10-14 11:33:11 -07001362 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001363 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364
Steve Antonba818672017-11-06 10:21:57 -08001365 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001366 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001367
Steve Antond25da372017-11-06 14:50:29 -08001368 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001369
Steve Anton75737c02017-11-06 10:37:17 -08001370 video_options_.screencast_min_bitrate_kbps =
1371 configuration.screencast_min_bitrate;
1372 audio_options_.combined_audio_video_bwe =
1373 configuration.combined_audio_video_bwe;
1374
1375 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001376 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001377
1378 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001379 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001380
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001381 audio_options_.audio_jitter_buffer_min_delay_ms =
1382 configuration.audio_jitter_buffer_min_delay_ms;
1383
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001384 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1385 configuration.audio_jitter_buffer_enable_rtx_handling;
1386
Steve Anton75737c02017-11-06 10:37:17 -08001387 // Whether the certificate generator/certificate is null or not determines
1388 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1389 // the right instructions by clearing the variables if needed.
1390 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001391 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001392 certificate = nullptr;
1393 } else if (certificate) {
1394 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001395 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001396 }
1397
1398 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1399 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001400 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001401 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1402 this, &PeerConnection::OnCertificateReady);
1403
1404 if (options.disable_encryption) {
1405 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1406 }
1407
1408 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001409 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001410 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411
Steve Anton4171afb2017-11-20 10:20:22 -08001412 // Add default audio/video transceivers for Plan B SDP.
1413 if (!IsUnifiedPlan()) {
1414 transceivers_.push_back(
1415 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1416 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1417 transceivers_.push_back(
1418 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1419 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1420 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001421 int delay_ms =
1422 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001423 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1424 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001425
1426 if (dependencies.video_bitrate_allocator_factory) {
1427 video_bitrate_allocator_factory_ =
1428 std::move(dependencies.video_bitrate_allocator_factory);
1429 } else {
1430 video_bitrate_allocator_factory_ =
1431 CreateBuiltinVideoBitrateAllocatorFactory();
1432 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 return true;
1434}
1435
Steve Anton038834f2017-07-14 15:59:59 -07001436RTCError PeerConnection::ValidateConfiguration(
1437 const RTCConfiguration& config) const {
1438 if (config.ice_regather_interval_range &&
1439 config.continual_gathering_policy == GATHER_ONCE) {
1440 return RTCError(RTCErrorType::INVALID_PARAMETER,
1441 "ice_regather_interval_range specified but continual "
1442 "gathering policy is GATHER_ONCE");
1443 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001444 auto result =
1445 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1446 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001447}
1448
Yves Gerey665174f2018-06-19 15:03:05 +02001449rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001450 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001451 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1452 "Plan SdpSemantics. Please use GetSenders "
1453 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001454 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455}
1456
Yves Gerey665174f2018-06-19 15:03:05 +02001457rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001458 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001459 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1460 "Plan SdpSemantics. Please use GetReceivers "
1461 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001462 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463}
1464
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001465bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001466 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001467 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1468 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001469 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470 if (IsClosed()) {
1471 return false;
1472 }
deadbeefab9b2d12015-10-14 11:33:11 -07001473 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474 return false;
1475 }
deadbeefab9b2d12015-10-14 11:33:11 -07001476
1477 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001478 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1479 observer->SignalAudioTrackAdded.connect(this,
1480 &PeerConnection::OnAudioTrackAdded);
1481 observer->SignalAudioTrackRemoved.connect(
1482 this, &PeerConnection::OnAudioTrackRemoved);
1483 observer->SignalVideoTrackAdded.connect(this,
1484 &PeerConnection::OnVideoTrackAdded);
1485 observer->SignalVideoTrackRemoved.connect(
1486 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001487 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001488
deadbeefab9b2d12015-10-14 11:33:11 -07001489 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001490 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001491 }
1492 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001493 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001494 }
1495
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001496 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001497 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001498 return true;
1499}
1500
1501void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001502 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001503 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1504 "Plan SdpSemantics. Please use RemoveTrack "
1505 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001506 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001507 if (!IsClosed()) {
1508 for (const auto& track : local_stream->GetAudioTracks()) {
1509 RemoveAudioTrack(track.get(), local_stream);
1510 }
1511 for (const auto& track : local_stream->GetVideoTracks()) {
1512 RemoveVideoTrack(track.get(), local_stream);
1513 }
deadbeefab9b2d12015-10-14 11:33:11 -07001514 }
deadbeefab9b2d12015-10-14 11:33:11 -07001515 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001516 stream_observers_.erase(
1517 std::remove_if(
1518 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001519 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001520 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001521 }),
1522 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001523
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524 if (IsClosed()) {
1525 return;
1526 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001527 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528}
1529
Steve Anton2d6c76a2018-01-05 17:10:52 -08001530RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001531 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001532 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001533 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001534 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001535 if (!track) {
1536 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1537 }
1538 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1539 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1540 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1541 "Track has invalid kind: " + track->kind());
1542 }
Steve Antonf9381f02017-12-14 10:23:57 -08001543 if (IsClosed()) {
1544 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1545 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001546 }
Steve Anton4171afb2017-11-20 10:20:22 -08001547 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001548 LOG_AND_RETURN_ERROR(
1549 RTCErrorType::INVALID_PARAMETER,
1550 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001551 }
Steve Antonf9381f02017-12-14 10:23:57 -08001552 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001553 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1554 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001555 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001556 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001557 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001558 }
1559 return sender_or_error;
1560}
deadbeefe1f9d832016-01-14 15:35:42 -08001561
Steve Antonf9381f02017-12-14 10:23:57 -08001562RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1563PeerConnection::AddTrackPlanB(
1564 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001565 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001566 if (stream_ids.size() > 1u) {
1567 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1568 "AddTrack with more than one stream is not "
1569 "supported with Plan B semantics.");
1570 }
1571 std::vector<std::string> adjusted_stream_ids = stream_ids;
1572 if (adjusted_stream_ids.empty()) {
1573 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1574 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001575 cricket::MediaType media_type =
1576 (track->kind() == MediaStreamTrackInterface::kAudioKind
1577 ? cricket::MEDIA_TYPE_AUDIO
1578 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001579 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001580 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001581 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001582 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001583 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001584 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001585 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001586 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001587 if (sender_info) {
1588 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001589 }
Steve Antonf9381f02017-12-14 10:23:57 -08001590 } else {
1591 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001592 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001593 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001594 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001595 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001596 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001597 if (sender_info) {
1598 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001599 }
deadbeefe1f9d832016-01-14 15:35:42 -08001600 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001601 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001602}
deadbeefe1f9d832016-01-14 15:35:42 -08001603
Steve Antonf9381f02017-12-14 10:23:57 -08001604RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1605PeerConnection::AddTrackUnifiedPlan(
1606 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001607 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001608 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1609 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001610 RTC_LOG(LS_INFO) << "Reusing an existing "
1611 << cricket::MediaTypeToString(transceiver->media_type())
1612 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001613 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001614 transceiver->internal()->set_direction(
1615 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001616 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001617 transceiver->internal()->set_direction(
1618 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001619 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001620 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001621 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001622 } else {
1623 cricket::MediaType media_type =
1624 (track->kind() == MediaStreamTrackInterface::kAudioKind
1625 ? cricket::MEDIA_TYPE_AUDIO
1626 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001627 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1628 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001629 std::string sender_id = track->id();
1630 // Avoid creating a sender with an existing ID by generating a random ID.
1631 // This can happen if this is the second time AddTrack has created a sender
1632 // for this track.
1633 if (FindSenderById(sender_id)) {
1634 sender_id = rtc::CreateRandomUuid();
1635 }
Florent Castelli892acf02018-10-01 22:47:20 +02001636 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001637 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1638 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001639 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001640 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001641 }
Steve Antonf9381f02017-12-14 10:23:57 -08001642 return transceiver->sender();
1643}
1644
1645rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1646PeerConnection::FindFirstTransceiverForAddedTrack(
1647 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1648 RTC_DCHECK(track);
1649 for (auto transceiver : transceivers_) {
1650 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001651 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001652 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001653 !transceiver->internal()->has_ever_been_used_to_send() &&
1654 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001655 return transceiver;
1656 }
1657 }
1658 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001659}
1660
1661bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1662 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001663 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001664}
1665
Steve Anton24db5732018-07-23 10:27:33 -07001666RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001667 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001668 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001669 if (!sender) {
1670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1671 }
deadbeefe1f9d832016-01-14 15:35:42 -08001672 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1674 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001675 }
Steve Antonf9381f02017-12-14 10:23:57 -08001676 if (IsUnifiedPlan()) {
1677 auto transceiver = FindTransceiverBySender(sender);
1678 if (!transceiver || !sender->track()) {
1679 return RTCError::OK();
1680 }
1681 sender->SetTrack(nullptr);
1682 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001683 transceiver->internal()->set_direction(
1684 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001685 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001686 transceiver->internal()->set_direction(
1687 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001688 }
Steve Anton4171afb2017-11-20 10:20:22 -08001689 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001690 bool removed;
1691 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1692 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1693 } else {
1694 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1695 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1696 }
1697 if (!removed) {
1698 LOG_AND_RETURN_ERROR(
1699 RTCErrorType::INVALID_PARAMETER,
1700 "Couldn't find sender " + sender->id() + " to remove.");
1701 }
Steve Anton4171afb2017-11-20 10:20:22 -08001702 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001703 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001704 return RTCError::OK();
1705}
1706
1707rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1708PeerConnection::FindTransceiverBySender(
1709 rtc::scoped_refptr<RtpSenderInterface> sender) {
1710 for (auto transceiver : transceivers_) {
1711 if (transceiver->sender() == sender) {
1712 return transceiver;
1713 }
1714 }
1715 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001716}
1717
Steve Anton9158ef62017-11-27 13:01:52 -08001718RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1719PeerConnection::AddTransceiver(
1720 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1721 return AddTransceiver(track, RtpTransceiverInit());
1722}
1723
1724RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1725PeerConnection::AddTransceiver(
1726 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1727 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001728 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001729 RTC_CHECK(IsUnifiedPlan())
1730 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001731 if (!track) {
1732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1733 }
1734 cricket::MediaType media_type;
1735 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1736 media_type = cricket::MEDIA_TYPE_AUDIO;
1737 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1738 media_type = cricket::MEDIA_TYPE_VIDEO;
1739 } else {
1740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1741 "Track kind is not audio or video");
1742 }
1743 return AddTransceiver(media_type, track, init);
1744}
1745
1746RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1747PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1748 return AddTransceiver(media_type, RtpTransceiverInit());
1749}
1750
1751RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1752PeerConnection::AddTransceiver(cricket::MediaType media_type,
1753 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001754 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001755 RTC_CHECK(IsUnifiedPlan())
1756 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001757 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1758 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1759 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1760 "media type is not audio or video");
1761 }
1762 return AddTransceiver(media_type, nullptr, init);
1763}
1764
1765RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1766PeerConnection::AddTransceiver(
1767 cricket::MediaType media_type,
1768 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001769 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001770 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001771 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1772 media_type == cricket::MEDIA_TYPE_VIDEO));
1773 if (track) {
1774 RTC_DCHECK_EQ(media_type,
1775 (track->kind() == MediaStreamTrackInterface::kAudioKind
1776 ? cricket::MEDIA_TYPE_AUDIO
1777 : cricket::MEDIA_TYPE_VIDEO));
1778 }
1779
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001780 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1781 init.send_encodings.size(), 0, 7, 8);
1782
Amit Hilbuchaa584152019-02-06 17:09:52 -08001783 size_t num_rids = absl::c_count_if(init.send_encodings,
1784 [](const RtpEncodingParameters& encoding) {
1785 return !encoding.rid.empty();
1786 });
1787 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001788 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001789 RTCErrorType::INVALID_PARAMETER,
1790 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001791 }
1792
Amit Hilbuchf4770402019-04-08 14:11:57 -07001793 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1794 [](const RtpEncodingParameters& encoding) {
1795 return !IsLegalRsidName(encoding.rid);
1796 })) {
1797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1798 "Invalid RID value provided.");
1799 }
1800
Amit Hilbuchaa584152019-02-06 17:09:52 -08001801 if (absl::c_any_of(init.send_encodings,
1802 [](const RtpEncodingParameters& encoding) {
1803 return encoding.ssrc.has_value();
1804 })) {
1805 LOG_AND_RETURN_ERROR(
1806 RTCErrorType::UNSUPPORTED_PARAMETER,
1807 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001808 }
1809
1810 RtpParameters parameters;
1811 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001812
1813 // Encodings are dropped from the tail if too many are provided.
1814 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1815 parameters.encodings.erase(
1816 parameters.encodings.begin() + kMaxSimulcastStreams,
1817 parameters.encodings.end());
1818 }
1819
1820 // Single RID should be removed.
1821 if (parameters.encodings.size() == 1 &&
1822 !parameters.encodings[0].rid.empty()) {
1823 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1824 parameters.encodings[0].rid.clear();
1825 }
1826
1827 // If RIDs were not provided, they are generated for simulcast scenario.
1828 if (parameters.encodings.size() > 1 && num_rids == 0) {
1829 rtc::UniqueStringGenerator rid_generator;
1830 for (RtpEncodingParameters& encoding : parameters.encodings) {
1831 encoding.rid = rid_generator();
1832 }
1833 }
1834
Florent Castelli892acf02018-10-01 22:47:20 +02001835 if (UnimplementedRtpParameterHasValue(parameters)) {
1836 LOG_AND_RETURN_ERROR(
1837 RTCErrorType::UNSUPPORTED_PARAMETER,
1838 "Attempted to set an unimplemented parameter of RtpParameters.");
1839 }
Steve Anton9158ef62017-11-27 13:01:52 -08001840
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001841 auto result = cricket::CheckRtpParametersValues(parameters);
1842 if (!result.ok()) {
1843 LOG_AND_RETURN_ERROR(result.type(), result.message());
1844 }
1845
Steve Anton3d954a62018-04-02 11:27:23 -07001846 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1847 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001848 // Set the sender ID equal to the track ID if the track is specified unless
1849 // that sender ID is already in use.
1850 std::string sender_id =
1851 (track && !FindSenderById(track->id()) ? track->id()
1852 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001853 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001854 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001855 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1856 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1857 transceiver->internal()->set_direction(init.direction);
1858
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001859 if (update_negotiation_needed) {
1860 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001861 }
Steve Antonf9381f02017-12-14 10:23:57 -08001862
1863 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1864}
1865
Steve Anton02ee47c2018-01-10 16:26:06 -08001866rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1867PeerConnection::CreateSender(
1868 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001869 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001870 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001871 const std::vector<std::string>& stream_ids,
1872 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001873 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001874 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001875 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1876 RTC_DCHECK(!track ||
1877 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1878 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1879 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001880 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001881 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001882 } else {
1883 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1884 RTC_DCHECK(!track ||
1885 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1886 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001887 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001888 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001889 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001890 bool set_track_succeeded = sender->SetTrack(track);
1891 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001892 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001893 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001894 return sender;
1895}
1896
1897rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1898PeerConnection::CreateReceiver(cricket::MediaType media_type,
1899 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001900 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1901 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001902 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001903 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001904 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1905 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001906 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001907 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001908 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001909 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001910 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1911 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001912 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001913 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001914 return receiver;
1915}
1916
1917rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1918PeerConnection::CreateAndAddTransceiver(
1919 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1920 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1921 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001922 // Ensure that the new sender does not have an ID that is already in use by
1923 // another sender.
1924 // Allow receiver IDs to conflict since those come from remote SDP (which
1925 // could be invalid, but should not cause a crash).
1926 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001927 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001928 signaling_thread(),
1929 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001930 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001931 transceiver->internal()->SignalNegotiationNeeded.connect(
1932 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001933 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001934}
1935
Steve Anton52d86772018-02-20 15:48:12 -08001936void PeerConnection::OnNegotiationNeeded() {
1937 RTC_DCHECK_RUN_ON(signaling_thread());
1938 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001939 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001940}
1941
deadbeeffac06552015-11-25 11:26:01 -08001942rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001943 const std::string& kind,
1944 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001945 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001946 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1947 "Plan SdpSemantics. Please use AddTransceiver "
1948 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001949 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001950 if (IsClosed()) {
1951 return nullptr;
1952 }
Steve Anton4171afb2017-11-20 10:20:22 -08001953
Seth Hampson5b4f0752018-04-02 16:31:36 -07001954 // Internally we need to have one stream with Plan B semantics, so we
1955 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001956 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001957 if (stream_id.empty()) {
1958 stream_ids.push_back(rtc::CreateRandomUuid());
1959 RTC_LOG(LS_INFO)
1960 << "No stream_id specified for sender. Generated stream ID: "
1961 << stream_ids[0];
1962 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001963 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001964 }
1965
Steve Anton4171afb2017-11-20 10:20:22 -08001966 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001967 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001968 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001969 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001970 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001971 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001972 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001973 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001974 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001975 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001976 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001977 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001978 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001979 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001980 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001981 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001982 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001983 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001984 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001985 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001986 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001987
deadbeefe1f9d832016-01-14 15:35:42 -08001988 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001989}
1990
deadbeef70ab1a12015-09-28 16:53:55 -07001991std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1992 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001993 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001994 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001995 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001996 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001997 }
1998 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001999}
2000
Steve Anton4171afb2017-11-20 10:20:22 -08002001std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
2002PeerConnection::GetSendersInternal() const {
2003 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
2004 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002005 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08002006 auto senders = transceiver->internal()->senders();
2007 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
2008 }
2009 return all_senders;
2010}
2011
deadbeef70ab1a12015-09-28 16:53:55 -07002012std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
2013PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01002014 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07002015 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08002016 for (const auto& receiver : GetReceiversInternal()) {
2017 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07002018 }
2019 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07002020}
2021
Steve Anton4171afb2017-11-20 10:20:22 -08002022std::vector<
2023 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2024PeerConnection::GetReceiversInternal() const {
2025 std::vector<
2026 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2027 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002028 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08002029 auto receivers = transceiver->internal()->receivers();
2030 all_receivers.insert(all_receivers.end(), receivers.begin(),
2031 receivers.end());
2032 }
2033 return all_receivers;
2034}
2035
Steve Anton9158ef62017-11-27 13:01:52 -08002036std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2037PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01002038 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08002039 RTC_CHECK(IsUnifiedPlan())
2040 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08002041 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002042 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08002043 all_transceivers.push_back(transceiver);
2044 }
2045 return all_transceivers;
2046}
2047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002049 MediaStreamTrackInterface* track,
2050 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002051 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002052 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08002053 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002054 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002055 return false;
2056 }
2057
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002058 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07002059 // The StatsCollector is used to tell if a track is valid because it may
2060 // remember tracks that the PeerConnection previously removed.
2061 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002062 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
2063 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07002064 return false;
2065 }
Steve Antonad182762018-09-05 20:22:40 +00002066 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
2067 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002068 return true;
2069}
2070
hbos74e1a4f2016-09-15 23:33:01 -07002071void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01002072 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002073 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07002074 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01002075 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07002076 stats_collector_->GetStatsReport(callback);
2077}
2078
Henrik Boström1df1bf82018-03-20 13:24:20 +01002079void PeerConnection::GetStats(
2080 rtc::scoped_refptr<RtpSenderInterface> selector,
2081 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2082 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002083 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002084 RTC_DCHECK(callback);
2085 RTC_DCHECK(stats_collector_);
2086 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
2087 if (selector) {
2088 for (const auto& proxy_transceiver : transceivers_) {
2089 for (const auto& proxy_sender :
2090 proxy_transceiver->internal()->senders()) {
2091 if (proxy_sender == selector) {
2092 internal_sender = proxy_sender->internal();
2093 break;
2094 }
2095 }
2096 if (internal_sender)
2097 break;
2098 }
2099 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002100 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01002101 // belong to the PeerConnection (in Plan B, senders can be removed from the
2102 // PeerConnection). This means that "all the stats objects representing the
2103 // selector" is an empty set. Invoking GetStatsReport() with a null selector
2104 // produces an empty stats report.
2105 stats_collector_->GetStatsReport(internal_sender, callback);
2106}
2107
2108void PeerConnection::GetStats(
2109 rtc::scoped_refptr<RtpReceiverInterface> selector,
2110 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2111 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002112 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002113 RTC_DCHECK(callback);
2114 RTC_DCHECK(stats_collector_);
2115 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
2116 if (selector) {
2117 for (const auto& proxy_transceiver : transceivers_) {
2118 for (const auto& proxy_receiver :
2119 proxy_transceiver->internal()->receivers()) {
2120 if (proxy_receiver == selector) {
2121 internal_receiver = proxy_receiver->internal();
2122 break;
2123 }
2124 }
2125 if (internal_receiver)
2126 break;
2127 }
2128 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002129 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01002130 // not belong to the PeerConnection (in Plan B, receivers can be removed from
2131 // the PeerConnection). This means that "all the stats objects representing
2132 // the selector" is an empty set. Invoking GetStatsReport() with a null
2133 // selector produces an empty stats report.
2134 stats_collector_->GetStatsReport(internal_receiver, callback);
2135}
2136
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002138 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139 return signaling_state_;
2140}
2141
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142PeerConnectionInterface::IceConnectionState
2143PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002144 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145 return ice_connection_state_;
2146}
2147
Alex Loiko9289eda2018-11-23 16:18:59 +00002148PeerConnectionInterface::IceConnectionState
2149PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002150 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00002151 return standardized_ice_connection_state_;
2152}
2153
Jonas Olsson635474e2018-10-18 15:58:17 +02002154PeerConnectionInterface::PeerConnectionState
2155PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002156 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002157 return connection_state_;
2158}
2159
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160PeerConnectionInterface::IceGatheringState
2161PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002162 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 return ice_gathering_state_;
2164}
2165
Yves Gerey665174f2018-06-19 15:03:05 +02002166rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002167 const std::string& label,
2168 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002169 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002170 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002171
deadbeefab9b2d12015-10-14 11:33:11 -07002172 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002173
kwibergd1fe2812016-04-27 06:47:29 -07002174 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002175 if (config) {
2176 internal_config.reset(new InternalDataChannelInit(*config));
2177 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002178 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002179 InternalCreateDataChannel(label, internal_config.get()));
2180 if (!channel.get()) {
2181 return nullptr;
2182 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002184 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2185 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002186 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002187 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002188 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002189 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002190 return DataChannelProxy::Create(signaling_thread(), channel.get());
2191}
2192
Henrik Boström79b69802019-07-18 11:16:56 +02002193void PeerConnection::RestartIce() {
2194 RTC_DCHECK_RUN_ON(signaling_thread());
2195 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2196 current_local_description_.get(), pending_local_description_.get());
2197 UpdateNegotiationNeeded();
2198}
2199
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002201 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002202 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002203 // Chain this operation. If asynchronous operations are pending on the chain,
2204 // this operation will be queued to be invoked, otherwise the contents of the
2205 // lambda will execute immediately.
2206 operations_chain_->ChainOperation(
2207 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2208 observer_refptr =
2209 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2210 options](std::function<void()> operations_chain_callback) {
2211 // Abort early if |this_weak_ptr| is no longer valid.
2212 if (!this_weak_ptr) {
2213 observer_refptr->OnFailure(
2214 RTCError(RTCErrorType::INTERNAL_ERROR,
2215 "CreateOffer failed because the session was shut down"));
2216 operations_chain_callback();
2217 return;
2218 }
2219 // The operation completes asynchronously when the wrapper is invoked.
2220 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2221 observer_wrapper(new rtc::RefCountedObject<
2222 CreateSessionDescriptionObserverOperationWrapper>(
2223 std::move(observer_refptr),
2224 std::move(operations_chain_callback)));
2225 this_weak_ptr->DoCreateOffer(options, observer_wrapper);
2226 });
2227}
2228
2229void PeerConnection::DoCreateOffer(
2230 const RTCOfferAnswerOptions& options,
2231 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2232 RTC_DCHECK_RUN_ON(signaling_thread());
2233 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002234
nisse7ce109a2017-01-31 00:57:56 -08002235 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002236 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002237 return;
2238 }
deadbeefab9b2d12015-10-14 11:33:11 -07002239
Steve Anton8d3444d2017-10-20 15:30:51 -07002240 if (IsClosed()) {
2241 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002242 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002243 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002244 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002245 return;
2246 }
2247
Steve Anton25ca0ac2019-06-25 10:40:48 -07002248 // If a session error has occurred the PeerConnection is in a possibly
2249 // inconsistent state so fail right away.
2250 if (session_error() != SessionError::kNone) {
2251 std::string error_message = GetSessionErrorMsg();
2252 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2253 PostCreateSessionDescriptionFailure(
2254 observer,
2255 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2256 return;
2257 }
2258
zhihuang1c378ed2017-08-17 14:10:50 -07002259 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002260 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002261 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002262 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002263 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002264 return;
2265 }
2266
Steve Anton22da89f2018-01-25 13:58:07 -08002267 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2268 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2269 if (IsUnifiedPlan()) {
2270 RTCError error = HandleLegacyOfferOptions(options);
2271 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002272 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002273 return;
2274 }
2275 }
2276
zhihuang1c378ed2017-08-17 14:10:50 -07002277 cricket::MediaSessionOptions session_options;
2278 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002279 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002280}
2281
Steve Anton22da89f2018-01-25 13:58:07 -08002282RTCError PeerConnection::HandleLegacyOfferOptions(
2283 const RTCOfferAnswerOptions& options) {
2284 RTC_DCHECK(IsUnifiedPlan());
2285
2286 if (options.offer_to_receive_audio == 0) {
2287 RemoveRecvDirectionFromReceivingTransceiversOfType(
2288 cricket::MEDIA_TYPE_AUDIO);
2289 } else if (options.offer_to_receive_audio == 1) {
2290 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2291 } else if (options.offer_to_receive_audio > 1) {
2292 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2293 "offer_to_receive_audio > 1 is not supported.");
2294 }
2295
2296 if (options.offer_to_receive_video == 0) {
2297 RemoveRecvDirectionFromReceivingTransceiversOfType(
2298 cricket::MEDIA_TYPE_VIDEO);
2299 } else if (options.offer_to_receive_video == 1) {
2300 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2301 } else if (options.offer_to_receive_video > 1) {
2302 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2303 "offer_to_receive_video > 1 is not supported.");
2304 }
2305
2306 return RTCError::OK();
2307}
2308
2309void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2310 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002311 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002312 RtpTransceiverDirection new_direction =
2313 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2314 if (new_direction != transceiver->direction()) {
2315 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2316 << " transceiver (MID="
2317 << transceiver->mid().value_or("<not set>") << ") from "
2318 << RtpTransceiverDirectionToString(
2319 transceiver->direction())
2320 << " to "
2321 << RtpTransceiverDirectionToString(new_direction)
2322 << " since CreateOffer specified offer_to_receive=0";
2323 transceiver->internal()->set_direction(new_direction);
2324 }
Steve Anton22da89f2018-01-25 13:58:07 -08002325 }
2326}
2327
2328void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2329 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002330 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002331 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002332 RTC_LOG(LS_INFO)
2333 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2334 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002335 RtpTransceiverInit init;
2336 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002337 AddTransceiver(media_type, nullptr, init,
2338 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002339 }
2340}
2341
2342std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2343PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2344 std::vector<
2345 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2346 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002347 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002348 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002349 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2350 receiving_transceivers.push_back(transceiver);
2351 }
2352 }
2353 return receiving_transceivers;
2354}
2355
htaa2a49d92016-03-04 02:51:39 -08002356void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2357 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002358 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002359 // Chain this operation. If asynchronous operations are pending on the chain,
2360 // this operation will be queued to be invoked, otherwise the contents of the
2361 // lambda will execute immediately.
2362 operations_chain_->ChainOperation(
2363 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2364 observer_refptr =
2365 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2366 options](std::function<void()> operations_chain_callback) {
2367 // Abort early if |this_weak_ptr| is no longer valid.
2368 if (!this_weak_ptr) {
2369 observer_refptr->OnFailure(RTCError(
2370 RTCErrorType::INTERNAL_ERROR,
2371 "CreateAnswer failed because the session was shut down"));
2372 operations_chain_callback();
2373 return;
2374 }
2375 // The operation completes asynchronously when the wrapper is invoked.
2376 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2377 observer_wrapper(new rtc::RefCountedObject<
2378 CreateSessionDescriptionObserverOperationWrapper>(
2379 std::move(observer_refptr),
2380 std::move(operations_chain_callback)));
2381 this_weak_ptr->DoCreateAnswer(options, observer_wrapper);
2382 });
2383}
2384
2385void PeerConnection::DoCreateAnswer(
2386 const RTCOfferAnswerOptions& options,
2387 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2388 RTC_DCHECK_RUN_ON(signaling_thread());
2389 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002390 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002391 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002392 return;
2393 }
2394
Steve Anton25ca0ac2019-06-25 10:40:48 -07002395 // If a session error has occurred the PeerConnection is in a possibly
2396 // inconsistent state so fail right away.
2397 if (session_error() != SessionError::kNone) {
2398 std::string error_message = GetSessionErrorMsg();
2399 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2400 PostCreateSessionDescriptionFailure(
2401 observer,
2402 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2403 return;
2404 }
2405
Steve Antondffead82018-02-06 10:31:29 -08002406 if (!(signaling_state_ == kHaveRemoteOffer ||
2407 signaling_state_ == kHaveLocalPrAnswer)) {
2408 std::string error =
2409 "PeerConnection cannot create an answer in a state other than "
2410 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002411 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002412 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002413 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002414 return;
2415 }
2416
Steve Antondffead82018-02-06 10:31:29 -08002417 // The remote description should be set if we're in the right state.
2418 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002419
Steve Anton22da89f2018-01-25 13:58:07 -08002420 if (IsUnifiedPlan()) {
2421 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2422 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2423 "supported with Unified Plan semantics. Use the "
2424 "RtpTransceiver API instead.";
2425 }
2426 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2427 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2428 "supported with Unified Plan semantics. Use the "
2429 "RtpTransceiver API instead.";
2430 }
2431 }
2432
htaa2a49d92016-03-04 02:51:39 -08002433 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002434 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002435
Steve Antond25da372017-11-06 14:50:29 -08002436 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002437}
2438
2439void PeerConnection::SetLocalDescription(
2440 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002441 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002442 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002443 // Chain this operation. If asynchronous operations are pending on the chain,
2444 // this operation will be queued to be invoked, otherwise the contents of the
2445 // lambda will execute immediately.
2446 operations_chain_->ChainOperation(
2447 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2448 observer_refptr =
2449 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2450 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2451 std::function<void()> operations_chain_callback) mutable {
2452 // Abort early if |this_weak_ptr| is no longer valid.
2453 if (!this_weak_ptr) {
2454 // For consistency with DoSetLocalDescription(), we DO NOT inform the
2455 // |observer_refptr| that the operation failed in this case.
2456 // TODO(hbos): If/when we process SLD messages in ~PeerConnection,
2457 // the consistent thing would be to inform the observer here.
2458 operations_chain_callback();
2459 return;
2460 }
2461 this_weak_ptr->DoSetLocalDescription(std::move(desc),
2462 std::move(observer_refptr));
2463 // DoSetLocalDescription() is currently implemented as a synchronous
2464 // operation but where the |observer|'s callbacks are invoked
2465 // asynchronously in a post to OnMessage().
2466 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 10:35:50 +01002467 // completed here (rather than in OnMessage()). This ensures that
2468 // subsequent offer/answer operations can start immediately (without
2469 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 12:09:49 +01002470 operations_chain_callback();
2471 });
2472}
Steve Anton8a006912017-12-04 15:25:56 -08002473
Henrik Boström4e196702019-10-30 10:35:50 +01002474void PeerConnection::SetLocalDescription(
2475 SetSessionDescriptionObserver* observer) {
2476 RTC_DCHECK_RUN_ON(signaling_thread());
2477 // The |create_sdp_observer| handles performing DoSetLocalDescription() with
2478 // the resulting description as well as completing the operation.
2479 rtc::scoped_refptr<ImplicitCreateSessionDescriptionObserver>
2480 create_sdp_observer(
2481 new rtc::RefCountedObject<ImplicitCreateSessionDescriptionObserver>(
2482 weak_ptr_factory_.GetWeakPtr(),
2483 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer)));
2484 // Chain this operation. If asynchronous operations are pending on the chain,
2485 // this operation will be queued to be invoked, otherwise the contents of the
2486 // lambda will execute immediately.
2487 operations_chain_->ChainOperation(
2488 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2489 create_sdp_observer](std::function<void()> operations_chain_callback) {
2490 // The |create_sdp_observer| is responsible for completing the
2491 // operation.
2492 create_sdp_observer->SetOperationCompleteCallback(
2493 std::move(operations_chain_callback));
2494 // Abort early if |this_weak_ptr| is no longer valid. This triggers the
2495 // same code path as if DoCreateOffer() or DoCreateAnswer() failed.
2496 if (!this_weak_ptr) {
2497 create_sdp_observer->OnFailure(RTCError(
2498 RTCErrorType::INTERNAL_ERROR,
2499 "SetLocalDescription failed because the session was shut down"));
2500 return;
2501 }
2502 switch (this_weak_ptr->signaling_state()) {
2503 case PeerConnectionInterface::kStable:
2504 case PeerConnectionInterface::kHaveLocalOffer:
2505 case PeerConnectionInterface::kHaveRemotePrAnswer:
2506 // TODO(hbos): If [LastCreatedOffer] exists and still represents the
2507 // current state of the system, use that instead of creating another
2508 // offer.
2509 this_weak_ptr->DoCreateOffer(RTCOfferAnswerOptions(),
2510 create_sdp_observer);
2511 break;
2512 case PeerConnectionInterface::kHaveLocalPrAnswer:
2513 case PeerConnectionInterface::kHaveRemoteOffer:
2514 // TODO(hbos): If [LastCreatedAnswer] exists and still represents
2515 // the current state of the system, use that instead of creating
2516 // another answer.
2517 this_weak_ptr->DoCreateAnswer(RTCOfferAnswerOptions(),
2518 create_sdp_observer);
2519 break;
2520 case PeerConnectionInterface::kClosed:
2521 create_sdp_observer->OnFailure(RTCError(
2522 RTCErrorType::INVALID_STATE,
2523 "SetLocalDescription called when PeerConnection is closed."));
2524 break;
2525 }
2526 });
2527}
2528
Henrik Boströma3728d32019-10-28 12:09:49 +01002529void PeerConnection::DoSetLocalDescription(
2530 std::unique_ptr<SessionDescriptionInterface> desc,
2531 rtc::scoped_refptr<SetSessionDescriptionObserver> observer) {
2532 RTC_DCHECK_RUN_ON(signaling_thread());
2533 TRACE_EVENT0("webrtc", "PeerConnection::DoSetLocalDescription");
Steve Anton80dd7b52018-02-16 17:08:42 -08002534
nisse7ce109a2017-01-31 00:57:56 -08002535 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002536 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537 return;
2538 }
Steve Anton8a006912017-12-04 15:25:56 -08002539
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002540 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002541 PostSetSessionDescriptionFailure(
2542 observer,
2543 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002544 return;
2545 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002546
Steve Anton80dd7b52018-02-16 17:08:42 -08002547 // If a session error has occurred the PeerConnection is in a possibly
2548 // inconsistent state so fail right away.
2549 if (session_error() != SessionError::kNone) {
2550 std::string error_message = GetSessionErrorMsg();
2551 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002552 PostSetSessionDescriptionFailure(
2553 observer,
2554 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002555 return;
2556 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002557
Eldar Rello5ab79e62019-10-09 18:29:44 +03002558 // For SLD we support only explicit rollback.
2559 if (desc->GetType() == SdpType::kRollback) {
2560 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002561 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002562 if (error.ok()) {
2563 PostSetSessionDescriptionSuccess(observer);
2564 } else {
2565 PostSetSessionDescriptionFailure(observer, std::move(error));
2566 }
2567 } else {
2568 PostSetSessionDescriptionFailure(
2569 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2570 "Rollback not supported in Plan B"));
2571 }
2572 return;
2573 }
2574
Steve Anton80dd7b52018-02-16 17:08:42 -08002575 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2576 if (!error.ok()) {
2577 std::string error_message = GetSetDescriptionErrorMessage(
2578 cricket::CS_LOCAL, desc->GetType(), error);
2579 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002580 PostSetSessionDescriptionFailure(
2581 observer,
2582 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002583 return;
2584 }
2585
2586 // Grab the description type before moving ownership to ApplyLocalDescription,
2587 // which may destroy it before returning.
2588 const SdpType type = desc->GetType();
2589
2590 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002591 // |desc| may be destroyed at this point.
2592
2593 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002594 // If ApplyLocalDescription fails, the PeerConnection could be in an
2595 // inconsistent state, so act conservatively here and set the session error
2596 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2597 SetSessionError(SessionError::kContent, error.message());
2598 std::string error_message =
2599 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2600 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002601 PostSetSessionDescriptionFailure(
2602 observer,
2603 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002604 return;
2605 }
Steve Anton8a006912017-12-04 15:25:56 -08002606 RTC_DCHECK(local_description());
2607
2608 PostSetSessionDescriptionSuccess(observer);
2609
Steve Antonad182762018-09-05 20:22:40 +00002610 // MaybeStartGathering needs to be called after posting
2611 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2612 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002613 transport_controller_->MaybeStartGathering();
2614
Steve Antona3a92c22017-12-07 10:27:41 -08002615 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002616 // TODO(deadbeef): We already had to hop to the network thread for
2617 // MaybeStartGathering...
2618 network_thread()->Invoke<void>(
2619 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2620 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002621 // Make UMA notes about what was agreed to.
2622 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002623 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002624
2625 if (IsUnifiedPlan()) {
2626 bool was_negotiation_needed = is_negotiation_needed_;
2627 UpdateNegotiationNeeded();
2628 if (signaling_state() == kStable && was_negotiation_needed &&
2629 is_negotiation_needed_) {
2630 Observer()->OnRenegotiationNeeded();
2631 }
2632 }
2633
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002634 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002635}
2636
2637RTCError PeerConnection::ApplyLocalDescription(
2638 std::unique_ptr<SessionDescriptionInterface> desc) {
2639 RTC_DCHECK_RUN_ON(signaling_thread());
2640 RTC_DCHECK(desc);
2641
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642 // Update stats here so that we have the most recent stats for tracks and
2643 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002644 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002645
Steve Antondcc3c022017-12-22 16:02:54 -08002646 // Take a reference to the old local description since it's used below to
2647 // compare against the new local description. When setting the new local
2648 // description, grab ownership of the replaced session description in case it
2649 // is the same as |old_local_description|, to keep it alive for the duration
2650 // of the method.
2651 const SessionDescriptionInterface* old_local_description =
2652 local_description();
2653 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002654 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002655 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002656 replaced_local_description = pending_local_description_
2657 ? std::move(pending_local_description_)
2658 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002659 current_local_description_ = std::move(desc);
2660 pending_local_description_ = nullptr;
2661 current_remote_description_ = std::move(pending_remote_description_);
2662 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002663 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002664 pending_local_description_ = std::move(desc);
2665 }
2666 // The session description to apply now must be accessed by
2667 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002668 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002669
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002670 // Report statistics about any use of simulcast.
2671 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2672 *local_description()->description());
2673
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002674 if (!is_caller_) {
2675 if (remote_description()) {
2676 // Remote description was applied first, so this PC is the callee.
2677 is_caller_ = false;
2678 } else {
2679 // Local description is applied first, so this PC is the caller.
2680 is_caller_ = true;
2681 }
2682 }
2683
Zhi Huange830e682018-03-30 10:48:35 -07002684 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2685 if (!error.ok()) {
2686 return error;
2687 }
2688
Steve Antondcc3c022017-12-22 16:02:54 -08002689 if (IsUnifiedPlan()) {
2690 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002691 cricket::CS_LOCAL, *local_description(), old_local_description,
2692 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002693 if (!error.ok()) {
2694 return error;
2695 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002696 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2697 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002698 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002699 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2700 // Note that code paths that don't set MID won't be able to use
2701 // information about DTLS transports.
2702 if (transceiver->mid()) {
2703 auto dtls_transport =
2704 LookupDtlsTransportByMidInternal(*transceiver->mid());
2705 transceiver->internal()->sender_internal()->set_transport(
2706 dtls_transport);
2707 transceiver->internal()->receiver_internal()->set_transport(
2708 dtls_transport);
2709 }
2710
Steve Antondcc3c022017-12-22 16:02:54 -08002711 const ContentInfo* content =
2712 FindMediaSectionForTransceiver(transceiver, local_description());
2713 if (!content) {
2714 continue;
2715 }
2716 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002717 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2718 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002719 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002720 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2721 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2722 // "recvonly", process the removal of a remote track for the media
2723 // description, given transceiver, removeList, and muteTracks.
2724 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2725 (transceiver->internal()->fired_direction() &&
2726 RtpTransceiverDirectionHasRecv(
2727 *transceiver->internal()->fired_direction()))) {
2728 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2729 &removed_streams);
2730 }
2731 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2732 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002733 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002734 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002735 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002736 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002737 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002738 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002739 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002740 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002741 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002742 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002743 }
2744 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002745 // Media channels will be created only when offer is set. These may use new
2746 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002747 if (type == SdpType::kOffer) {
2748 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2749 // description is applied. Restore back to old description.
2750 RTCError error = CreateChannels(*local_description()->description());
2751 if (!error.ok()) {
2752 return error;
2753 }
2754 }
Steve Antondcc3c022017-12-22 16:02:54 -08002755 // Remove unused channels if MediaContentDescription is rejected.
2756 RemoveUnusedChannels(local_description()->description());
2757 }
Steve Anton8a006912017-12-04 15:25:56 -08002758
Zhi Huange830e682018-03-30 10:48:35 -07002759 error = UpdateSessionState(type, cricket::CS_LOCAL,
2760 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002761 if (!error.ok()) {
2762 return error;
2763 }
Steve Antondcc3c022017-12-22 16:02:54 -08002764
Steve Anton8a006912017-12-04 15:25:56 -08002765 if (remote_description()) {
2766 // Now that we have a local description, we can push down remote candidates.
2767 UseCandidatesInSessionDescription(remote_description());
2768 }
2769
2770 pending_ice_restarts_.clear();
2771 if (session_error() != SessionError::kNone) {
2772 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2773 }
2774
deadbeefab9b2d12015-10-14 11:33:11 -07002775 // If setting the description decided our SSL role, allocate any necessary
2776 // SCTP sids.
2777 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002778 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002779 AllocateSctpSids(role);
2780 }
2781
Steve Antond3679212018-01-17 17:41:02 -08002782 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002783 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002784 const ContentInfo* content =
2785 FindMediaSectionForTransceiver(transceiver, local_description());
2786 if (!content) {
2787 continue;
2788 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002789 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2790 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002791 // 0 is a special value meaning "this sender has no associated send
2792 // stream". Need to call this so the sender won't attempt to configure
2793 // a no longer existing stream and run into DCHECKs in the lower
2794 // layers.
2795 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002796 } else {
2797 // Get the StreamParams from the channel which could generate SSRCs.
2798 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002799 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002800 streams[0].stream_ids());
2801 transceiver->internal()->sender_internal()->SetSsrc(
2802 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002803 }
2804 }
2805 } else {
2806 // Plan B semantics.
2807
Steve Antondcc3c022017-12-22 16:02:54 -08002808 // Update state and SSRC of local MediaStreams and DataChannels based on the
2809 // local session description.
2810 const cricket::ContentInfo* audio_content =
2811 GetFirstAudioContent(local_description()->description());
2812 if (audio_content) {
2813 if (audio_content->rejected) {
2814 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2815 } else {
2816 const cricket::AudioContentDescription* audio_desc =
2817 audio_content->media_description()->as_audio();
2818 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2819 }
deadbeeffaac4972015-11-12 15:33:07 -08002820 }
deadbeefab9b2d12015-10-14 11:33:11 -07002821
Steve Antondcc3c022017-12-22 16:02:54 -08002822 const cricket::ContentInfo* video_content =
2823 GetFirstVideoContent(local_description()->description());
2824 if (video_content) {
2825 if (video_content->rejected) {
2826 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2827 } else {
2828 const cricket::VideoContentDescription* video_desc =
2829 video_content->media_description()->as_video();
2830 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2831 }
deadbeeffaac4972015-11-12 15:33:07 -08002832 }
deadbeefab9b2d12015-10-14 11:33:11 -07002833 }
2834
2835 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002836 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002837 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002838 const cricket::RtpDataContentDescription* rtp_data_desc =
2839 data_content->media_description()->as_rtp_data();
2840 // rtp_data_desc will be null if this is an SCTP description.
2841 if (rtp_data_desc) {
2842 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002843 }
2844 }
2845
Henrik Boström79b69802019-07-18 11:16:56 +02002846 if (type == SdpType::kAnswer &&
2847 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2848 *current_local_description_)) {
2849 local_ice_credentials_to_replace_->ClearIceCredentials();
2850 }
2851
Steve Anton8a006912017-12-04 15:25:56 -08002852 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853}
2854
Steve Anton06817cd2018-12-18 15:55:30 -08002855// The SDP parser used to populate these values by default for the 'content
2856// name' if an a=mid line was absent.
2857static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2858 switch (media_type) {
2859 case cricket::MEDIA_TYPE_AUDIO:
2860 return cricket::CN_AUDIO;
2861 case cricket::MEDIA_TYPE_VIDEO:
2862 return cricket::CN_VIDEO;
2863 case cricket::MEDIA_TYPE_DATA:
2864 return cricket::CN_DATA;
2865 }
2866 RTC_NOTREACHED();
2867 return "";
2868}
2869
2870void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002871 cricket::SessionDescription* new_remote_description) {
2872 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002873 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002874 const cricket::ContentInfos& local_contents =
2875 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002876 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002877 const cricket::ContentInfos& remote_contents =
2878 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002879 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002880 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2881 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002882 if (!content.name.empty()) {
2883 continue;
2884 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002885 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002886 absl::string_view source_explanation;
2887 if (IsUnifiedPlan()) {
2888 if (i < local_contents.size()) {
2889 new_mid = local_contents[i].name;
2890 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002891 } else if (i < remote_contents.size()) {
2892 new_mid = remote_contents[i].name;
2893 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002894 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002895 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002896 source_explanation = "generated just now";
2897 }
2898 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002899 new_mid = std::string(
2900 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002901 source_explanation = "to match pre-existing behavior";
2902 }
Steve Antond7180cc2019-02-07 10:44:53 -08002903 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002904 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002905 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002906 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2907 << " is missing an a=mid line. Filling in the value '"
2908 << new_mid << "' " << source_explanation << ".";
2909 }
2910}
2911
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002913 SetSessionDescriptionObserver* observer,
Henrik Boströma3728d32019-10-28 12:09:49 +01002914 SessionDescriptionInterface* desc_ptr) {
2915 RTC_DCHECK_RUN_ON(signaling_thread());
2916 // Chain this operation. If asynchronous operations are pending on the chain,
2917 // this operation will be queued to be invoked, otherwise the contents of the
2918 // lambda will execute immediately.
2919 operations_chain_->ChainOperation(
2920 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2921 observer_refptr =
2922 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2923 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2924 std::function<void()> operations_chain_callback) mutable {
2925 // Abort early if |this_weak_ptr| is no longer valid.
2926 if (!this_weak_ptr) {
2927 // For consistency with SetRemoteDescriptionObserverAdapter, we DO NOT
2928 // inform the |observer_refptr| that the operation failed in this
2929 // case.
2930 // TODO(hbos): If/when we process SRD messages in ~PeerConnection,
2931 // the consistent thing would be to inform the observer here.
2932 operations_chain_callback();
2933 return;
2934 }
2935 this_weak_ptr->DoSetRemoteDescription(
2936 std::move(desc),
2937 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2938 new SetRemoteDescriptionObserverAdapter(
2939 this_weak_ptr.get(), std::move(observer_refptr))));
2940 // DoSetRemoteDescription() is currently implemented as a synchronous
2941 // operation but where SetRemoteDescriptionObserverAdapter ensures that
2942 // the |observer|'s callbacks are invoked asynchronously in a post to
2943 // OnMessage().
2944 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 10:35:50 +01002945 // completed here (rather than in OnMessage()). This ensures that
2946 // subsequent offer/answer operations can start immediately (without
2947 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 12:09:49 +01002948 operations_chain_callback();
2949 });
Henrik Boström31638672017-11-23 17:48:32 +01002950}
2951
2952void PeerConnection::SetRemoteDescription(
2953 std::unique_ptr<SessionDescriptionInterface> desc,
2954 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002955 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002956 // Chain this operation. If asynchronous operations are pending on the chain,
2957 // this operation will be queued to be invoked, otherwise the contents of the
2958 // lambda will execute immediately.
2959 operations_chain_->ChainOperation(
2960 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer,
2961 desc = std::move(desc)](
2962 std::function<void()> operations_chain_callback) mutable {
2963 // Abort early if |this_weak_ptr| is no longer valid.
2964 if (!this_weak_ptr) {
2965 // For consistency with DoSetRemoteDescription(), we DO inform the
2966 // |observer| that the operation failed in this case.
2967 observer->OnSetRemoteDescriptionComplete(RTCError(
2968 RTCErrorType::INVALID_STATE,
2969 "Failed to set remote offer sdp: failed because the session was "
2970 "shut down"));
2971 operations_chain_callback();
2972 return;
2973 }
2974 this_weak_ptr->DoSetRemoteDescription(std::move(desc),
2975 std::move(observer));
2976 // DoSetRemoteDescription() is currently implemented as a synchronous
2977 // operation. The |observer| will already have been informed that it
2978 // completed, and we can mark this operation as complete without any
2979 // loose ends.
2980 operations_chain_callback();
2981 });
2982}
2983
2984void PeerConnection::DoSetRemoteDescription(
2985 std::unique_ptr<SessionDescriptionInterface> desc,
2986 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
2987 RTC_DCHECK_RUN_ON(signaling_thread());
2988 TRACE_EVENT0("webrtc", "PeerConnection::DoSetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002989
nisse7ce109a2017-01-31 00:57:56 -08002990 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002991 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 return;
2993 }
Steve Anton8a006912017-12-04 15:25:56 -08002994
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002996 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002997 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 return;
2999 }
Steve Anton8d3444d2017-10-20 15:30:51 -07003000
Steve Anton80dd7b52018-02-16 17:08:42 -08003001 // If a session error has occurred the PeerConnection is in a possibly
3002 // inconsistent state so fail right away.
3003 if (session_error() != SessionError::kNone) {
3004 std::string error_message = GetSessionErrorMsg();
3005 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
3006 observer->OnSetRemoteDescriptionComplete(
3007 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
3008 return;
3009 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003010 if (IsUnifiedPlan()) {
3011 if (configuration_.enable_implicit_rollback) {
3012 if (desc->GetType() == SdpType::kOffer &&
3013 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 23:01:31 +03003014 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03003015 }
3016 }
3017 // Explicit rollback.
3018 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 23:01:31 +03003019 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 18:29:44 +03003020 return;
3021 }
3022 } else if (desc->GetType() == SdpType::kRollback) {
3023 observer->OnSetRemoteDescriptionComplete(
3024 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
3025 "Rollback not supported in Plan B"));
3026 return;
3027 }
Steve Antonba42e992018-04-09 14:10:01 -07003028 if (desc->GetType() == SdpType::kOffer) {
3029 // Report to UMA the format of the received offer.
3030 ReportSdpFormatReceived(*desc);
3031 }
3032
Steve Anton06817cd2018-12-18 15:55:30 -08003033 // Handle remote descriptions missing a=mid lines for interop with legacy end
3034 // points.
3035 FillInMissingRemoteMids(desc->description());
3036
Steve Anton80dd7b52018-02-16 17:08:42 -08003037 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08003038 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08003039 std::string error_message = GetSetDescriptionErrorMessage(
3040 cricket::CS_REMOTE, desc->GetType(), error);
3041 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08003042 observer->OnSetRemoteDescriptionComplete(
3043 RTCError(error.type(), std::move(error_message)));
3044 return;
3045 }
Steve Anton71439a62018-02-15 11:53:06 -08003046
Steve Anton80dd7b52018-02-16 17:08:42 -08003047 // Grab the description type before moving ownership to
3048 // ApplyRemoteDescription, which may destroy it before returning.
3049 const SdpType type = desc->GetType();
3050
3051 error = ApplyRemoteDescription(std::move(desc));
3052 // |desc| may be destroyed at this point.
3053
3054 if (!error.ok()) {
3055 // If ApplyRemoteDescription fails, the PeerConnection could be in an
3056 // inconsistent state, so act conservatively here and set the session error
3057 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
3058 SetSessionError(SessionError::kContent, error.message());
3059 std::string error_message =
3060 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
3061 RTC_LOG(LS_ERROR) << error_message;
3062 observer->OnSetRemoteDescriptionComplete(
3063 RTCError(error.type(), std::move(error_message)));
3064 return;
3065 }
3066 RTC_DCHECK(remote_description());
3067
3068 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08003069 // TODO(deadbeef): We already had to hop to the network thread for
3070 // MaybeStartGathering...
3071 network_thread()->Invoke<void>(
3072 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3073 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01003074 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08003075 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08003076 }
3077
Guido Urdaneta70c2db12019-04-16 12:24:14 +02003078 if (IsUnifiedPlan()) {
3079 bool was_negotiation_needed = is_negotiation_needed_;
3080 UpdateNegotiationNeeded();
3081 if (signaling_state() == kStable && was_negotiation_needed &&
3082 is_negotiation_needed_) {
3083 Observer()->OnRenegotiationNeeded();
3084 }
3085 }
3086
Steve Anton8a006912017-12-04 15:25:56 -08003087 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003088 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08003089}
3090
3091RTCError PeerConnection::ApplyRemoteDescription(
3092 std::unique_ptr<SessionDescriptionInterface> desc) {
3093 RTC_DCHECK_RUN_ON(signaling_thread());
3094 RTC_DCHECK(desc);
3095
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003096 // Update stats here so that we have the most recent stats for tracks and
3097 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003098 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08003099
Steve Antondcc3c022017-12-22 16:02:54 -08003100 // Take a reference to the old remote description since it's used below to
3101 // compare against the new remote description. When setting the new remote
3102 // description, grab ownership of the replaced session description in case it
3103 // is the same as |old_remote_description|, to keep it alive for the duration
3104 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08003105 const SessionDescriptionInterface* old_remote_description =
3106 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08003107 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08003108 SdpType type = desc->GetType();
3109 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08003110 replaced_remote_description = pending_remote_description_
3111 ? std::move(pending_remote_description_)
3112 : std::move(current_remote_description_);
3113 current_remote_description_ = std::move(desc);
3114 pending_remote_description_ = nullptr;
3115 current_local_description_ = std::move(pending_local_description_);
3116 } else {
3117 replaced_remote_description = std::move(pending_remote_description_);
3118 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003119 }
Steve Anton8a006912017-12-04 15:25:56 -08003120 // The session description to apply now must be accessed by
3121 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01003122 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003123
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003124 // Report statistics about any use of simulcast.
3125 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
3126 *remote_description()->description());
3127
Zhi Huange830e682018-03-30 10:48:35 -07003128 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
3129 if (!error.ok()) {
3130 return error;
3131 }
Steve Anton8a006912017-12-04 15:25:56 -08003132 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08003133 if (IsUnifiedPlan()) {
3134 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003135 cricket::CS_REMOTE, *remote_description(), local_description(),
3136 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08003137 if (!error.ok()) {
3138 return error;
3139 }
Steve Antondcc3c022017-12-22 16:02:54 -08003140 } else {
Zhi Huange830e682018-03-30 10:48:35 -07003141 // Media channels will be created only when offer is set. These may use new
3142 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08003143 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07003144 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08003145 // description is applied. Restore back to old description.
3146 RTCError error = CreateChannels(*remote_description()->description());
3147 if (!error.ok()) {
3148 return error;
3149 }
3150 }
Steve Antondcc3c022017-12-22 16:02:54 -08003151 // Remove unused channels if MediaContentDescription is rejected.
3152 RemoveUnusedChannels(remote_description()->description());
3153 }
Steve Anton8a006912017-12-04 15:25:56 -08003154
Zhi Huange830e682018-03-30 10:48:35 -07003155 // NOTE: Candidates allocation will be initiated only when
3156 // SetLocalDescription is called.
3157 error = UpdateSessionState(type, cricket::CS_REMOTE,
3158 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08003159 if (!error.ok()) {
3160 return error;
3161 }
3162
3163 if (local_description() &&
3164 !UseCandidatesInSessionDescription(remote_description())) {
3165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
3166 }
3167
3168 if (old_remote_description) {
3169 for (const cricket::ContentInfo& content :
3170 old_remote_description->description()->contents()) {
3171 // Check if this new SessionDescription contains new ICE ufrag and
3172 // password that indicates the remote peer requests an ICE restart.
3173 // TODO(deadbeef): When we start storing both the current and pending
3174 // remote description, this should reset pending_ice_restarts and compare
3175 // against the current description.
3176 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3177 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08003178 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08003179 pending_ice_restarts_.insert(content.name);
3180 }
3181 } else {
3182 // We retain all received candidates only if ICE is not restarted.
3183 // When ICE is restarted, all previous candidates belong to an old
3184 // generation and should not be kept.
3185 // TODO(deadbeef): This goes against the W3C spec which says the remote
3186 // description should only contain candidates from the last set remote
3187 // description plus any candidates added since then. We should remove
3188 // this once we're sure it won't break anything.
3189 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3190 old_remote_description, content.name, mutable_remote_description());
3191 }
3192 }
3193 }
3194
3195 if (session_error() != SessionError::kNone) {
3196 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3197 }
3198
3199 // Set the the ICE connection state to connecting since the connection may
3200 // become writable with peer reflexive candidates before any remote candidate
3201 // is signaled.
3202 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3203 // is to have a new signal the indicates a change in checking state from the
3204 // transport and expose a new checking() member from transport that can be
3205 // read to determine the current checking state. The existing SignalConnecting
3206 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08003207 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07003208 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08003209 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3210 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3211 }
3212
deadbeefab9b2d12015-10-14 11:33:11 -07003213 // If setting the description decided our SSL role, allocate any necessary
3214 // SCTP sids.
3215 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003216 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07003217 AllocateSctpSids(role);
3218 }
3219
Steve Antondcc3c022017-12-22 16:02:54 -08003220 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08003221 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07003222 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07003223 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08003224 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07003225 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01003226 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08003227 const ContentInfo* content =
3228 FindMediaSectionForTransceiver(transceiver, remote_description());
3229 if (!content) {
3230 continue;
3231 }
3232 const MediaContentDescription* media_desc = content->media_description();
3233 RtpTransceiverDirection local_direction =
3234 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003235 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
3236 // RTCSessionDescription: Set the associated remote streams given
3237 // transceiver.[[Receiver]], msids, addList, and removeList".
3238 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
3239 if (RtpTransceiverDirectionHasRecv(local_direction)) {
3240 std::vector<std::string> stream_ids;
3241 if (!media_desc->streams().empty()) {
3242 // The remote description has signaled the stream IDs.
3243 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08003244 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003245 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
3246 << " (" << GetStreamIdsString(stream_ids) << ").";
3247 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
3248 stream_ids, &added_streams,
3249 &removed_streams);
3250 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
3251 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
3252 // and transceiver's current direction is neither sendrecv nor recvonly,
3253 // process the addition of a remote track for the media description.
3254 if (!transceiver->fired_direction() ||
3255 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
3256 RTC_LOG(LS_INFO)
3257 << "Processing the addition of a remote track for MID="
3258 << content->name << ".";
3259 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01003260 }
Steve Antondcc3c022017-12-22 16:02:54 -08003261 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003262 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07003263 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
3264 // removal of a remote track for the media description, given transceiver,
3265 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08003266 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07003267 (transceiver->fired_direction() &&
3268 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
3269 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
3270 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08003271 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003272 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07003273 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003274 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07003275 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08003276 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003277 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07003278 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08003279 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003280 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
3281 if (transceiver->mid()) {
3282 auto dtls_transport =
3283 LookupDtlsTransportByMidInternal(*transceiver->mid());
3284 transceiver->internal()->sender_internal()->set_transport(
3285 dtls_transport);
3286 transceiver->internal()->receiver_internal()->set_transport(
3287 dtls_transport);
3288 }
Steve Antondcc3c022017-12-22 16:02:54 -08003289 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003290 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07003291 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08003292 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07003293 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
3294 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08003295 transceiver->Stop();
3296 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003297 if (!content->rejected &&
3298 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07003299 if (!media_desc->streams().empty() &&
3300 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07003301 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
3302 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
3303 } else {
3304 transceiver->internal()
3305 ->receiver_internal()
3306 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08003307 }
Steve Antond3679212018-01-17 17:41:02 -08003308 }
Steve Antondcc3c022017-12-22 16:02:54 -08003309 }
Steve Antonc49bcd92018-02-14 14:28:13 -08003310 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003311 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01003312 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08003313 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003314 observer->OnTrack(transceiver);
3315 observer->OnAddTrack(transceiver->receiver(),
3316 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08003317 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003318 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003319 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08003320 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003321 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003322 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07003323 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003324 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003325 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07003326 }
Steve Antondcc3c022017-12-22 16:02:54 -08003327 }
3328
Henrik Boströmfdb92012017-11-09 19:55:44 +01003329 const cricket::ContentInfo* audio_content =
3330 GetFirstAudioContent(remote_description()->description());
3331 const cricket::ContentInfo* video_content =
3332 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003333 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003334 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003335 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003336 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003337 const cricket::RtpDataContentDescription* rtp_data_desc =
3338 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003339
3340 // Check if the descriptions include streams, just in case the peer supports
3341 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01003342 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08003343 (audio_desc && !audio_desc->streams().empty()) ||
3344 (video_desc && !video_desc->streams().empty())) {
3345 remote_peer_supports_msid_ = true;
3346 }
deadbeefab9b2d12015-10-14 11:33:11 -07003347
3348 // We wait to signal new streams until we finish processing the description,
3349 // since only at that point will new streams have all their tracks.
3350 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
3351
Steve Antondcc3c022017-12-22 16:02:54 -08003352 if (!IsUnifiedPlan()) {
3353 // TODO(steveanton): When removing RTP senders/receivers in response to a
3354 // rejected media section, there is some cleanup logic that expects the
3355 // voice/ video channel to still be set. But in this method the voice/video
3356 // channel would have been destroyed by the SetRemoteDescription caller
3357 // above so the cleanup that relies on them fails to run. The RemoveSenders
3358 // calls should be moved to right before the DestroyChannel calls to fix
3359 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07003360
Steve Antondcc3c022017-12-22 16:02:54 -08003361 // Find all audio rtp streams and create corresponding remote AudioTracks
3362 // and MediaStreams.
3363 if (audio_content) {
3364 if (audio_content->rejected) {
3365 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3366 } else {
3367 bool default_audio_track_needed =
3368 !remote_peer_supports_msid_ &&
3369 RtpTransceiverDirectionHasSend(audio_desc->direction());
3370 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3371 default_audio_track_needed, audio_desc->type(),
3372 new_streams);
3373 }
deadbeeffaac4972015-11-12 15:33:07 -08003374 }
deadbeefab9b2d12015-10-14 11:33:11 -07003375
Steve Antondcc3c022017-12-22 16:02:54 -08003376 // Find all video rtp streams and create corresponding remote VideoTracks
3377 // and MediaStreams.
3378 if (video_content) {
3379 if (video_content->rejected) {
3380 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3381 } else {
3382 bool default_video_track_needed =
3383 !remote_peer_supports_msid_ &&
3384 RtpTransceiverDirectionHasSend(video_desc->direction());
3385 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3386 default_video_track_needed, video_desc->type(),
3387 new_streams);
3388 }
deadbeeffaac4972015-11-12 15:33:07 -08003389 }
deadbeefab9b2d12015-10-14 11:33:11 -07003390
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003391 // If this is an RTP data transport, update the DataChannels with the
3392 // information from the remote peer.
3393 if (rtp_data_desc) {
3394 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003395 }
deadbeefab9b2d12015-10-14 11:33:11 -07003396
Steve Antondcc3c022017-12-22 16:02:54 -08003397 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003398 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003399 for (size_t i = 0; i < new_streams->count(); ++i) {
3400 MediaStreamInterface* new_stream = new_streams->at(i);
3401 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003402 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003403 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3404 }
deadbeefab9b2d12015-10-14 11:33:11 -07003405
Steve Antondcc3c022017-12-22 16:02:54 -08003406 UpdateEndedRemoteMediaStreams();
3407 }
deadbeefab9b2d12015-10-14 11:33:11 -07003408
Henrik Boström79b69802019-07-18 11:16:56 +02003409 if (type == SdpType::kAnswer &&
3410 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3411 *current_local_description_)) {
3412 local_ice_credentials_to_replace_->ClearIceCredentials();
3413 }
3414
Steve Anton8a006912017-12-04 15:25:56 -08003415 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003416}
3417
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003418void PeerConnection::SetAssociatedRemoteStreams(
3419 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3420 const std::vector<std::string>& stream_ids,
3421 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3422 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3423 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3424 for (const std::string& stream_id : stream_ids) {
3425 rtc::scoped_refptr<MediaStreamInterface> stream =
3426 remote_streams_->find(stream_id);
3427 if (!stream) {
3428 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3429 MediaStream::Create(stream_id));
3430 remote_streams_->AddStream(stream);
3431 added_streams->push_back(stream);
3432 }
3433 media_streams.push_back(stream);
3434 }
3435 // Special case: "a=msid" missing, use random stream ID.
3436 if (media_streams.empty() &&
3437 !(remote_description()->description()->msid_signaling() &
3438 cricket::kMsidSignalingMediaSection)) {
3439 if (!missing_msid_default_stream_) {
3440 missing_msid_default_stream_ = MediaStreamProxy::Create(
3441 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3442 added_streams->push_back(missing_msid_default_stream_);
3443 }
3444 media_streams.push_back(missing_msid_default_stream_);
3445 }
3446 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3447 receiver->streams();
3448 // SetStreams() will add/remove the receiver's track to/from the streams. This
3449 // differs from the spec - the spec uses an "addList" and "removeList" to
3450 // update the stream-track relationships in a later step. We do this earlier,
3451 // changing the order of things, but the end-result is the same.
3452 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3453 // instead. https://crbug.com/webrtc/9480
3454 receiver->SetStreams(media_streams);
3455 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3456}
3457
Steve Anton0f5400a2018-07-17 14:25:36 -07003458void PeerConnection::ProcessRemovalOfRemoteTrack(
3459 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3460 transceiver,
3461 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3462 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3463 RTC_DCHECK(transceiver->mid());
3464 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3465 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003466 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003467 transceiver->internal()->receiver_internal()->streams();
3468 // This will remove the remote track from the streams.
3469 transceiver->internal()->receiver_internal()->set_stream_ids({});
3470 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003471 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3472}
3473
3474void PeerConnection::RemoveRemoteStreamsIfEmpty(
3475 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3476 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3477 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3478 // streams, see if the stream was removed by checking if this was the last
3479 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003480 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003481 if (remote_stream->GetAudioTracks().empty() &&
3482 remote_stream->GetVideoTracks().empty()) {
3483 remote_streams_->RemoveStream(remote_stream);
3484 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003485 }
3486 }
3487}
3488
Steve Antondcc3c022017-12-22 16:02:54 -08003489RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3490 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003491 const SessionDescriptionInterface& new_session,
3492 const SessionDescriptionInterface* old_local_description,
3493 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003494 RTC_DCHECK(IsUnifiedPlan());
3495
Steve Anton7464fca2018-01-19 11:10:37 -08003496 const cricket::ContentGroup* bundle_group = nullptr;
3497 if (new_session.GetType() == SdpType::kOffer) {
3498 auto bundle_group_or_error =
3499 GetEarlyBundleGroup(*new_session.description());
3500 if (!bundle_group_or_error.ok()) {
3501 return bundle_group_or_error.MoveError();
3502 }
3503 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003504 }
Steve Antondcc3c022017-12-22 16:02:54 -08003505
Steve Antondcc3c022017-12-22 16:02:54 -08003506 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003507 for (size_t i = 0; i < new_contents.size(); ++i) {
3508 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003509 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003510 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003511 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3512 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003513 const cricket::ContentInfo* old_local_content = nullptr;
3514 if (old_local_description &&
3515 i < old_local_description->description()->contents().size()) {
3516 old_local_content =
3517 &old_local_description->description()->contents()[i];
3518 }
3519 const cricket::ContentInfo* old_remote_content = nullptr;
3520 if (old_remote_description &&
3521 i < old_remote_description->description()->contents().size()) {
3522 old_remote_content =
3523 &old_remote_description->description()->contents()[i];
3524 }
Steve Antondcc3c022017-12-22 16:02:54 -08003525 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003526 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3527 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003528 if (!transceiver_or_error.ok()) {
3529 return transceiver_or_error.MoveError();
3530 }
3531 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003532 RTCError error =
3533 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3534 if (!error.ok()) {
3535 return error;
3536 }
3537 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003538 if (GetDataMid() && new_content.name != *GetDataMid()) {
3539 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003540 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3541 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003542 continue;
3543 }
3544 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3545 if (!error.ok()) {
3546 return error;
3547 }
Steve Antondcc3c022017-12-22 16:02:54 -08003548 } else {
3549 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3550 "Unknown section type.");
3551 }
3552 }
3553
3554 return RTCError::OK();
3555}
3556
3557RTCError PeerConnection::UpdateTransceiverChannel(
3558 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3559 transceiver,
3560 const cricket::ContentInfo& content,
3561 const cricket::ContentGroup* bundle_group) {
3562 RTC_DCHECK(IsUnifiedPlan());
3563 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003564 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003565 if (content.rejected) {
3566 if (channel) {
3567 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003568 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003569 }
3570 } else {
3571 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003572 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003573 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003574 } else {
Steve Anton69470252018-02-09 11:43:08 -08003575 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003576 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003577 }
3578 if (!channel) {
3579 LOG_AND_RETURN_ERROR(
3580 RTCErrorType::INTERNAL_ERROR,
3581 "Failed to create channel for mid=" + content.name);
3582 }
3583 transceiver->internal()->SetChannel(channel);
3584 }
3585 }
3586 return RTCError::OK();
3587}
3588
Steve Antonfa2260d2017-12-28 16:38:23 -08003589RTCError PeerConnection::UpdateDataChannel(
3590 cricket::ContentSource source,
3591 const cricket::ContentInfo& content,
3592 const cricket::ContentGroup* bundle_group) {
3593 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003594 // If data channels are disabled, ignore this media section. CreateAnswer
3595 // will take care of rejecting it.
3596 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003597 }
3598 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003599 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003600 DestroyDataChannel();
3601 } else {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07003602 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003603 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003604 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003605 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3606 "Failed to create data channel.");
3607 }
3608 }
3609 if (source == cricket::CS_REMOTE) {
3610 const MediaContentDescription* data_desc = content.media_description();
3611 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3612 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3613 }
3614 }
3615 }
3616 return RTCError::OK();
3617}
3618
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003619// This method will extract any send encodings that were sent by the remote
3620// connection. This is currently only relevant for Simulcast scenario (where
3621// the number of layers may be communicated by the server).
3622static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3623 const MediaContentDescription& desc) {
3624 if (!desc.HasSimulcast()) {
3625 return {};
3626 }
3627 std::vector<RtpEncodingParameters> result;
3628 const SimulcastDescription& simulcast = desc.simulcast_description();
3629
3630 // This is a remote description, the parameters we are after should appear
3631 // as receive streams.
3632 for (const auto& alternatives : simulcast.receive_layers()) {
3633 RTC_DCHECK(!alternatives.empty());
3634 // There is currently no way to specify or choose from alternatives.
3635 // We will always use the first alternative, which is the most preferred.
3636 const SimulcastLayer& layer = alternatives[0];
3637 RtpEncodingParameters parameters;
3638 parameters.rid = layer.rid;
3639 parameters.active = !layer.is_paused;
3640 result.push_back(parameters);
3641 }
3642
3643 return result;
3644}
3645
3646static RTCError UpdateSimulcastLayerStatusInSender(
3647 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003648 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003649 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003650 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003651 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003652
3653 // The simulcast envelope cannot be changed, only the status of the streams.
3654 // So we will iterate over the send encodings rather than the layers.
3655 for (RtpEncodingParameters& encoding : parameters.encodings) {
3656 auto iter = std::find_if(layers.begin(), layers.end(),
3657 [&encoding](const SimulcastLayer& layer) {
3658 return layer.rid == encoding.rid;
3659 });
3660 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003661 if (iter == layers.end()) {
3662 disabled_layers.push_back(encoding.rid);
3663 continue;
3664 }
3665
3666 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003667 }
3668
Amit Hilbuch619b2942019-02-26 15:55:19 -08003669 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003670 if (result.ok()) {
3671 result = sender->DisableEncodingLayers(disabled_layers);
3672 }
3673
3674 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003675}
3676
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003677static bool SimulcastIsRejected(
3678 const ContentInfo* local_content,
3679 const MediaContentDescription& answer_media_desc) {
3680 bool simulcast_offered = local_content &&
3681 local_content->media_description() &&
3682 local_content->media_description()->HasSimulcast();
3683 bool simulcast_answered = answer_media_desc.HasSimulcast();
3684 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3685 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3686 return simulcast_offered && (!simulcast_answered || !rids_supported);
3687}
3688
Amit Hilbuch2297d332019-02-19 12:49:22 -08003689static RTCError DisableSimulcastInSender(
3690 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003691 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003692 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003693 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003694 return RTCError::OK();
3695 }
3696
Amit Hilbuch2297d332019-02-19 12:49:22 -08003697 std::vector<std::string> disabled_layers;
3698 std::transform(
3699 parameters.encodings.begin() + 1, parameters.encodings.end(),
3700 std::back_inserter(disabled_layers),
3701 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3702 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003703}
3704
Steve Antondcc3c022017-12-22 16:02:54 -08003705RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3706PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003707 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003708 size_t mline_index,
3709 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003710 const ContentInfo* old_local_content,
3711 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003712 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003713 // If this is an offer then the m= section might be recycled. If the m=
3714 // section is being recycled (defined as: rejected in the current local or
3715 // remote description and not rejected in new description), dissociate the
3716 // currently associated RtpTransceiver by setting its mid property to null,
3717 // and discard the mapping between the transceiver and its m= section index.
3718 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3719 old_remote_content)) {
3720 // We want to dissociate the transceiver that has the rejected mid.
3721 const std::string& old_mid =
3722 (old_local_content && old_local_content->rejected)
3723 ? old_local_content->name
3724 : old_remote_content->name;
3725 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003726 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003727 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3728 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003729 old_transceiver->internal()->set_mid(absl::nullopt);
3730 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003731 }
3732 }
3733 const MediaContentDescription* media_desc = content.media_description();
3734 auto transceiver = GetAssociatedTransceiver(content.name);
3735 if (source == cricket::CS_LOCAL) {
3736 // Find the RtpTransceiver that corresponds to this m= section, using the
3737 // mapping between transceivers and m= section indices established when
3738 // creating the offer.
3739 if (!transceiver) {
3740 transceiver = GetTransceiverByMLineIndex(mline_index);
3741 }
3742 if (!transceiver) {
3743 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3744 "Unknown transceiver");
3745 }
3746 } else {
3747 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3748 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3749 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003750 // When simulcast is requested, a transceiver cannot be associated because
3751 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003752 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003753 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3754 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003755 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3756 }
3757 // If no RtpTransceiver was found in the previous step, create one with a
3758 // recvonly direction.
3759 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003760 RTC_LOG(LS_INFO) << "Adding "
3761 << cricket::MediaTypeToString(media_desc->type())
3762 << " transceiver for MID=" << content.name
3763 << " at i=" << mline_index
3764 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003765 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003766 std::vector<RtpEncodingParameters> send_encodings =
3767 GetSendEncodingsFromRemoteDescription(*media_desc);
3768 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3769 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003770 std::string receiver_id;
3771 if (!media_desc->streams().empty()) {
3772 receiver_id = media_desc->streams()[0].id;
3773 } else {
3774 receiver_id = rtc::CreateRandomUuid();
3775 }
3776 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003777 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003778 transceiver->internal()->set_direction(
3779 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 18:29:44 +03003780 if (type == SdpType::kOffer) {
3781 transceiver_stable_states_by_transceivers_[transceiver] =
3782 TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
3783 absl::nullopt, absl::nullopt, true);
3784 }
Steve Antondcc3c022017-12-22 16:02:54 -08003785 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003786 // Check if the offer indicated simulcast but the answer rejected it.
3787 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003788 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003789 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003790 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003791 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003792 if (!error.ok()) {
3793 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3794 return std::move(error);
3795 }
3796 }
Steve Antondcc3c022017-12-22 16:02:54 -08003797 }
3798 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003799 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003800 LOG_AND_RETURN_ERROR(
3801 RTCErrorType::INVALID_PARAMETER,
3802 "Transceiver type does not match media description type.");
3803 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003804 if (media_desc->HasSimulcast()) {
3805 std::vector<SimulcastLayer> layers =
3806 source == cricket::CS_LOCAL
3807 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3808 : media_desc->simulcast_description()
3809 .receive_layers()
3810 .GetAllLayers();
3811 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003812 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003813 if (!error.ok()) {
3814 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3815 return std::move(error);
3816 }
3817 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003818 if (type == SdpType::kOffer) {
3819 // Make sure we don't overwrite existing stable states and that the
3820 // state is really going to change when adding new record to the map.
3821 auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
3822 if (it == transceiver_stable_states_by_transceivers_.end() &&
3823 (transceiver->internal()->mid() != content.name ||
3824 transceiver->internal()->mline_index() != mline_index)) {
3825 transceiver_stable_states_by_transceivers_[transceiver] =
3826 TransceiverStableState(transceiver->internal()->direction(),
3827 transceiver->internal()->mid(),
3828 transceiver->internal()->mline_index(), false);
3829 }
3830 }
3831
Steve Antondcc3c022017-12-22 16:02:54 -08003832 // Associate the found or created RtpTransceiver with the m= section by
3833 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3834 // section, and establish a mapping between the transceiver and the index of
3835 // the m= section.
3836 transceiver->internal()->set_mid(content.name);
3837 transceiver->internal()->set_mline_index(mline_index);
3838 return std::move(transceiver);
3839}
3840
3841rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3842PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3843 RTC_DCHECK(IsUnifiedPlan());
3844 for (auto transceiver : transceivers_) {
3845 if (transceiver->mid() == mid) {
3846 return transceiver;
3847 }
3848 }
3849 return nullptr;
3850}
3851
3852rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3853PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3854 RTC_DCHECK(IsUnifiedPlan());
3855 for (auto transceiver : transceivers_) {
3856 if (transceiver->internal()->mline_index() == mline_index) {
3857 return transceiver;
3858 }
3859 }
3860 return nullptr;
3861}
3862
3863rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3864PeerConnection::FindAvailableTransceiverToReceive(
3865 cricket::MediaType media_type) const {
3866 RTC_DCHECK(IsUnifiedPlan());
3867 // From JSEP section 5.10 (Applying a Remote Description):
3868 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3869 // the same type that were added to the PeerConnection by addTrack and are not
3870 // associated with any m= section and are not stopped, find the first such
3871 // RtpTransceiver.
3872 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003873 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003874 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3875 !transceiver->stopped()) {
3876 return transceiver;
3877 }
3878 }
3879 return nullptr;
3880}
3881
Steve Antoned10bd92017-12-05 10:52:59 -08003882const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3883 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3884 transceiver,
3885 const SessionDescriptionInterface* sdesc) const {
3886 RTC_DCHECK(transceiver);
3887 RTC_DCHECK(sdesc);
3888 if (IsUnifiedPlan()) {
3889 if (!transceiver->internal()->mid()) {
3890 // This transceiver is not associated with a media section yet.
3891 return nullptr;
3892 }
3893 return sdesc->description()->GetContentByName(
3894 *transceiver->internal()->mid());
3895 } else {
3896 // Plan B only allows at most one audio and one video section, so use the
3897 // first media section of that type.
3898 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003899 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003900 }
3901}
3902
deadbeef46c73892016-11-16 19:42:04 -08003903PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003904 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003905 return configuration_;
3906}
3907
Niels Möller2579f0c2019-08-19 09:58:17 +02003908RTCError PeerConnection::SetConfiguration(
3909 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003910 RTC_DCHECK_RUN_ON(signaling_thread());
3911 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003912 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003913 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003914 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3915 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003916 }
3917
Qingsi Wanga2d60672018-04-11 16:57:45 -07003918 // According to JSEP, after setLocalDescription, changing the candidate pool
3919 // size is not allowed, and changing the set of ICE servers will not result
3920 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003921 if (local_description() && configuration.ice_candidate_pool_size !=
3922 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003923 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3924 "Can't change candidate pool size after calling "
3925 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003926 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003927
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003928 if (local_description() &&
3929 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003930 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3931 "Can't change media_transport after calling "
3932 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003933 }
3934
3935 if (remote_description() &&
3936 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003937 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3938 "Can't change media_transport after calling "
3939 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003940 }
3941
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003942 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003943 configuration.use_media_transport_for_data_channels !=
3944 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003945 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3946 "Can't change media_transport_for_data_channels "
3947 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003948 }
3949
3950 if (remote_description() &&
3951 configuration.use_media_transport_for_data_channels !=
3952 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003953 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3954 "Can't change media_transport_for_data_channels "
3955 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003956 }
3957
3958 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003959 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003960 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3961 "Can't change crypto_options after calling "
3962 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003963 }
3964
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003965 if (local_description() && configuration.use_datagram_transport !=
3966 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003967 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3968 "Can't change use_datagram_transport "
3969 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003970 }
3971
3972 if (remote_description() && configuration.use_datagram_transport !=
3973 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003974 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3975 "Can't change use_datagram_transport "
3976 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003977 }
3978
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003979 if (local_description() &&
3980 configuration.use_datagram_transport_for_data_channels !=
3981 configuration_.use_datagram_transport_for_data_channels) {
3982 LOG_AND_RETURN_ERROR(
3983 RTCErrorType::INVALID_MODIFICATION,
3984 "Can't change use_datagram_transport_for_data_channels "
3985 "after calling SetLocalDescription.");
3986 }
3987
3988 if (remote_description() &&
3989 configuration.use_datagram_transport_for_data_channels !=
3990 configuration_.use_datagram_transport_for_data_channels) {
3991 LOG_AND_RETURN_ERROR(
3992 RTCErrorType::INVALID_MODIFICATION,
3993 "Can't change use_datagram_transport_for_data_channels "
3994 "after calling SetRemoteDescription.");
3995 }
3996
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003997 if (local_description() &&
3998 configuration.use_datagram_transport_for_data_channels_receive_only !=
3999 configuration_
4000 .use_datagram_transport_for_data_channels_receive_only) {
4001 LOG_AND_RETURN_ERROR(
4002 RTCErrorType::INVALID_MODIFICATION,
4003 "Can't change use_datagram_transport_for_data_channels_receive_only "
4004 "after calling SetLocalDescription.");
4005 }
4006
4007 if (remote_description() &&
4008 configuration.use_datagram_transport_for_data_channels_receive_only !=
4009 configuration_
4010 .use_datagram_transport_for_data_channels_receive_only) {
4011 LOG_AND_RETURN_ERROR(
4012 RTCErrorType::INVALID_MODIFICATION,
4013 "Can't change use_datagram_transport_for_data_channels_receive_only "
4014 "after calling SetRemoteDescription.");
4015 }
4016
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08004017 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07004018 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004019 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004020 *configuration.use_datagram_transport) ||
4021 (configuration.use_datagram_transport_for_data_channels &&
4022 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08004023 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
4024 << "Media transport requires MaxBundle policy.";
4025 }
4026
deadbeef293e9262017-01-11 12:28:30 -08004027 // The simplest (and most future-compatible) way to tell if the config was
4028 // modified in an invalid way is to copy each property we do support
4029 // modifying, then use operator==. There are far more properties we don't
4030 // support modifying than those we do, and more could be added.
4031 RTCConfiguration modified_config = configuration_;
4032 modified_config.servers = configuration.servers;
4033 modified_config.type = configuration.type;
4034 modified_config.ice_candidate_pool_size =
4035 configuration.ice_candidate_pool_size;
4036 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004037 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 14:56:02 -07004038 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
4039 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08004040 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08004041 modified_config.ice_check_interval_strong_connectivity =
4042 configuration.ice_check_interval_strong_connectivity;
4043 modified_config.ice_check_interval_weak_connectivity =
4044 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07004045 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
4046 modified_config.ice_unwritable_min_checks =
4047 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08004048 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004049 modified_config.stun_candidate_keepalive_interval =
4050 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004051 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004052 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07004053 modified_config.active_reset_srtp_params =
4054 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07004055 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07004056 modified_config.use_media_transport_for_data_channels =
4057 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004058 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004059 modified_config.use_datagram_transport_for_data_channels =
4060 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004061 modified_config.use_datagram_transport_for_data_channels_receive_only =
4062 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 16:16:35 +02004063 modified_config.turn_logging_id = configuration.turn_logging_id;
philipel16cec3b2019-10-25 12:23:02 +02004064 modified_config.allow_codec_switching = configuration.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -08004065 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004066 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
4067 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08004068 }
4069
Steve Anton038834f2017-07-14 15:59:59 -07004070 // Validate the modified configuration.
4071 RTCError validate_error = ValidateConfiguration(modified_config);
4072 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004073 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07004074 }
4075
deadbeef293e9262017-01-11 12:28:30 -08004076 // Note that this isn't possible through chromium, since it's an unsigned
4077 // short in WebIDL.
4078 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07004079 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004080 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08004081 }
4082
4083 // Parse ICE servers before hopping to network thread.
4084 cricket::ServerAddresses stun_servers;
4085 std::vector<cricket::RelayServerConfig> turn_servers;
4086 RTCErrorType parse_error =
4087 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
4088 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004089 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08004090 }
Jonas Oreland3c028422019-08-22 16:16:35 +02004091 // Add the turn logging id to all turn servers
4092 for (cricket::RelayServerConfig& turn_server : turn_servers) {
4093 turn_server.turn_logging_id = configuration.turn_logging_id;
4094 }
4095
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004096 // Note if STUN or TURN servers were supplied.
4097 if (!stun_servers.empty()) {
4098 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
4099 }
4100 if (!turn_servers.empty()) {
4101 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
4102 }
deadbeef293e9262017-01-11 12:28:30 -08004103
4104 // In theory this shouldn't fail.
4105 if (!network_thread()->Invoke<bool>(
4106 RTC_FROM_HERE,
4107 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
4108 stun_servers, turn_servers, modified_config.type,
4109 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004110 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004111 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02004112 modified_config.stun_candidate_keepalive_interval,
4113 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004114 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4115 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08004116 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004117
deadbeefd1a38b52016-12-10 13:15:33 -08004118 // As described in JSEP, calling setConfiguration with new ICE servers or
4119 // candidate policy must set a "needs-ice-restart" bit so that the next offer
4120 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08004121 if (modified_config.servers != configuration_.servers ||
4122 modified_config.type != configuration_.type ||
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004123 modified_config.GetTurnPortPrunePolicy() !=
4124 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 14:50:29 -08004125 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08004126 }
skvladd1f5fda2017-02-03 16:54:05 -08004127
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08004128 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004129
4130 use_datagram_transport_ = datagram_transport_config_.enabled &&
4131 modified_config.use_datagram_transport.value_or(
4132 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004133 use_datagram_transport_for_data_channels_ =
4134 datagram_transport_data_channel_config_.enabled &&
4135 modified_config.use_datagram_transport_for_data_channels.value_or(
4136 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004137 use_datagram_transport_for_data_channels_receive_only_ =
4138 modified_config.use_datagram_transport_for_data_channels_receive_only
4139 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08004140 transport_controller_->SetMediaTransportSettings(
4141 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07004142 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004143 use_datagram_transport_, use_datagram_transport_for_data_channels_,
4144 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-03 16:54:05 -08004145
Zhi Huangb57e1692018-06-12 11:41:11 -07004146 if (configuration_.active_reset_srtp_params !=
4147 modified_config.active_reset_srtp_params) {
4148 transport_controller_->SetActiveResetSrtpParams(
4149 modified_config.active_reset_srtp_params);
4150 }
4151
philipel16cec3b2019-10-25 12:23:02 +02004152 if (modified_config.allow_codec_switching.has_value()) {
philipel01294f02019-11-14 13:03:25 +01004153 cricket::VideoMediaChannel* video_channel = video_media_channel();
4154 if (video_channel) {
4155 video_channel->SetVideoCodecSwitchingEnabled(
4156 *modified_config.allow_codec_switching);
4157 }
philipel16cec3b2019-10-25 12:23:02 +02004158 }
4159
deadbeef293e9262017-01-11 12:28:30 -08004160 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01004161 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02004162 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00004163}
4164
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004165bool PeerConnection::AddIceCandidate(
4166 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004167 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004168 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07004169 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004170 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004171 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07004172 return false;
4173 }
Steve Antond25da372017-11-06 14:50:29 -08004174
4175 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004176 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004177 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004178 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08004179 return false;
4180 }
4181
4182 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07004183 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004184 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08004185 return false;
4186 }
4187
4188 bool valid = false;
4189 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
4190 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004191 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08004192 return false;
4193 }
4194
4195 // Add this candidate to the remote session description.
4196 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07004197 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004198 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08004199 return false;
4200 }
4201
4202 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004203 bool result = UseCandidate(ice_candidate);
4204 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004205 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02004206 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
4207 } else {
4208 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
4209 }
4210 return result;
Steve Antond25da372017-11-06 14:50:29 -08004211 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07004212 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004213 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08004214 return true;
4215 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004216}
4217
Henrik Boströmee6f4f62019-11-06 12:36:12 +01004218void PeerConnection::AddIceCandidate(
4219 std::unique_ptr<IceCandidateInterface> candidate,
4220 std::function<void(RTCError)> callback) {
4221 RTC_DCHECK_RUN_ON(signaling_thread());
4222 // Chain this operation. If asynchronous operations are pending on the chain,
4223 // this operation will be queued to be invoked, otherwise the contents of the
4224 // lambda will execute immediately.
4225 operations_chain_->ChainOperation(
4226 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
4227 candidate = std::move(candidate), callback = std::move(callback)](
4228 std::function<void()> operations_chain_callback) {
4229 if (!this_weak_ptr) {
4230 operations_chain_callback();
4231 callback(RTCError(
4232 RTCErrorType::INVALID_STATE,
4233 "AddIceCandidate failed because the session was shut down"));
4234 return;
4235 }
4236 if (!this_weak_ptr->AddIceCandidate(candidate.get())) {
4237 operations_chain_callback();
4238 // Fail with an error type and message consistent with Chromium.
4239 // TODO(hbos): Fail with error types according to spec.
4240 callback(RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
4241 "Error processing ICE candidate"));
4242 return;
4243 }
4244 operations_chain_callback();
4245 callback(RTCError::OK());
4246 });
4247}
4248
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004249bool PeerConnection::RemoveIceCandidates(
4250 const std::vector<cricket::Candidate>& candidates) {
4251 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004252 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07004253 if (IsClosed()) {
4254 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
4255 return false;
4256 }
4257
Steve Antond25da372017-11-06 14:50:29 -08004258 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004259 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
4260 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08004261 return false;
4262 }
4263
4264 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004265 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08004266 return false;
4267 }
4268
4269 size_t number_removed =
4270 mutable_remote_description()->RemoveCandidates(candidates);
4271 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004272 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07004273 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004274 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01004275 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08004276 }
4277
4278 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07004279 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
4280 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004281 RTC_LOG(LS_ERROR)
4282 << "RemoveIceCandidates: Error when removing remote candidates: "
4283 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08004284 }
4285 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004286}
4287
Niels Möller0c4f7be2018-05-07 14:01:37 +02004288RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07004289 if (!worker_thread()->IsCurrent()) {
4290 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02004291 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07004292 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01004293 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07004294
Niels Möller0c4f7be2018-05-07 14:01:37 +02004295 const bool has_min = bitrate.min_bitrate_bps.has_value();
4296 const bool has_start = bitrate.start_bitrate_bps.has_value();
4297 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07004298 if (has_min && *bitrate.min_bitrate_bps < 0) {
4299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4300 "min_bitrate_bps <= 0");
4301 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02004302 if (has_start) {
4303 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004305 "start_bitrate_bps < min_bitrate_bps");
4306 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07004307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4308 "curent_bitrate_bps < 0");
4309 }
4310 }
4311 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02004312 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004314 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07004315 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
4316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4317 "max_bitrate_bps < min_bitrate_bps");
4318 } else if (*bitrate.max_bitrate_bps < 0) {
4319 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4320 "max_bitrate_bps < 0");
4321 }
4322 }
4323
zstein4b979802017-06-02 14:37:37 -07004324 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07004325 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07004326
4327 return RTCError::OK();
4328}
4329
henrika5f6bf242017-11-01 11:06:56 +01004330void PeerConnection::SetAudioPlayout(bool playout) {
4331 if (!worker_thread()->IsCurrent()) {
4332 worker_thread()->Invoke<void>(
4333 RTC_FROM_HERE,
4334 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
4335 return;
4336 }
4337 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004338 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004339 audio_state->SetPlayout(playout);
4340}
4341
4342void PeerConnection::SetAudioRecording(bool recording) {
4343 if (!worker_thread()->IsCurrent()) {
4344 worker_thread()->Invoke<void>(
4345 RTC_FROM_HERE,
4346 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
4347 return;
4348 }
4349 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004350 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004351 audio_state->SetRecording(recording);
4352}
4353
Steve Anton8c0f7a72017-10-03 10:03:10 -07004354std::unique_ptr<rtc::SSLCertificate>
4355PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004356 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
4357 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07004358 return nullptr;
4359 }
Steve Antonf25303e2018-10-16 15:23:31 -07004360 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07004361}
4362
Zhi Huang70b820f2018-01-27 14:16:15 -08004363std::unique_ptr<rtc::SSLCertChain>
4364PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01004365 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08004366 auto audio_transceiver = GetFirstAudioTransceiver();
4367 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08004368 return nullptr;
4369 }
Zhi Huang70b820f2018-01-27 14:16:15 -08004370 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08004371 audio_transceiver->internal()->channel()->transport_name());
4372}
4373
4374rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4375PeerConnection::GetFirstAudioTransceiver() const {
4376 for (auto transceiver : transceivers_) {
4377 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4378 return transceiver;
4379 }
4380 }
4381 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08004382}
4383
Bjorn Tereliusde939432017-11-20 17:38:14 +01004384bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
4385 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01004386 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02004387 RTC_FROM_HERE,
4388 [this, output = std::move(output), output_period_ms]() mutable {
4389 return StartRtcEventLog_w(std::move(output), output_period_ms);
4390 });
ivoc14d5dbe2016-07-04 07:06:55 -07004391}
4392
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004393bool PeerConnection::StartRtcEventLog(
4394 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02004395 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4396 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4397 output_period_ms = 5000;
4398 }
4399 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004400}
4401
ivoc14d5dbe2016-07-04 07:06:55 -07004402void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004403 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004404 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4405}
4406
Harald Alvestrandad88c882018-11-28 16:47:46 +01004407rtc::scoped_refptr<DtlsTransportInterface>
4408PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004409 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004410 return transport_controller_->LookupDtlsTransportByMid(mid);
4411}
4412
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004413rtc::scoped_refptr<DtlsTransport>
4414PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004415 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004416 return transport_controller_->LookupDtlsTransportByMid(mid);
4417}
4418
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004419rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4420 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004421 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004422 if (!sctp_mid_) {
4423 return nullptr;
4424 }
4425 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004426}
4427
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004428const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004429 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004430 return pending_local_description_ ? pending_local_description_.get()
4431 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004432}
4433
4434const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004435 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004436 return pending_remote_description_ ? pending_remote_description_.get()
4437 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004438}
4439
deadbeeffe4a8a42016-12-20 17:56:17 -08004440const SessionDescriptionInterface* PeerConnection::current_local_description()
4441 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004442 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004443 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004444}
4445
4446const SessionDescriptionInterface* PeerConnection::current_remote_description()
4447 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004448 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004449 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004450}
4451
4452const SessionDescriptionInterface* PeerConnection::pending_local_description()
4453 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004454 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004455 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004456}
4457
4458const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4459 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004460 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004461 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004462}
4463
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004464void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004465 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004466 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004467 // Update stats here so that we have the most recent stats for tracks and
4468 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004469 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004470
Steve Anton75737c02017-11-06 10:37:17 -08004471 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004472 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004473
Mirko Bonadei739baf02019-01-27 17:29:42 +01004474 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004475 transceiver->Stop();
4476 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004477
4478 // Ensure that all asynchronous stats requests are completed before destroying
4479 // the transport controller below.
4480 if (stats_collector_) {
4481 stats_collector_->WaitForPendingRequest();
4482 }
4483
4484 // Don't destroy BaseChannels until after stats has been cleaned up so that
4485 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004486 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004487
Qingsi Wang93a84392018-01-30 17:13:09 -08004488 // The event log is used in the transport controller, which must be outlived
4489 // by the former. CreateOffer by the peer connection is implemented
4490 // asynchronously and if the peer connection is closed without resetting the
4491 // WebRTC session description factory, the session description factory would
4492 // call the transport controller.
4493 webrtc_session_desc_factory_.reset();
4494 transport_controller_.reset();
4495
deadbeef42a42632017-03-10 15:18:00 -08004496 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004497 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4498 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004499
Steve Anton978b8762017-09-29 12:15:02 -07004500 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004501 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004502 call_.reset();
4503 // The event log must outlive call (and any other object that uses it).
4504 event_log_.reset();
4505 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004506 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004507 // The .h file says that observer can be discarded after close() returns.
4508 // Make sure this is true.
4509 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004510}
4511
Steve Antonad182762018-09-05 20:22:40 +00004512void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004513 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004514 switch (msg->message_id) {
4515 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4516 SetSessionDescriptionMsg* param =
4517 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4518 param->observer->OnSuccess();
4519 delete param;
4520 break;
4521 }
4522 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4523 SetSessionDescriptionMsg* param =
4524 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4525 param->observer->OnFailure(std::move(param->error));
4526 delete param;
4527 break;
4528 }
4529 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4530 CreateSessionDescriptionMsg* param =
4531 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4532 param->observer->OnFailure(std::move(param->error));
4533 delete param;
4534 break;
4535 }
4536 case MSG_GETSTATS: {
4537 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4538 StatsReports reports;
4539 stats_->GetStats(param->track, &reports);
4540 param->observer->OnComplete(reports);
4541 delete param;
4542 break;
4543 }
4544 case MSG_FREE_DATACHANNELS: {
4545 sctp_data_channels_to_free_.clear();
4546 break;
4547 }
4548 case MSG_REPORT_USAGE_PATTERN: {
4549 ReportUsagePattern();
4550 break;
4551 }
4552 default:
4553 RTC_NOTREACHED() << "Not implemented";
4554 break;
4555 }
4556}
4557
Steve Antonafb0bb72018-02-20 11:35:37 -08004558cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4559 RTC_DCHECK(!IsUnifiedPlan());
4560 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4561 GetAudioTransceiver()->internal()->channel());
4562 if (voice_channel) {
4563 return voice_channel->media_channel();
4564 } else {
4565 return nullptr;
4566 }
4567}
4568
4569cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4570 RTC_DCHECK(!IsUnifiedPlan());
4571 auto* video_channel = static_cast<cricket::VideoChannel*>(
4572 GetVideoTransceiver()->internal()->channel());
4573 if (video_channel) {
4574 return video_channel->media_channel();
4575 } else {
4576 return nullptr;
4577 }
4578}
4579
Steve Anton4171afb2017-11-20 10:20:22 -08004580void PeerConnection::CreateAudioReceiver(
4581 MediaStreamInterface* stream,
4582 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004583 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4584 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004585 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4586 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004587 auto* audio_receiver = new AudioRtpReceiver(
4588 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004589 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004590 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4591 audio_receiver->SetupUnsignaledMediaChannel();
4592 } else {
4593 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4594 }
Steve Antond3679212018-01-17 17:41:02 -08004595 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4596 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004597 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004598 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004599 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004600}
4601
Steve Anton4171afb2017-11-20 10:20:22 -08004602void PeerConnection::CreateVideoReceiver(
4603 MediaStreamInterface* stream,
4604 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004605 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4606 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004607 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4608 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004609 auto* video_receiver = new VideoRtpReceiver(
4610 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004611 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004612 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4613 video_receiver->SetupUnsignaledMediaChannel();
4614 } else {
4615 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4616 }
Steve Antond3679212018-01-17 17:41:02 -08004617 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4618 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004619 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004620 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004621 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004622}
4623
deadbeef70ab1a12015-09-28 16:53:55 -07004624// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4625// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004626rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004627 const RtpSenderInfo& remote_sender_info) {
4628 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4629 if (!receiver) {
4630 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4631 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004632 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004633 }
Steve Anton4171afb2017-11-20 10:20:22 -08004634 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4635 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4636 } else {
4637 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4638 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004639 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004640}
4641
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004642void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4643 MediaStreamInterface* stream) {
4644 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004645 RTC_DCHECK(track);
4646 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004647 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004648 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004649 // We already have a sender for this track, so just change the stream_id
4650 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004651 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004652 return;
4653 }
4654
4655 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004656 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004657 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004658 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004659 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004660 // If the sender has already been configured in SDP, we call SetSsrc,
4661 // which will connect the sender to the underlying transport. This can
4662 // occur if a local session description that contains the ID of the sender
4663 // is set before AddStream is called. It can also occur if the local
4664 // session description is not changed and RemoveStream is called, and
4665 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004666 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004667 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004668 if (sender_info) {
4669 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004670 }
4671}
4672
4673// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4674// indefinitely, when we have unified plan SDP.
4675void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4676 MediaStreamInterface* stream) {
4677 RTC_DCHECK(!IsClosed());
4678 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004679 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004680 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4681 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004682 return;
4683 }
Steve Anton4171afb2017-11-20 10:20:22 -08004684 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004685}
4686
4687void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4688 MediaStreamInterface* stream) {
4689 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004690 RTC_DCHECK(track);
4691 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004692 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004693 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004694 // We already have a sender for this track, so just change the stream_id
4695 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004696 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004697 return;
4698 }
4699
4700 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004701 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004702 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004703 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004704 GetVideoTransceiver()->internal()->AddSender(new_sender);
4705 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004706 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004707 if (sender_info) {
4708 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004709 }
4710}
4711
4712void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4713 MediaStreamInterface* stream) {
4714 RTC_DCHECK(!IsClosed());
4715 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004716 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004717 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4718 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004719 return;
4720 }
Steve Anton4171afb2017-11-20 10:20:22 -08004721 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004722}
4723
Steve Antonba818672017-11-06 10:21:57 -08004724void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004725 if (ice_connection_state_ == new_state) {
4726 return;
4727 }
4728
deadbeefcbecd352015-09-23 11:50:27 -07004729 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004730 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004731 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004732 return;
4733 }
Steve Antonba818672017-11-06 10:21:57 -08004734
Mirko Bonadei675513b2017-11-09 11:09:25 +01004735 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4736 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004737 RTC_DCHECK(ice_connection_state_ !=
4738 PeerConnectionInterface::kIceConnectionClosed);
4739
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004740 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004741 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004742}
4743
Alex Loiko9289eda2018-11-23 16:18:59 +00004744void PeerConnection::SetStandardizedIceConnectionState(
4745 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004746 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004747 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004748 }
4749
4750 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004751 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004752 }
4753
4754 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4755 << standardized_ice_connection_state_ << " => " << new_state;
4756
Alex Loiko9289eda2018-11-23 16:18:59 +00004757 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004758 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004759}
4760
Jonas Olsson635474e2018-10-18 15:58:17 +02004761void PeerConnection::SetConnectionState(
4762 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004763 if (connection_state_ == new_state)
4764 return;
4765 if (IsClosed())
4766 return;
4767 connection_state_ = new_state;
4768 Observer()->OnConnectionChange(new_state);
4769}
4770
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004771void PeerConnection::OnIceGatheringChange(
4772 PeerConnectionInterface::IceGatheringState new_state) {
4773 if (IsClosed()) {
4774 return;
4775 }
4776 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004777 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004778}
4779
jbauch81bf7b02017-03-25 08:31:12 -07004780void PeerConnection::OnIceCandidate(
4781 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004782 if (IsClosed()) {
4783 return;
4784 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004785 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004786 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004787}
4788
Eldar Relloda13ea22019-06-01 12:23:43 +03004789void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4790 const std::string& url,
4791 int error_code,
4792 const std::string& error_text) {
4793 if (IsClosed()) {
4794 return;
4795 }
4796 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4797}
4798
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004799void PeerConnection::OnIceCandidatesRemoved(
4800 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004801 if (IsClosed()) {
4802 return;
4803 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004804 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004805}
4806
Alex Drake00c7ecf2019-08-06 10:54:47 -07004807void PeerConnection::OnSelectedCandidatePairChanged(
4808 const cricket::CandidatePairChangeEvent& event) {
4809 if (IsClosed()) {
4810 return;
4811 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004812
Qingsi Wangcc46b102019-09-12 11:19:01 -07004813 if (event.selected_candidate_pair.local_candidate().type() ==
4814 LOCAL_PORT_TYPE &&
4815 event.selected_candidate_pair.remote_candidate().type() ==
4816 LOCAL_PORT_TYPE) {
4817 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4818 }
4819
Alex Drake00c7ecf2019-08-06 10:54:47 -07004820 Observer()->OnIceSelectedCandidatePairChanged(event);
4821}
4822
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004823void PeerConnection::ChangeSignalingState(
4824 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004825 if (signaling_state_ == signaling_state) {
4826 return;
4827 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004828 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4829 << GetSignalingStateString(signaling_state_)
4830 << " New state: "
4831 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004832 signaling_state_ = signaling_state;
4833 if (signaling_state == kClosed) {
4834 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004835 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004836 standardized_ice_connection_state_ =
4837 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004838 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4839 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004840 if (ice_gathering_state_ != kIceGatheringComplete) {
4841 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004842 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004843 }
4844 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004845 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004846}
4847
deadbeefeb459812015-12-15 19:24:43 -08004848void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4849 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004850 if (IsClosed()) {
4851 return;
4852 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004853 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004854 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004855}
4856
deadbeefeb459812015-12-15 19:24:43 -08004857void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4858 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004859 if (IsClosed()) {
4860 return;
4861 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004862 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004863 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004864}
4865
4866void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4867 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004868 if (IsClosed()) {
4869 return;
4870 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004871 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004872 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004873}
4874
4875void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4876 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004877 if (IsClosed()) {
4878 return;
4879 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004880 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004881 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004882}
4883
Henrik Boström31638672017-11-23 17:48:32 +01004884void PeerConnection::PostSetSessionDescriptionSuccess(
4885 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004886 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4887 signaling_thread()->Post(RTC_FROM_HERE, this,
4888 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004889}
4890
deadbeefab9b2d12015-10-14 11:33:11 -07004891void PeerConnection::PostSetSessionDescriptionFailure(
4892 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004893 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004894 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004895 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4896 msg->error = std::move(error);
4897 signaling_thread()->Post(RTC_FROM_HERE, this,
4898 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004899}
4900
4901void PeerConnection::PostCreateSessionDescriptionFailure(
4902 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004903 RTCError error) {
4904 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004905 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4906 msg->error = std::move(error);
4907 signaling_thread()->Post(RTC_FROM_HERE, this,
4908 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004909}
4910
zhihuang1c378ed2017-08-17 14:10:50 -07004911void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004912 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004913 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004914 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004915
Steve Antondcc3c022017-12-22 16:02:54 -08004916 if (IsUnifiedPlan()) {
4917 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4918 } else {
4919 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4920 }
4921
Steve Antonfa2260d2017-12-28 16:38:23 -08004922 // Intentionally unset the data channel type for RTP data channel with the
4923 // second condition. Otherwise the RTP data channels would be successfully
4924 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4925 // when building with chromium. We want to leave RTP data channels broken, so
4926 // people won't try to use them.
4927 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4928 session_options->data_channel_type = data_channel_type();
4929 }
4930
Steve Antondcc3c022017-12-22 16:02:54 -08004931 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004932 bool ice_restart = offer_answer_options.ice_restart ||
4933 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004934 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004935 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004936 options.transport_options.enable_ice_renomination =
4937 configuration_.enable_ice_renomination;
4938 }
4939
4940 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004941 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004942 session_options->pooled_ice_credentials =
4943 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4944 RTC_FROM_HERE,
4945 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4946 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004947 session_options->offer_extmap_allow_mixed =
4948 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004949
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004950 if (configuration_.use_media_transport ||
4951 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004952 session_options->media_transport_settings =
4953 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4954 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004955
4956 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004957 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004958 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004959 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004960 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004961 if (!params) {
4962 continue;
4963 }
4964 options.transport_options.opaque_parameters = params;
4965 if ((use_datagram_transport_ &&
4966 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4967 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4968 (use_datagram_transport_for_data_channels_ &&
4969 options.type == cricket::MEDIA_TYPE_DATA)) {
4970 options.alt_protocol = params->protocol;
4971 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004972 }
4973 }
4974
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004975 // Allow fallback for using obsolete SCTP syntax.
4976 // Note that the default in |session_options| is true, while
4977 // the default in |options| is false.
4978 session_options->use_obsolete_sctp_sdp =
4979 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004980}
4981
4982void PeerConnection::GetOptionsForPlanBOffer(
4983 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4984 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004985 // Figure out transceiver directional preferences.
4986 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4987 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4988
4989 // By default, generate sendrecv/recvonly m= sections.
4990 bool recv_audio = true;
4991 bool recv_video = true;
4992
4993 // By default, only offer a new m= section if we have media to send with it.
4994 bool offer_new_audio_description = send_audio;
4995 bool offer_new_video_description = send_video;
4996 bool offer_new_data_description = HasDataChannels();
4997
4998 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004999 if (offer_answer_options.offer_to_receive_audio !=
5000 RTCOfferAnswerOptions::kUndefined) {
5001 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005002 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08005003 offer_new_audio_description ||
5004 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005005 }
Steve Antondcc3c022017-12-22 16:02:54 -08005006 if (offer_answer_options.offer_to_receive_video !=
5007 RTCOfferAnswerOptions::kUndefined) {
5008 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005009 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08005010 offer_new_video_description ||
5011 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005012 }
5013
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005014 absl::optional<size_t> audio_index;
5015 absl::optional<size_t> video_index;
5016 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07005017 // If a current description exists, generate m= sections in the same order,
5018 // using the first audio/video/data section that appears and rejecting
5019 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08005020 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07005021 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08005022 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08005023 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5024 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5025 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07005026 }
5027
zhihuang1c378ed2017-08-17 14:10:50 -07005028 // Add audio/video/data m= sections to the end if needed.
5029 if (!audio_index && offer_new_audio_description) {
5030 session_options->media_description_options.push_back(
5031 cricket::MediaDescriptionOptions(
5032 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08005033 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5034 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005035 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07005036 }
zhihuang1c378ed2017-08-17 14:10:50 -07005037 if (!video_index && offer_new_video_description) {
5038 session_options->media_description_options.push_back(
5039 cricket::MediaDescriptionOptions(
5040 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08005041 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5042 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005043 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07005044 }
zhihuang1c378ed2017-08-17 14:10:50 -07005045 if (!data_index && offer_new_data_description) {
5046 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005047 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005048 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005049 }
5050
5051 cricket::MediaDescriptionOptions* audio_media_description_options =
5052 !audio_index ? nullptr
5053 : &session_options->media_description_options[*audio_index];
5054 cricket::MediaDescriptionOptions* video_media_description_options =
5055 !video_index ? nullptr
5056 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005057
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005058 AddPlanBRtpSenderOptions(GetSendersInternal(),
5059 audio_media_description_options,
5060 video_media_description_options,
5061 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005062}
5063
Steve Antondcc3c022017-12-22 16:02:54 -08005064static cricket::MediaDescriptionOptions
5065GetMediaDescriptionOptionsForTransceiver(
5066 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5067 transceiver,
5068 const std::string& mid) {
5069 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08005070 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08005071 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02005072 media_description_options.codec_preferences =
5073 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08005074 // This behavior is specified in JSEP. The gist is that:
5075 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
5076 // sendrecv.
5077 // 2. If the MSID is included, then it must be included in any subsequent
5078 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005079 if (transceiver->stopped() ||
5080 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
5081 !transceiver->internal()->has_ever_been_used_to_send())) {
5082 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08005083 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005084
5085 cricket::SenderOptions sender_options;
5086 sender_options.track_id = transceiver->sender()->id();
5087 sender_options.stream_ids = transceiver->sender()->stream_ids();
5088
5089 // The following sets up RIDs and Simulcast.
5090 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08005091 RtpParameters send_parameters =
5092 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005093 bool has_rids = std::any_of(send_parameters.encodings.begin(),
5094 send_parameters.encodings.end(),
5095 [](const RtpEncodingParameters& encoding) {
5096 return !encoding.rid.empty();
5097 });
5098
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08005099 std::vector<RidDescription> send_rids;
5100 SimulcastLayerList send_layers;
5101 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
5102 if (encoding.rid.empty()) {
5103 continue;
5104 }
5105 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
5106 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
5107 }
5108
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005109 if (has_rids) {
5110 sender_options.rids = send_rids;
5111 }
5112
5113 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005114 // When RIDs are configured, we must set num_sim_layers to 0 to.
5115 // Otherwise, num_sim_layers must be 1 because either there is no
5116 // simulcast, or simulcast is acheived by munging the SDP.
5117 sender_options.num_sim_layers = has_rids ? 0 : 1;
5118 media_description_options.sender_options.push_back(sender_options);
5119
Steve Antondcc3c022017-12-22 16:02:54 -08005120 return media_description_options;
5121}
5122
Steve Anton5c72e712018-12-10 14:25:30 -08005123// Returns the ContentInfo at mline index |i|, or null if none exists.
5124static const ContentInfo* GetContentByIndex(
5125 const SessionDescriptionInterface* sdesc,
5126 size_t i) {
5127 if (!sdesc) {
5128 return nullptr;
5129 }
5130 const ContentInfos& contents = sdesc->description()->contents();
5131 return (i < contents.size() ? &contents[i] : nullptr);
5132}
5133
Steve Antondcc3c022017-12-22 16:02:54 -08005134void PeerConnection::GetOptionsForUnifiedPlanOffer(
5135 const RTCOfferAnswerOptions& offer_answer_options,
5136 cricket::MediaSessionOptions* session_options) {
5137 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
5138 // Offers) and 5.2.2 (Subsequent Offers).
5139 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02005140 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08005141 const ContentInfos& local_contents =
5142 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005143 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005144 const ContentInfos& remote_contents =
5145 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005146 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005147 // The mline indices that can be recycled. New transceivers should reuse these
5148 // slots first.
5149 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08005150 // First, go through each media section that exists in either the local or
5151 // remote description and generate a media section in this offer for the
5152 // associated transceiver. If a media section can be recycled, generate a
5153 // default, rejected media section here that can be later overwritten.
5154 for (size_t i = 0;
5155 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
5156 // Either |local_content| or |remote_content| is non-null.
5157 const ContentInfo* local_content =
5158 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005159 const ContentInfo* current_local_content =
5160 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08005161 const ContentInfo* remote_content =
5162 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005163 const ContentInfo* current_remote_content =
5164 GetContentByIndex(current_remote_description(), i);
5165 bool had_been_rejected =
5166 (current_local_content && current_local_content->rejected) ||
5167 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08005168 const std::string& mid =
5169 (local_content ? local_content->name : remote_content->name);
5170 cricket::MediaType media_type =
5171 (local_content ? local_content->media_description()->type()
5172 : remote_content->media_description()->type());
5173 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5174 media_type == cricket::MEDIA_TYPE_VIDEO) {
5175 auto transceiver = GetAssociatedTransceiver(mid);
5176 RTC_CHECK(transceiver);
5177 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08005178 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005179 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08005180 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08005181 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
5182 RtpTransceiverDirection::kInactive,
5183 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08005184 recycleable_mline_indices.push(i);
5185 } else {
5186 session_options->media_description_options.push_back(
5187 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
5188 // CreateOffer shouldn't really cause any state changes in
5189 // PeerConnection, but we need a way to match new transceivers to new
5190 // media sections in SetLocalDescription and JSEP specifies this is done
5191 // by recording the index of the media section generated for the
5192 // transceiver in the offer.
5193 transceiver->internal()->set_mline_index(i);
5194 }
5195 } else {
5196 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08005197 RTC_CHECK(GetDataMid());
5198 if (had_been_rejected || mid != *GetDataMid()) {
5199 session_options->media_description_options.push_back(
5200 GetMediaDescriptionOptionsForRejectedData(mid));
5201 } else {
5202 session_options->media_description_options.push_back(
5203 GetMediaDescriptionOptionsForActiveData(mid));
5204 }
Steve Antondcc3c022017-12-22 16:02:54 -08005205 }
5206 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08005207
Steve Antondcc3c022017-12-22 16:02:54 -08005208 // Next, look for transceivers that are newly added (that is, are not stopped
5209 // and not associated). Reuse media sections marked as recyclable first,
5210 // otherwise append to the end of the offer. New media sections should be
5211 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005212 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08005213 if (transceiver->mid() || transceiver->stopped()) {
5214 continue;
5215 }
5216 size_t mline_index;
5217 if (!recycleable_mline_indices.empty()) {
5218 mline_index = recycleable_mline_indices.front();
5219 recycleable_mline_indices.pop();
5220 session_options->media_description_options[mline_index] =
5221 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005222 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08005223 } else {
5224 mline_index = session_options->media_description_options.size();
5225 session_options->media_description_options.push_back(
5226 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005227 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08005228 }
5229 // See comment above for why CreateOffer changes the transceiver's state.
5230 transceiver->internal()->set_mline_index(mline_index);
5231 }
Steve Antonfa2260d2017-12-28 16:38:23 -08005232 // Lastly, add a m-section if we have local data channels and an m section
5233 // does not already exist.
5234 if (!GetDataMid() && HasDataChannels()) {
5235 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08005236 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08005237 }
Steve Antondcc3c022017-12-22 16:02:54 -08005238}
5239
5240void PeerConnection::GetOptionsForAnswer(
5241 const RTCOfferAnswerOptions& offer_answer_options,
5242 cricket::MediaSessionOptions* session_options) {
5243 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
5244
5245 if (IsUnifiedPlan()) {
5246 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
5247 } else {
5248 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
5249 }
5250
Steve Antonfa2260d2017-12-28 16:38:23 -08005251 // Intentionally unset the data channel type for RTP data channel. Otherwise
5252 // the RTP data channels would be successfully negotiated by default and the
5253 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
5254 // We want to leave RTP data channels broken, so people won't try to use them.
5255 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
5256 session_options->data_channel_type = data_channel_type();
5257 }
5258
Steve Antondcc3c022017-12-22 16:02:54 -08005259 // Apply ICE renomination flag.
5260 for (auto& options : session_options->media_description_options) {
5261 options.transport_options.enable_ice_renomination =
5262 configuration_.enable_ice_renomination;
5263 }
zhihuang8f65cdf2016-05-06 18:40:30 -07005264
5265 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005266 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02005267 session_options->pooled_ice_credentials =
5268 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
5269 RTC_FROM_HERE,
5270 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
5271 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005272
5273 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005274 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005275 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005276 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005277 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005278 if (!params) {
5279 continue;
5280 }
5281 options.transport_options.opaque_parameters = params;
5282 if ((use_datagram_transport_ &&
5283 (options.type == cricket::MEDIA_TYPE_AUDIO ||
5284 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
5285 (use_datagram_transport_for_data_channels_ &&
5286 options.type == cricket::MEDIA_TYPE_DATA)) {
5287 options.alt_protocol = params->protocol;
5288 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005289 }
5290 }
deadbeefab9b2d12015-10-14 11:33:11 -07005291}
5292
Steve Antondcc3c022017-12-22 16:02:54 -08005293void PeerConnection::GetOptionsForPlanBAnswer(
5294 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07005295 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005296 // Figure out transceiver directional preferences.
5297 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
5298 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
5299
5300 // By default, generate sendrecv/recvonly m= sections. The direction is also
5301 // restricted by the direction in the offer.
5302 bool recv_audio = true;
5303 bool recv_video = true;
5304
5305 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08005306 if (offer_answer_options.offer_to_receive_audio !=
5307 RTCOfferAnswerOptions::kUndefined) {
5308 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08005309 }
Steve Antondcc3c022017-12-22 16:02:54 -08005310 if (offer_answer_options.offer_to_receive_video !=
5311 RTCOfferAnswerOptions::kUndefined) {
5312 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005313 }
5314
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005315 absl::optional<size_t> audio_index;
5316 absl::optional<size_t> video_index;
5317 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08005318
5319 // Generate m= sections that match those in the offer.
5320 // Note that mediasession.cc will handle intersection our preferred
5321 // direction with the offered direction.
5322 GenerateMediaDescriptionOptions(
5323 remote_description(),
5324 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5325 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
5326 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07005327
5328 cricket::MediaDescriptionOptions* audio_media_description_options =
5329 !audio_index ? nullptr
5330 : &session_options->media_description_options[*audio_index];
5331 cricket::MediaDescriptionOptions* video_media_description_options =
5332 !video_index ? nullptr
5333 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005334
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005335 AddPlanBRtpSenderOptions(GetSendersInternal(),
5336 audio_media_description_options,
5337 video_media_description_options,
5338 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005339}
zhihuangaf388472016-11-02 16:49:48 -07005340
Steve Antondcc3c022017-12-22 16:02:54 -08005341void PeerConnection::GetOptionsForUnifiedPlanAnswer(
5342 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
5343 cricket::MediaSessionOptions* session_options) {
5344 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
5345 // Answers) and 5.3.2 (Subsequent Answers).
5346 RTC_DCHECK(remote_description());
5347 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
5348 for (const ContentInfo& content :
5349 remote_description()->description()->contents()) {
5350 cricket::MediaType media_type = content.media_description()->type();
5351 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5352 media_type == cricket::MEDIA_TYPE_VIDEO) {
5353 auto transceiver = GetAssociatedTransceiver(content.name);
5354 RTC_CHECK(transceiver);
5355 session_options->media_description_options.push_back(
5356 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
5357 } else {
5358 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08005359 // Reject all data sections if data channels are disabled.
5360 // Reject a data section if it has already been rejected.
5361 // Reject all data sections except for the first one.
5362 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
5363 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005364 session_options->media_description_options.push_back(
5365 GetMediaDescriptionOptionsForRejectedData(content.name));
5366 } else {
5367 session_options->media_description_options.push_back(
5368 GetMediaDescriptionOptionsForActiveData(content.name));
5369 }
Steve Antondcc3c022017-12-22 16:02:54 -08005370 }
5371 }
htaa2a49d92016-03-04 02:51:39 -08005372}
5373
zhihuang1c378ed2017-08-17 14:10:50 -07005374void PeerConnection::GenerateMediaDescriptionOptions(
5375 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08005376 RtpTransceiverDirection audio_direction,
5377 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005378 absl::optional<size_t>* audio_index,
5379 absl::optional<size_t>* video_index,
5380 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08005381 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005382 for (const cricket::ContentInfo& content :
5383 session_desc->description()->contents()) {
5384 if (IsAudioContent(&content)) {
5385 // If we already have an audio m= section, reject this extra one.
5386 if (*audio_index) {
5387 session_options->media_description_options.push_back(
5388 cricket::MediaDescriptionOptions(
5389 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005390 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005391 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005392 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005393 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005394 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5395 content.name, audio_direction,
5396 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005397 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005398 }
5399 } else if (IsVideoContent(&content)) {
5400 // If we already have an video m= section, reject this extra one.
5401 if (*video_index) {
5402 session_options->media_description_options.push_back(
5403 cricket::MediaDescriptionOptions(
5404 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005405 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005406 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005407 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005408 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005409 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5410 content.name, video_direction,
5411 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005412 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005413 }
5414 } else {
5415 RTC_DCHECK(IsDataContent(&content));
5416 // If we already have an data m= section, reject this extra one.
5417 if (*data_index) {
5418 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005419 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005420 } else {
5421 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005422 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005423 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005424 }
5425 }
htaa2a49d92016-03-04 02:51:39 -08005426 }
deadbeefab9b2d12015-10-14 11:33:11 -07005427}
5428
Steve Antonfa2260d2017-12-28 16:38:23 -08005429cricket::MediaDescriptionOptions
5430PeerConnection::GetMediaDescriptionOptionsForActiveData(
5431 const std::string& mid) const {
5432 // Direction for data sections is meaningless, but legacy endpoints might
5433 // expect sendrecv.
5434 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5435 RtpTransceiverDirection::kSendRecv,
5436 /*stopped=*/false);
5437 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5438 return options;
5439}
5440
5441cricket::MediaDescriptionOptions
5442PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5443 const std::string& mid) const {
5444 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5445 RtpTransceiverDirection::kInactive,
5446 /*stopped=*/true);
5447 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5448 return options;
5449}
5450
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005451absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08005452 switch (data_channel_type_) {
5453 case cricket::DCT_RTP:
5454 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005455 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005456 }
5457 return rtp_data_channel_->content_name();
5458 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005459 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005460 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5461 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5462 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005463 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005464 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005465 }
5466}
5467
Steve Anton4171afb2017-11-20 10:20:22 -08005468void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5469 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5470 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005471 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005472}
5473
Steve Anton4171afb2017-11-20 10:20:22 -08005474void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005475 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005476 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005477 cricket::MediaType media_type,
5478 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005479 RTC_DCHECK(!IsUnifiedPlan());
5480
Steve Anton4171afb2017-11-20 10:20:22 -08005481 std::vector<RtpSenderInfo>* current_senders =
5482 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005483
Steve Anton4171afb2017-11-20 10:20:22 -08005484 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005485 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005486 for (auto sender_it = current_senders->begin();
5487 sender_it != current_senders->end();
5488 /* incremented manually */) {
5489 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005490 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005491 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005492 std::string params_stream_id;
5493 if (params) {
5494 params_stream_id =
5495 (!params->first_stream_id().empty() ? params->first_stream_id()
5496 : kDefaultStreamId);
5497 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005498 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005499 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005500 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005501 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005502 sender_exists) {
5503 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005504 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005505 OnRemoteSenderRemoved(info, media_type);
5506 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005507 }
5508 }
5509
Steve Anton4171afb2017-11-20 10:20:22 -08005510 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005511 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005512 if (!params.has_ssrcs()) {
5513 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5514 // sender, this means it is coming from a Unified Plan endpoint,so we just
5515 // create a default.
5516 default_sender_needed = true;
5517 break;
5518 }
5519
Seth Hampson845e8782018-03-02 11:34:10 -08005520 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005521 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005522 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5523 // not supported in Plan B, we just take the first here and create the
5524 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005525 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005526 (!params.first_stream_id().empty() ? params.first_stream_id()
5527 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005528 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005529 uint32_t ssrc = params.first_ssrc();
5530
5531 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005532 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005533 if (!stream) {
5534 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005535 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005536 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005537 remote_streams_->AddStream(stream);
5538 new_streams->AddStream(stream);
5539 }
5540
Steve Anton4171afb2017-11-20 10:20:22 -08005541 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005542 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005543 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005544 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005545 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005546 }
5547 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005548
Steve Anton4171afb2017-11-20 10:20:22 -08005549 // Add default sender if necessary.
5550 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005551 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005552 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005553 if (!default_stream) {
5554 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005555 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005556 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005557 remote_streams_->AddStream(default_stream);
5558 new_streams->AddStream(default_stream);
5559 }
Steve Anton4171afb2017-11-20 10:20:22 -08005560 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5561 ? kDefaultAudioSenderId
5562 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005563 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005564 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005565 if (!default_sender_info) {
5566 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005567 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005568 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005569 }
5570 }
deadbeefab9b2d12015-10-14 11:33:11 -07005571}
5572
Steve Anton4171afb2017-11-20 10:20:22 -08005573void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5574 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005575 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5576 << " receiver for track_id=" << sender_info.sender_id
5577 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005578
Steve Anton3d954a62018-04-02 11:27:23 -07005579 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005580 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005581 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005582 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005583 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005584 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005585 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005586 }
5587}
5588
Steve Anton4171afb2017-11-20 10:20:22 -08005589void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5590 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005591 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5592 << " receiver for track_id=" << sender_info.sender_id
5593 << " and stream_id=" << sender_info.stream_id;
5594
Seth Hampson845e8782018-03-02 11:34:10 -08005595 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005596
Henrik Boström933d8b02017-10-10 10:05:16 -07005597 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005598 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005599 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5600 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005601 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005602 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005603 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005604 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005605 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005606 }
5607 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005608 // Stopping or destroying a VideoRtpReceiver will end the
5609 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005610 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005611 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005612 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005613 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005614 // There's no guarantee the track is still available, e.g. the track may
5615 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005616 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005617 }
5618 } else {
nisseede5da42017-01-12 05:15:36 -08005619 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005620 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005621 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005622 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005623 }
deadbeefab9b2d12015-10-14 11:33:11 -07005624}
5625
5626void PeerConnection::UpdateEndedRemoteMediaStreams() {
5627 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5628 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5629 MediaStreamInterface* stream = remote_streams_->at(i);
5630 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5631 streams_to_remove.push_back(stream);
5632 }
5633 }
5634
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005635 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005636 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005637 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005638 }
5639}
5640
Steve Anton4171afb2017-11-20 10:20:22 -08005641void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005642 const std::vector<cricket::StreamParams>& streams,
5643 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005644 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005645
Seth Hampson845e8782018-03-02 11:34:10 -08005646 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005647 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005648 for (auto sender_it = current_senders->begin();
5649 sender_it != current_senders->end();
5650 /* incremented manually */) {
5651 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005652 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005653 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5654 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005655 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005656 OnLocalSenderRemoved(info, media_type);
5657 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005658 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005659 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005660 }
5661 }
5662
Steve Anton4171afb2017-11-20 10:20:22 -08005663 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005664 for (const cricket::StreamParams& params : streams) {
5665 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005666 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005667 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005668 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005669 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005670 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005671 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005672 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005673 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005674 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005675 }
5676 }
5677}
5678
Steve Anton4171afb2017-11-20 10:20:22 -08005679void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5680 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005681 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005682 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005683 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005684 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5685 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005686 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005687 return;
5688 }
5689
deadbeeffac06552015-11-25 11:26:01 -08005690 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005691 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005692 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005693 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005694 }
deadbeeffac06552015-11-25 11:26:01 -08005695
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005696 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005697 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005698}
5699
Steve Anton4171afb2017-11-20 10:20:22 -08005700void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5701 cricket::MediaType media_type) {
5702 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005703 if (!sender) {
5704 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005705 // SessionDescriptions has been renegotiated.
5706 return;
5707 }
deadbeeffac06552015-11-25 11:26:01 -08005708
5709 // A sender has been removed from the SessionDescription but it's still
5710 // associated with the PeerConnection. This only occurs if the SDP doesn't
5711 // match with the calls to CreateSender, AddStream and RemoveStream.
5712 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005713 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005714 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005715 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005716 }
deadbeeffac06552015-11-25 11:26:01 -08005717
Steve Anton4171afb2017-11-20 10:20:22 -08005718 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005719}
5720
5721void PeerConnection::UpdateLocalRtpDataChannels(
5722 const cricket::StreamParamsVec& streams) {
5723 std::vector<std::string> existing_channels;
5724
5725 // Find new and active data channels.
5726 for (const cricket::StreamParams& params : streams) {
5727 // |it->sync_label| is actually the data channel label. The reason is that
5728 // we use the same naming of data channels as we do for
5729 // MediaStreams and Tracks.
5730 // For MediaStreams, the sync_label is the MediaStream label and the
5731 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005732 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005733 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005734 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005735 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005736 continue;
5737 }
5738 // Set the SSRC the data channel should use for sending.
5739 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5740 existing_channels.push_back(data_channel_it->first);
5741 }
5742
5743 UpdateClosingRtpDataChannels(existing_channels, true);
5744}
5745
5746void PeerConnection::UpdateRemoteRtpDataChannels(
5747 const cricket::StreamParamsVec& streams) {
5748 std::vector<std::string> existing_channels;
5749
5750 // Find new and active data channels.
5751 for (const cricket::StreamParams& params : streams) {
5752 // The data channel label is either the mslabel or the SSRC if the mslabel
5753 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005754 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005755 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005756 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005757 auto data_channel_it = rtp_data_channels_.find(label);
5758 if (data_channel_it == rtp_data_channels_.end()) {
5759 // This is a new data channel.
5760 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5761 } else {
5762 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5763 }
5764 existing_channels.push_back(label);
5765 }
5766
5767 UpdateClosingRtpDataChannels(existing_channels, false);
5768}
5769
5770void PeerConnection::UpdateClosingRtpDataChannels(
5771 const std::vector<std::string>& active_channels,
5772 bool is_local_update) {
5773 auto it = rtp_data_channels_.begin();
5774 while (it != rtp_data_channels_.end()) {
5775 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005776 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005777 ++it;
5778 continue;
5779 }
5780
5781 if (is_local_update) {
5782 data_channel->SetSendSsrc(0);
5783 } else {
5784 data_channel->RemotePeerRequestClose();
5785 }
5786
5787 if (data_channel->state() == DataChannel::kClosed) {
5788 rtp_data_channels_.erase(it);
5789 it = rtp_data_channels_.begin();
5790 } else {
5791 ++it;
5792 }
5793 }
5794}
5795
5796void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5797 uint32_t remote_ssrc) {
5798 rtc::scoped_refptr<DataChannel> channel(
5799 InternalCreateDataChannel(label, nullptr));
5800 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005801 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005802 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005803 return;
5804 }
5805 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005806 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5807 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005808 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005809}
5810
5811rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5812 const std::string& label,
5813 const InternalDataChannelInit* config) {
5814 if (IsClosed()) {
5815 return nullptr;
5816 }
Steve Anton75737c02017-11-06 10:37:17 -08005817 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005818 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005819 << "InternalCreateDataChannel: Data is not supported in this call.";
5820 return nullptr;
5821 }
5822 InternalDataChannelInit new_config =
5823 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005824 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005825 if (new_config.id < 0) {
5826 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005827 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005828 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005829 RTC_LOG(LS_ERROR)
5830 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005831 return nullptr;
5832 }
5833 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005834 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005835 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005836 return nullptr;
5837 }
5838 }
5839
Steve Anton75737c02017-11-06 10:37:17 -08005840 rtc::scoped_refptr<DataChannel> channel(
5841 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005842 if (!channel) {
5843 sid_allocator_.ReleaseSid(new_config.id);
5844 return nullptr;
5845 }
5846
5847 if (channel->data_channel_type() == cricket::DCT_RTP) {
5848 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005849 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5850 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005851 return nullptr;
5852 }
5853 rtp_data_channels_[channel->label()] = channel;
5854 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005855 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005856 sctp_data_channels_.push_back(channel);
5857 channel->SignalClosed.connect(this,
5858 &PeerConnection::OnSctpDataChannelClosed);
5859 }
5860
Steve Anton2d8609c2018-01-23 16:38:46 -08005861 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005862 return channel;
5863}
5864
5865bool PeerConnection::HasDataChannels() const {
5866 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5867}
5868
5869void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005870 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005871 for (const auto& channel : sctp_data_channels_) {
5872 if (channel->id() < 0) {
5873 int sid;
5874 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005875 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5876 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005877 continue;
5878 }
5879 channel->SetSctpSid(sid);
5880 }
5881 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005882 // Since closing modifies the list of channels, we have to do the actual
5883 // closing outside the loop.
5884 for (const auto& channel : channels_to_close) {
5885 channel->CloseAbruptly();
5886 }
deadbeefab9b2d12015-10-14 11:33:11 -07005887}
5888
5889void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005890 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005891 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5892 ++it) {
5893 if (it->get() == channel) {
5894 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005895 // After the closing procedure is done, it's safe to use this ID for
5896 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005897 sid_allocator_.ReleaseSid(channel->id());
5898 }
deadbeefbd292462015-12-14 18:15:29 -08005899 // Since this method is triggered by a signal from the DataChannel,
5900 // we can't free it directly here; we need to free it asynchronously.
5901 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005902 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005903 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5904 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005905 return;
5906 }
5907 }
5908}
5909
deadbeefab9b2d12015-10-14 11:33:11 -07005910void PeerConnection::OnDataChannelDestroyed() {
5911 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5912 // DataChannel may callback to us and try to modify the list.
5913 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5914 temp_rtp_dcs.swap(rtp_data_channels_);
5915 for (const auto& kv : temp_rtp_dcs) {
5916 kv.second->OnTransportChannelDestroyed();
5917 }
5918
5919 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5920 temp_sctp_dcs.swap(sctp_data_channels_);
5921 for (const auto& channel : temp_sctp_dcs) {
5922 channel->OnTransportChannelDestroyed();
5923 }
5924}
5925
5926void PeerConnection::OnDataChannelOpenMessage(
5927 const std::string& label,
5928 const InternalDataChannelInit& config) {
5929 rtc::scoped_refptr<DataChannel> channel(
5930 InternalCreateDataChannel(label, &config));
5931 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005932 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005933 return;
5934 }
5935
deadbeefa601f5c2016-06-06 14:27:39 -07005936 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5937 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005938 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005939 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005940}
5941
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005942bool PeerConnection::HandleOpenMessage_s(
5943 const cricket::ReceiveDataParams& params,
5944 const rtc::CopyOnWriteBuffer& buffer) {
5945 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5946 // Received OPEN message; parse and signal that a new data channel should
5947 // be created.
5948 std::string label;
5949 InternalDataChannelInit config;
5950 config.id = params.ssrc;
5951 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5952 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5953 << params.ssrc;
5954 return true;
5955 }
5956 config.open_handshake_role = InternalDataChannelInit::kAcker;
5957 OnDataChannelOpenMessage(label, config);
5958 return true;
5959 }
5960 return false;
5961}
5962
Steve Anton4171afb2017-11-20 10:20:22 -08005963rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5964PeerConnection::GetAudioTransceiver() const {
5965 // This method only works with Plan B SDP, where there is a single
5966 // audio/video transceiver.
5967 RTC_DCHECK(!IsUnifiedPlan());
5968 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005969 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005970 return transceiver;
5971 }
5972 }
5973 RTC_NOTREACHED();
5974 return nullptr;
5975}
5976
5977rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5978PeerConnection::GetVideoTransceiver() const {
5979 // This method only works with Plan B SDP, where there is a single
5980 // audio/video transceiver.
5981 RTC_DCHECK(!IsUnifiedPlan());
5982 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005983 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005984 return transceiver;
5985 }
5986 }
5987 RTC_NOTREACHED();
5988 return nullptr;
5989}
5990
5991// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5992// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005993bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005994 switch (type) {
5995 case cricket::MEDIA_TYPE_AUDIO:
5996 return !GetAudioTransceiver()->internal()->senders().empty();
5997 case cricket::MEDIA_TYPE_VIDEO:
5998 return !GetVideoTransceiver()->internal()->senders().empty();
5999 case cricket::MEDIA_TYPE_DATA:
6000 return false;
6001 }
6002 RTC_NOTREACHED();
6003 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07006004}
6005
Steve Anton4171afb2017-11-20 10:20:22 -08006006rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
6007PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006008 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08006009 for (auto sender : transceiver->internal()->senders()) {
6010 if (sender->track() == track) {
6011 return sender;
6012 }
6013 }
6014 }
6015 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08006016}
6017
Steve Anton4171afb2017-11-20 10:20:22 -08006018rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
6019PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006020 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08006021 for (auto sender : transceiver->internal()->senders()) {
6022 if (sender->id() == sender_id) {
6023 return sender;
6024 }
6025 }
6026 }
6027 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07006028}
6029
Steve Anton4171afb2017-11-20 10:20:22 -08006030rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
6031PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006032 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08006033 for (auto receiver : transceiver->internal()->receivers()) {
6034 if (receiver->id() == receiver_id) {
6035 return receiver;
6036 }
6037 }
6038 }
6039 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07006040}
6041
Steve Anton4171afb2017-11-20 10:20:22 -08006042std::vector<PeerConnection::RtpSenderInfo>*
6043PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
6044 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6045 media_type == cricket::MEDIA_TYPE_VIDEO);
6046 return (media_type == cricket::MEDIA_TYPE_AUDIO)
6047 ? &remote_audio_sender_infos_
6048 : &remote_video_sender_infos_;
6049}
6050
6051std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07006052 cricket::MediaType media_type) {
6053 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6054 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08006055 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
6056 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07006057}
6058
Steve Anton4171afb2017-11-20 10:20:22 -08006059const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
6060 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00006061 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08006062 const std::string sender_id) const {
6063 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00006064 if (sender_info.stream_id == stream_id &&
6065 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08006066 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07006067 }
6068 }
6069 return nullptr;
6070}
6071
6072DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
6073 for (const auto& channel : sctp_data_channels_) {
6074 if (channel->id() == sid) {
6075 return channel;
6076 }
6077 }
6078 return nullptr;
6079}
6080
Karl Wibergfb3be392019-03-22 14:13:22 +01006081PeerConnection::InitializePortAllocatorResult
6082PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02006083 const cricket::ServerAddresses& stun_servers,
6084 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006085 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006086 RTC_DCHECK_RUN_ON(network_thread());
6087
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07006088 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006089 // To handle both internal and externally created port allocator, we will
6090 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01006091 int port_allocator_flags = port_allocator_->flags();
6092 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
6093 cricket::PORTALLOCATOR_ENABLE_IPV6 |
6094 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006095 // If the disable-IPv6 flag was specified, we'll not override it
6096 // by experiment.
6097 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006098 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08006099 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
6100 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006101 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006102 }
6103
zhihuangb09b3f92017-03-07 14:40:51 -08006104 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006105 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01006106 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08006107 }
6108
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006109 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006110 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01006111 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006112 }
6113
honghaiz60347052016-05-31 18:29:12 -07006114 if (configuration.candidate_network_policy ==
6115 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006116 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01006117 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07006118 }
6119
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01006120 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006121 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01006122 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
6123 }
6124
Karl Wibergfb3be392019-03-22 14:13:22 +01006125 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006126 // No step delay is used while allocating ports.
6127 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07006128 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006129 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07006130 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006131
Harald Alvestrandb2a74782018-06-28 13:54:07 +02006132 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07006133 for (auto& turn_server : turn_servers_copy) {
6134 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07006135 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006136 // Call this last since it may create pooled allocator sessions using the
6137 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006138 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07006139 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006140 configuration.ice_candidate_pool_size,
6141 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006142 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01006143
6144 InitializePortAllocatorResult res;
6145 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
6146 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006147}
6148
deadbeef91dd5672016-05-18 16:55:30 -07006149bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08006150 const cricket::ServerAddresses& stun_servers,
6151 const std::vector<cricket::RelayServerConfig>& turn_servers,
6152 IceTransportsType type,
6153 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006154 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006155 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02006156 absl::optional<int> stun_candidate_keepalive_interval,
6157 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07006158 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08006159 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07006160 // According to JSEP, after setLocalDescription, changing the candidate pool
6161 // size is not allowed, and changing the set of ICE servers will not result
6162 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02006163 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07006164 port_allocator_->FreezeCandidatePool();
6165 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07006166 // Add the custom tls turn servers if they exist.
6167 auto turn_servers_copy = turn_servers;
6168 for (auto& turn_server : turn_servers_copy) {
6169 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
6170 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006171 // Call this last since it may create pooled allocator sessions using the
6172 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08006173 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07006174 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006175 turn_port_prune_policy, turn_customizer,
6176 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006177}
6178
Steve Antonba818672017-11-06 10:21:57 -08006179cricket::ChannelManager* PeerConnection::channel_manager() const {
6180 return factory_->channel_manager();
6181}
6182
Elad Alon99c3fe52017-10-13 16:29:40 +02006183bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01006184 std::unique_ptr<RtcEventLogOutput> output,
6185 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01006186 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006187 if (!event_log_) {
6188 return false;
6189 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01006190 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07006191}
6192
6193void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01006194 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006195 if (event_log_) {
6196 event_log_->StopLogging();
6197 }
ivoc14d5dbe2016-07-04 07:06:55 -07006198}
nisseeaabdf62017-05-05 02:23:02 -07006199
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006200cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08006201 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006202 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006203 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08006204 if (channel && channel->content_name() == content_name) {
6205 return channel;
6206 }
Steve Anton75737c02017-11-06 10:37:17 -08006207 }
6208 if (rtp_data_channel() &&
6209 rtp_data_channel()->content_name() == content_name) {
6210 return rtp_data_channel();
6211 }
6212 return nullptr;
6213}
6214
6215bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006216 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006217 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006218 RTC_LOG(LS_INFO)
6219 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006220 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006221 return false;
6222 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006223 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006224 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006225 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006226 return false;
6227 }
6228
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006229 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006230 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006231 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006232 if (!dtls_role && is_caller_.has_value()) {
6233 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
6234 }
Zhi Huange830e682018-03-30 10:48:35 -07006235 *role = *dtls_role;
6236 return true;
6237 }
6238 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006239}
6240
6241bool PeerConnection::GetSslRole(const std::string& content_name,
6242 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006243 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006244 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006245 RTC_LOG(LS_INFO)
6246 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006247 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08006248 return false;
6249 }
6250
Zhi Huange830e682018-03-30 10:48:35 -07006251 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
6252 if (dtls_role) {
6253 *role = *dtls_role;
6254 return true;
6255 }
6256 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006257}
6258
Steve Antonf8470812017-12-04 10:46:21 -08006259void PeerConnection::SetSessionError(SessionError error,
6260 const std::string& error_desc) {
6261 RTC_DCHECK_RUN_ON(signaling_thread());
6262 if (error != session_error_) {
6263 session_error_ = error;
6264 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08006265 }
6266}
6267
Zhi Huange830e682018-03-30 10:48:35 -07006268RTCError PeerConnection::UpdateSessionState(
6269 SdpType type,
6270 cricket::ContentSource source,
6271 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08006272 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006273
6274 // If there's already a pending error then no state transition should happen.
6275 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08006276 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006277
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006278 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08006279 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08006280 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006281 }
6282
6283 // Update the signaling state according to the specified state machine (see
6284 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08006285 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006286 ChangeSignalingState(source == cricket::CS_LOCAL
6287 ? PeerConnectionInterface::kHaveLocalOffer
6288 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08006289 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006290 ChangeSignalingState(source == cricket::CS_LOCAL
6291 ? PeerConnectionInterface::kHaveLocalPrAnswer
6292 : PeerConnectionInterface::kHaveRemotePrAnswer);
6293 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006294 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006295 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03006296 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006297 }
6298
6299 // Update internal objects according to the session description's media
6300 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07006301 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006302 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08006303 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006304 }
6305
Steve Anton8a006912017-12-04 15:25:56 -08006306 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006307}
6308
Steve Anton8a006912017-12-04 15:25:56 -08006309RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08006310 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08006311 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08006312 const SessionDescriptionInterface* sdesc =
6313 (source == cricket::CS_LOCAL ? local_description()
6314 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08006315 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08006316
6317 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01006318 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08006319 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08006320 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006321 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006322 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08006323 continue;
6324 }
6325 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006326 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006327 if (!content_desc) {
6328 continue;
6329 }
6330 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02006331 bool success = (source == cricket::CS_LOCAL)
6332 ? channel->SetLocalContent(content_desc, type, &error)
6333 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006334 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006336 }
6337 }
6338
6339 // If using the RtpDataChannel, push down the new SDP section for it too.
6340 if (rtp_data_channel_) {
6341 const ContentInfo* data_content =
6342 cricket::GetFirstDataContent(sdesc->description());
6343 if (data_content && !data_content->rejected) {
6344 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006345 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006346 if (data_desc) {
6347 std::string error;
6348 bool success =
6349 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08006350 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02006351 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006352 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006353 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006354 }
Steve Anton75737c02017-11-06 10:37:17 -08006355 }
6356 }
6357 }
Steve Antoned10bd92017-12-05 10:52:59 -08006358
Steve Anton75737c02017-11-06 10:37:17 -08006359 // Need complete offer/answer with an SCTP m= section before starting SCTP,
6360 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006361 if (sctp_mid_ && local_description() && remote_description()) {
6362 rtc::scoped_refptr<SctpTransport> sctp_transport =
6363 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006364 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
6365 local_description()->description());
6366 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
6367 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006368 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02006369 int max_message_size;
6370 // A remote max message size of zero means "any size supported".
6371 // We configure the connection with our own max message size.
6372 if (remote_sctp_description->max_message_size() == 0) {
6373 max_message_size = local_sctp_description->max_message_size();
6374 } else {
6375 max_message_size =
6376 std::min(local_sctp_description->max_message_size(),
6377 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006378 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006379 sctp_transport->Start(local_sctp_description->port(),
6380 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08006381 }
Steve Anton75737c02017-11-06 10:37:17 -08006382 }
Steve Antoned10bd92017-12-05 10:52:59 -08006383
Steve Anton8a006912017-12-04 15:25:56 -08006384 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006385}
6386
Steve Anton8a006912017-12-04 15:25:56 -08006387RTCError PeerConnection::PushdownTransportDescription(
6388 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08006389 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08006390 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006391
Zhi Huange830e682018-03-30 10:48:35 -07006392 if (source == cricket::CS_LOCAL) {
6393 const SessionDescriptionInterface* sdesc = local_description();
6394 RTC_DCHECK(sdesc);
6395 return transport_controller_->SetLocalDescription(type,
6396 sdesc->description());
6397 } else {
6398 const SessionDescriptionInterface* sdesc = remote_description();
6399 RTC_DCHECK(sdesc);
6400 return transport_controller_->SetRemoteDescription(type,
6401 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006402 }
Steve Anton75737c02017-11-06 10:37:17 -08006403}
6404
6405bool PeerConnection::GetTransportDescription(
6406 const SessionDescription* description,
6407 const std::string& content_name,
6408 cricket::TransportDescription* tdesc) {
6409 if (!description || !tdesc) {
6410 return false;
6411 }
6412 const TransportInfo* transport_info =
6413 description->GetTransportInfoByName(content_name);
6414 if (!transport_info) {
6415 return false;
6416 }
6417 *tdesc = transport_info->description;
6418 return true;
6419}
6420
Steve Anton75737c02017-11-06 10:37:17 -08006421cricket::IceConfig PeerConnection::ParseIceConfig(
6422 const PeerConnectionInterface::RTCConfiguration& config) const {
6423 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006424 switch (config.continual_gathering_policy) {
6425 case PeerConnectionInterface::GATHER_ONCE:
6426 gathering_policy = cricket::GATHER_ONCE;
6427 break;
6428 case PeerConnectionInterface::GATHER_CONTINUALLY:
6429 gathering_policy = cricket::GATHER_CONTINUALLY;
6430 break;
6431 default:
6432 RTC_NOTREACHED();
6433 gathering_policy = cricket::GATHER_ONCE;
6434 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006435
Steve Anton75737c02017-11-06 10:37:17 -08006436 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006437 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6438 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006439 ice_config.prioritize_most_likely_candidate_pairs =
6440 config.prioritize_most_likely_ice_candidate_pairs;
6441 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006442 RTCConfigurationToIceConfigOptionalInt(
6443 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006444 ice_config.continual_gathering_policy = gathering_policy;
6445 ice_config.presume_writable_when_fully_relayed =
6446 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006447 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6448 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006449 ice_config.ice_check_interval_strong_connectivity =
6450 config.ice_check_interval_strong_connectivity;
6451 ice_config.ice_check_interval_weak_connectivity =
6452 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006453 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006454 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6455 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006456 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006457 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08006458 ice_config.regather_all_networks_interval_range =
6459 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006460 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006461 return ice_config;
6462}
6463
Steve Anton75737c02017-11-06 10:37:17 -08006464bool PeerConnection::SendData(const cricket::SendDataParams& params,
6465 const rtc::CopyOnWriteBuffer& payload,
6466 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006467 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006468 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006469 SendDataParams send_params;
6470 send_params.type = ToWebrtcDataMessageType(params.type);
6471 send_params.ordered = params.ordered;
6472 if (params.max_rtx_count >= 0) {
6473 send_params.max_rtx_count = params.max_rtx_count;
6474 } else if (params.max_rtx_ms >= 0) {
6475 send_params.max_rtx_ms = params.max_rtx_ms;
6476 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006477
6478 RTCError error = network_thread()->Invoke<RTCError>(
6479 RTC_FROM_HERE, [this, params, send_params, payload] {
6480 return data_channel_transport_->SendData(params.sid, send_params,
6481 payload);
6482 });
6483
6484 if (error.ok()) {
6485 *result = cricket::SendDataResult::SDR_SUCCESS;
6486 return true;
6487 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6488 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6489 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6490 *result = cricket::SendDataResult::SDR_BLOCK;
6491 return false;
6492 }
6493 *result = cricket::SendDataResult::SDR_ERROR;
6494 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006495 } else if (rtp_data_channel_) {
6496 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006497 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006498 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6499 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006500}
6501
6502bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006503 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006504 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006505 // Don't log an error here, because DataChannels are expected to call
6506 // ConnectDataChannel in this state. It's the only way to initially tell
6507 // whether or not the underlying transport is ready.
6508 return false;
6509 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006510 if (data_channel_transport_) {
6511 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6512 &DataChannel::OnChannelReady);
6513 SignalDataChannelTransportReceivedData_s.connect(
6514 webrtc_data_channel, &DataChannel::OnDataReceived);
6515 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006516 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006517 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006518 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006519 }
6520 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006521 rtp_data_channel_->SignalReadyToSendData.connect(
6522 webrtc_data_channel, &DataChannel::OnChannelReady);
6523 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6524 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006525 }
Steve Anton75737c02017-11-06 10:37:17 -08006526 return true;
6527}
6528
6529void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006530 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006531 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006532 RTC_LOG(LS_ERROR)
6533 << "DisconnectDataChannel called when rtp_data_channel_ and "
6534 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006535 return;
6536 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006537 if (data_channel_transport_) {
6538 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6539 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6540 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6541 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6542 }
6543 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006544 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6545 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006546 }
Steve Anton75737c02017-11-06 10:37:17 -08006547}
6548
6549void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006550 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006551 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6552 if (data_channel_transport_) {
6553 data_channel_transport_->OpenChannel(sid);
6554 }
6555 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006556 }
Steve Anton75737c02017-11-06 10:37:17 -08006557}
6558
6559void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006560 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006561 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6562 if (data_channel_transport_) {
6563 data_channel_transport_->CloseChannel(sid);
6564 }
6565 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006566 }
Steve Anton75737c02017-11-06 10:37:17 -08006567}
6568
6569bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006570 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006571 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006572 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006573}
6574
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006575void PeerConnection::OnDataReceived(int channel_id,
6576 DataMessageType type,
6577 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006578 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006579 cricket::ReceiveDataParams params;
6580 params.sid = channel_id;
6581 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006582 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006583 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6584 RTC_DCHECK_RUN_ON(signaling_thread());
6585 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006586 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006587 }
6588 });
6589}
6590
6591void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006592 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006593 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006594 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6595 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006596 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006597 });
6598}
6599
6600void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006601 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006602 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006603 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6604 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006605 SignalDataChannelTransportChannelClosed_s(channel_id);
6606 });
6607}
6608
6609void PeerConnection::OnReadyToSend() {
6610 RTC_DCHECK_RUN_ON(network_thread());
6611 data_channel_transport_invoker_->AsyncInvoke<void>(
6612 RTC_FROM_HERE, signaling_thread(), [this] {
6613 RTC_DCHECK_RUN_ON(signaling_thread());
6614 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006615 SignalDataChannelTransportWritable_s(
6616 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006617 });
6618}
6619
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006620absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006621 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006622 if (sctp_mid_ && transport_controller_) {
6623 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6624 if (dtls_transport) {
6625 return dtls_transport->transport_name();
6626 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006627 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006628 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006629 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006630}
6631
Qingsi Wang72a43a12018-02-20 16:03:18 -08006632cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6633 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006634 network_thread()->Invoke<void>(
6635 RTC_FROM_HERE,
6636 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6637 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006638 return candidate_states_list;
6639}
6640
Steve Anton5dfde182018-02-06 10:34:40 -08006641std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6642 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006643 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006644 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006645 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006646 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006647 if (channel) {
6648 transport_names_by_mid[channel->content_name()] =
6649 channel->transport_name();
6650 }
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
Steve Anton5dfde182018-02-06 10:34:40 -08006652 if (rtp_data_channel_) {
6653 transport_names_by_mid[rtp_data_channel_->content_name()] =
6654 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006655 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006656 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006657 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006658 RTC_DCHECK(transport_name);
6659 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006660 }
Steve Anton5dfde182018-02-06 10:34:40 -08006661 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006662}
6663
Steve Anton5dfde182018-02-06 10:34:40 -08006664std::map<std::string, cricket::TransportStats>
6665PeerConnection::GetTransportStatsByNames(
6666 const std::set<std::string>& transport_names) {
6667 if (!network_thread()->IsCurrent()) {
6668 return network_thread()
6669 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6670 RTC_FROM_HERE,
6671 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006672 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006673 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006674 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6675 for (const std::string& transport_name : transport_names) {
6676 cricket::TransportStats transport_stats;
6677 bool success =
6678 transport_controller_->GetStats(transport_name, &transport_stats);
6679 if (success) {
6680 transport_stats_by_name[transport_name] = std::move(transport_stats);
6681 } else {
6682 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6683 << transport_name;
6684 }
6685 }
6686 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006687}
6688
6689bool PeerConnection::GetLocalCertificate(
6690 const std::string& transport_name,
6691 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006692 if (!certificate) {
6693 return false;
6694 }
6695 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6696 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006697}
6698
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006699std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006700 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006701 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006702}
6703
6704cricket::DataChannelType PeerConnection::data_channel_type() const {
6705 return data_channel_type_;
6706}
6707
6708bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006709 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006710 return pending_ice_restarts_.find(content_name) !=
6711 pending_ice_restarts_.end();
6712}
6713
Steve Anton75737c02017-11-06 10:37:17 -08006714bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6715 return transport_controller_->NeedsIceRestart(content_name);
6716}
6717
6718void PeerConnection::OnCertificateReady(
6719 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6720 transport_controller_->SetLocalCertificate(certificate);
6721}
6722
6723void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006724 SetSessionError(SessionError::kTransport,
6725 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006726}
6727
Alex Loiko9289eda2018-11-23 16:18:59 +00006728void PeerConnection::OnTransportControllerConnectionState(
6729 cricket::IceConnectionState state) {
6730 switch (state) {
6731 case cricket::kIceConnectionConnecting:
6732 // If the current state is Connected or Completed, then there were
6733 // writable channels but now there are not, so the next state must
6734 // be Disconnected.
6735 // kIceConnectionConnecting is currently used as the default,
6736 // un-connected state by the TransportController, so its only use is
6737 // detecting disconnections.
6738 if (ice_connection_state_ ==
6739 PeerConnectionInterface::kIceConnectionConnected ||
6740 ice_connection_state_ ==
6741 PeerConnectionInterface::kIceConnectionCompleted) {
6742 SetIceConnectionState(
6743 PeerConnectionInterface::kIceConnectionDisconnected);
6744 }
6745 break;
6746 case cricket::kIceConnectionFailed:
6747 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6748 break;
6749 case cricket::kIceConnectionConnected:
6750 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6751 "all transports are writable.";
6752 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6753 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6754 break;
6755 case cricket::kIceConnectionCompleted:
6756 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6757 "all transports are complete.";
6758 if (ice_connection_state_ !=
6759 PeerConnectionInterface::kIceConnectionConnected) {
6760 // If jumping directly from "checking" to "connected",
6761 // signal "connected" first.
6762 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6763 }
6764 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6765 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6766 ReportTransportStats();
6767 break;
6768 default:
6769 RTC_NOTREACHED();
6770 }
6771}
6772
Steve Anton75737c02017-11-06 10:37:17 -08006773void PeerConnection::OnTransportControllerCandidatesGathered(
6774 const std::string& transport_name,
6775 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006776 int sdp_mline_index;
6777 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006778 RTC_LOG(LS_ERROR)
6779 << "OnTransportControllerCandidatesGathered: content name "
6780 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006781 return;
6782 }
6783
6784 for (cricket::Candidates::const_iterator citer = candidates.begin();
6785 citer != candidates.end(); ++citer) {
6786 // Use transport_name as the candidate media id.
6787 std::unique_ptr<JsepIceCandidate> candidate(
6788 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6789 if (local_description()) {
6790 mutable_local_description()->AddCandidate(candidate.get());
6791 }
6792 OnIceCandidate(std::move(candidate));
6793 }
6794}
6795
Eldar Relloda13ea22019-06-01 12:23:43 +03006796void PeerConnection::OnTransportControllerCandidateError(
6797 const cricket::IceCandidateErrorEvent& event) {
6798 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6799 event.error_text);
6800}
6801
Steve Anton75737c02017-11-06 10:37:17 -08006802void PeerConnection::OnTransportControllerCandidatesRemoved(
6803 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006804 // Sanity check.
6805 for (const cricket::Candidate& candidate : candidates) {
6806 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006807 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006808 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006809 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006810 return;
6811 }
6812 }
6813
6814 if (local_description()) {
6815 mutable_local_description()->RemoveCandidates(candidates);
6816 }
6817 OnIceCandidatesRemoved(candidates);
6818}
6819
Alex Drake00c7ecf2019-08-06 10:54:47 -07006820void PeerConnection::OnTransportControllerCandidateChanged(
6821 const cricket::CandidatePairChangeEvent& event) {
6822 OnSelectedCandidatePairChanged(event);
6823}
6824
Steve Anton75737c02017-11-06 10:37:17 -08006825void PeerConnection::OnTransportControllerDtlsHandshakeError(
6826 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006827 RTC_HISTOGRAM_ENUMERATION(
6828 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6829 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006830}
6831
Steve Antoned10bd92017-12-05 10:52:59 -08006832void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006833 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006834 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006835 if (channel && !channel->enabled()) {
6836 channel->Enable(true);
6837 }
Steve Anton75737c02017-11-06 10:37:17 -08006838 }
6839
Steve Anton4171afb2017-11-20 10:20:22 -08006840 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006841 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006842 }
Steve Anton75737c02017-11-06 10:37:17 -08006843}
6844
6845// Returns the media index for a local ice candidate given the content name.
6846bool PeerConnection::GetLocalCandidateMediaIndex(
6847 const std::string& content_name,
6848 int* sdp_mline_index) {
6849 if (!local_description() || !sdp_mline_index) {
6850 return false;
6851 }
6852
6853 bool content_found = false;
6854 const ContentInfos& contents = local_description()->description()->contents();
6855 for (size_t index = 0; index < contents.size(); ++index) {
6856 if (contents[index].name == content_name) {
6857 *sdp_mline_index = static_cast<int>(index);
6858 content_found = true;
6859 break;
6860 }
6861 }
6862 return content_found;
6863}
6864
6865bool PeerConnection::UseCandidatesInSessionDescription(
6866 const SessionDescriptionInterface* remote_desc) {
6867 if (!remote_desc) {
6868 return true;
6869 }
6870 bool ret = true;
6871
6872 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6873 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6874 for (size_t n = 0; n < candidates->count(); ++n) {
6875 const IceCandidateInterface* candidate = candidates->at(n);
6876 bool valid = false;
6877 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6878 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006879 RTC_LOG(LS_INFO)
6880 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006881 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006882 }
6883 continue;
6884 }
6885 ret = UseCandidate(candidate);
6886 if (!ret) {
6887 break;
6888 }
6889 }
6890 }
6891 return ret;
6892}
6893
6894bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006895 RTCErrorOr<const cricket::ContentInfo*> result =
6896 FindContentInfo(remote_description(), candidate);
6897 if (!result.ok()) {
6898 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6899 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006900 return false;
6901 }
Steve Anton75737c02017-11-06 10:37:17 -08006902 std::vector<cricket::Candidate> candidates;
6903 candidates.push_back(candidate->candidate());
6904 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006905 RTCError error = transport_controller_->AddRemoteCandidates(
6906 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006907 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006908 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006909 // Candidates successfully submitted for checking.
6910 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6911 ice_connection_state_ ==
6912 PeerConnectionInterface::kIceConnectionDisconnected) {
6913 // If state is New, then the session has just gotten its first remote ICE
6914 // candidates, so go to Checking.
6915 // If state is Disconnected, the session is re-using old candidates or
6916 // receiving additional ones, so go to Checking.
6917 // If state is Connected, stay Connected.
6918 // TODO(bemasc): If state is Connected, and the new candidates are for a
6919 // newly added transport, then the state actually _should_ move to
6920 // checking. Add a way to distinguish that case.
6921 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6922 }
6923 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006924 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006925 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006926 }
6927 return true;
6928}
6929
Guido Urdaneta41633172019-05-23 20:12:29 +02006930RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6931 const SessionDescriptionInterface* description,
6932 const IceCandidateInterface* candidate) {
6933 if (candidate->sdp_mline_index() >= 0) {
6934 size_t mediacontent_index =
6935 static_cast<size_t>(candidate->sdp_mline_index());
6936 size_t content_size = description->description()->contents().size();
6937 if (mediacontent_index < content_size) {
6938 return &description->description()->contents()[mediacontent_index];
6939 } else {
6940 return RTCError(RTCErrorType::INVALID_RANGE,
6941 "Media line index (" +
6942 rtc::ToString(candidate->sdp_mline_index()) +
6943 ") out of range (number of mlines: " +
6944 rtc::ToString(content_size) + ").");
6945 }
6946 } else if (!candidate->sdp_mid().empty()) {
6947 auto& contents = description->description()->contents();
6948 auto it = absl::c_find_if(
6949 contents, [candidate](const cricket::ContentInfo& content_info) {
6950 return content_info.mid() == candidate->sdp_mid();
6951 });
6952 if (it == contents.end()) {
6953 return RTCError(
6954 RTCErrorType::INVALID_PARAMETER,
6955 "Mid " + candidate->sdp_mid() +
6956 " specified but no media section with that mid found.");
6957 } else {
6958 return &*it;
6959 }
6960 }
6961
6962 return RTCError(RTCErrorType::INVALID_PARAMETER,
6963 "Neither sdp_mline_index nor sdp_mid specified.");
6964}
6965
Steve Anton75737c02017-11-06 10:37:17 -08006966void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006967 // Destroy video channel first since it may have a pointer to the
6968 // voice channel.
6969 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006970 if (!video_info || video_info->rejected) {
6971 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006972 }
6973
Steve Anton6fec8802017-12-04 10:37:29 -08006974 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6975 if (!audio_info || audio_info->rejected) {
6976 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006977 }
6978
6979 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6980 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006981 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006982 }
6983}
6984
Steve Antondcc3c022017-12-22 16:02:54 -08006985RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6986 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006987 const cricket::ContentGroup* bundle_group = nullptr;
6988 if (configuration_.bundle_policy ==
6989 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006990 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006991 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006992 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6993 "max-bundle configured but session description "
6994 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006995 }
6996 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006997 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006998}
6999
7000RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07007001 // Creating the media channels. Transports should already have been created
7002 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08007003 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007004 if (voice && !voice->rejected &&
7005 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07007006 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007007 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08007008 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7009 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08007010 }
7011 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
7012 }
7013
Steve Antondcc3c022017-12-22 16:02:54 -08007014 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007015 if (video && !video->rejected &&
7016 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07007017 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007018 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08007019 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7020 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08007021 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08007022 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08007023 }
7024
Steve Antondcc3c022017-12-22 16:02:54 -08007025 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08007026 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007027 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007028 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08007029 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7030 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08007031 }
7032 }
7033
Steve Anton8a006912017-12-04 15:25:56 -08007034 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007035}
7036
Steve Anton4171afb2017-11-20 10:20:22 -08007037// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08007038cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07007039 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007040 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007041 MediaTransportConfig media_transport_config =
7042 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007043
Steve Anton75737c02017-11-06 10:37:17 -08007044 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007045 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007046 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7047 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08007048 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08007049 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08007050 }
Steve Anton75737c02017-11-06 10:37:17 -08007051 voice_channel->SignalDtlsSrtpSetupFailure.connect(
7052 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08007053 voice_channel->SignalSentPacket.connect(this,
7054 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07007055 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08007056
Steve Antoneda6ccd2017-12-04 10:21:55 -08007057 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08007058}
7059
Steve Anton4171afb2017-11-20 10:20:22 -08007060// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08007061cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07007062 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007063 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007064 MediaTransportConfig media_transport_config =
7065 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007066
Steve Anton75737c02017-11-06 10:37:17 -08007067 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007068 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007069 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7070 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007071 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08007072 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08007073 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08007074 }
Steve Anton75737c02017-11-06 10:37:17 -08007075 video_channel->SignalDtlsSrtpSetupFailure.connect(
7076 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08007077 video_channel->SignalSentPacket.connect(this,
7078 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07007079 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08007080
Steve Antoneda6ccd2017-12-04 10:21:55 -08007081 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08007082}
7083
Zhi Huange830e682018-03-30 10:48:35 -07007084bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007085 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007086 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00007087 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00007088 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
7089 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007090 if (!network_thread()->Invoke<bool>(
7091 RTC_FROM_HERE,
7092 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
7093 mid))) {
Qingsi Wang437077d2019-09-10 17:52:26 +00007094 return false;
7095 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007096
7097 // All non-RTP data channels must initialize |sctp_data_channels_|.
7098 for (const auto& channel : sctp_data_channels_) {
7099 channel->OnTransportChannelCreated();
7100 }
7101 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007102 case cricket::DCT_RTP:
7103 default:
7104 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
7105 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
7106 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08007107 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007108 if (!rtp_data_channel_) {
7109 return false;
7110 }
7111 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
7112 this, &PeerConnection::OnDtlsSrtpSetupFailure);
7113 rtp_data_channel_->SignalSentPacket.connect(
7114 this, &PeerConnection::OnSentPacket_w);
7115 rtp_data_channel_->SetRtpTransport(rtp_transport);
7116 return true;
Steve Anton75737c02017-11-06 10:37:17 -08007117 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007118 return false;
Steve Anton75737c02017-11-06 10:37:17 -08007119}
7120
7121Call::Stats PeerConnection::GetCallStats() {
7122 if (!worker_thread()->IsCurrent()) {
7123 return worker_thread()->Invoke<Call::Stats>(
7124 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
7125 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007126 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007127 if (call_) {
7128 return call_->GetStats();
7129 } else {
7130 return Call::Stats();
7131 }
7132}
7133
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007134bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007135 DataChannelTransportInterface* transport =
7136 transport_controller_->GetDataChannelTransport(mid);
7137 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08007138 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007139 << "Data channel transport is not available for data channels, mid="
7140 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007141 return false;
7142 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007143 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007144
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007145 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02007146 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007147 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007148
7149 // Note: setting the data sink and checking initial state must be done last,
7150 // after setting up the data channel. Setting the data sink may trigger
7151 // callbacks to PeerConnection which require the transport to be completely
7152 // set up (eg. OnReadyToSend()).
7153 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007154 return true;
7155}
7156
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007157void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007158 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007159 return;
7160 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007161 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
7162 << *sctp_mid_;
7163
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007164 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
7165 // it.
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007166 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +00007167 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007168 if (data_channel_transport_) {
7169 data_channel_transport_->SetDataSink(nullptr);
7170 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007171 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007172}
7173
Steve Anton75737c02017-11-06 10:37:17 -08007174// Returns false if bundle is enabled and rtcp_mux is disabled.
7175bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
7176 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
7177 if (!bundle_enabled)
7178 return true;
7179
7180 const cricket::ContentGroup* bundle_group =
7181 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
7182 RTC_DCHECK(bundle_group != NULL);
7183
7184 const cricket::ContentInfos& contents = desc->contents();
7185 for (cricket::ContentInfos::const_iterator citer = contents.begin();
7186 citer != contents.end(); ++citer) {
7187 const cricket::ContentInfo* content = (&*citer);
7188 RTC_DCHECK(content != NULL);
7189 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08007190 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08007191 if (!HasRtcpMuxEnabled(content))
7192 return false;
7193 }
7194 }
7195 // RTCP-MUX is enabled in all the contents.
7196 return true;
7197}
7198
7199bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08007200 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08007201}
7202
Steve Anton06817cd2018-12-18 15:55:30 -08007203static RTCError ValidateMids(const cricket::SessionDescription& description) {
7204 std::set<std::string> mids;
7205 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08007206 if (content.name.empty()) {
7207 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7208 "A media section is missing a MID attribute.");
7209 }
Steve Anton06817cd2018-12-18 15:55:30 -08007210 if (!mids.insert(content.name).second) {
7211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7212 "Duplicate a=mid value '" + content.name + "'.");
7213 }
7214 }
7215 return RTCError::OK();
7216}
7217
Steve Anton8a006912017-12-04 15:25:56 -08007218RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08007219 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08007220 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08007221 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08007222 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08007223 }
7224
7225 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08007226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08007227 }
7228
Steve Anton3828c062017-12-06 10:34:51 -08007229 SdpType type = sdesc->GetType();
7230 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
7231 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08007232 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01007233 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08007234 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08007235 }
7236
Steve Anton06817cd2018-12-18 15:55:30 -08007237 RTCError error = ValidateMids(*sdesc->description());
7238 if (!error.ok()) {
7239 return error;
7240 }
7241
Steve Anton75737c02017-11-06 10:37:17 -08007242 // Verify crypto settings.
7243 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08007244 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
7245 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007246 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08007247 if (!crypto_error.ok()) {
7248 return crypto_error;
7249 }
Steve Anton75737c02017-11-06 10:37:17 -08007250 }
7251
7252 // Verify ice-ufrag and ice-pwd.
7253 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7255 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08007256 }
7257
7258 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7260 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08007261 }
7262
7263 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
7264 // m-lines that do not rtcp-mux enabled.
7265
7266 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08007267 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007268 // With an answer we want to compare the new answer session description with
7269 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08007270 const cricket::SessionDescription* offer_desc =
7271 (source == cricket::CS_LOCAL) ? remote_description()->description()
7272 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007273 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
7274 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
7275 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7277 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007278 }
7279 } else {
Steve Anton75737c02017-11-06 10:37:17 -08007280 // The re-offers should respect the order of m= sections in current
7281 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007282 // With a re-offer, either the current local or current remote descriptions
7283 // could be the most up to date, so we would like to check against both of
7284 // them if they exist. It could be the case that one of them has a 0 port
7285 // for a media section, but the other does not. This is important to check
7286 // against in the case that we are recycling an m= section.
7287 const cricket::SessionDescription* current_desc = nullptr;
7288 const cricket::SessionDescription* secondary_current_desc = nullptr;
7289 if (local_description()) {
7290 current_desc = local_description()->description();
7291 if (remote_description()) {
7292 secondary_current_desc = remote_description()->description();
7293 }
7294 } else if (remote_description()) {
7295 current_desc = remote_description()->description();
7296 }
Steve Anton75737c02017-11-06 10:37:17 -08007297 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007298 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
7299 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007300 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7301 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08007302 }
7303 }
7304
Steve Antonba42e992018-04-09 14:10:01 -07007305 if (IsUnifiedPlan()) {
7306 // Ensure that each audio and video media section has at most one
7307 // "StreamParams". This will return an error if receiving a session
7308 // description from a "Plan B" endpoint which adds multiple tracks of the
7309 // same type. With Unified Plan, there can only be at most one track per
7310 // media section.
7311 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02007312 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07007313 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
7314 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
7315 desc.streams().size() > 1u) {
7316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7317 "Media section has more than one track specified "
7318 "with a=ssrc lines which is not supported with "
7319 "Unified Plan.");
7320 }
7321 }
7322 }
7323
Steve Anton8a006912017-12-04 15:25:56 -08007324 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007325}
7326
Steve Anton3828c062017-12-06 10:34:51 -08007327bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007328 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007329 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007330 return (state == PeerConnectionInterface::kStable) ||
7331 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08007332 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007333 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007334 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7335 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7336 }
7337}
7338
Steve Anton3828c062017-12-06 10:34:51 -08007339bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007340 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007341 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007342 return (state == PeerConnectionInterface::kStable) ||
7343 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08007344 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007345 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007346 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7347 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7348 }
7349}
7350
Steve Antonf8470812017-12-04 10:46:21 -08007351const char* PeerConnection::SessionErrorToString(SessionError error) const {
7352 switch (error) {
7353 case SessionError::kNone:
7354 return "ERROR_NONE";
7355 case SessionError::kContent:
7356 return "ERROR_CONTENT";
7357 case SessionError::kTransport:
7358 return "ERROR_TRANSPORT";
7359 }
7360 RTC_NOTREACHED();
7361 return "";
7362}
7363
Steve Anton75737c02017-11-06 10:37:17 -08007364std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02007365 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08007366 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7367 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02007368 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08007369}
7370
Steve Anton8e20f172018-03-06 10:55:04 -08007371void PeerConnection::ReportSdpFormatReceived(
7372 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08007373 int num_audio_mlines = 0;
7374 int num_video_mlines = 0;
7375 int num_audio_tracks = 0;
7376 int num_video_tracks = 0;
7377 for (const ContentInfo& content : remote_offer.description()->contents()) {
7378 cricket::MediaType media_type = content.media_description()->type();
7379 int num_tracks = std::max(
7380 1, static_cast<int>(content.media_description()->streams().size()));
7381 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7382 num_audio_mlines += 1;
7383 num_audio_tracks += num_tracks;
7384 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7385 num_video_mlines += 1;
7386 num_video_tracks += num_tracks;
7387 }
7388 }
7389 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7390 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7391 format = kSdpFormatReceivedComplexUnifiedPlan;
7392 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7393 format = kSdpFormatReceivedComplexPlanB;
7394 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7395 format = kSdpFormatReceivedSimple;
7396 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007397 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7398 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007399}
7400
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007401void PeerConnection::ReportIceCandidateCollected(
7402 const cricket::Candidate& candidate) {
7403 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7404 if (candidate.address().IsPrivateIP()) {
7405 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7406 }
7407 if (candidate.address().IsUnresolvedIP()) {
7408 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7409 }
7410 if (candidate.address().family() == AF_INET6) {
7411 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7412 }
7413}
7414
7415void PeerConnection::ReportRemoteIceCandidateAdded(
7416 const cricket::Candidate& candidate) {
7417 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7418 if (candidate.address().IsPrivateIP()) {
7419 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7420 }
7421 if (candidate.address().IsUnresolvedIP()) {
7422 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7423 }
7424 if (candidate.address().family() == AF_INET6) {
7425 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7426 }
7427}
7428
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007429void PeerConnection::NoteUsageEvent(UsageEvent event) {
7430 RTC_DCHECK_RUN_ON(signaling_thread());
7431 usage_event_accumulator_ |= static_cast<int>(event);
7432}
7433
7434void PeerConnection::ReportUsagePattern() const {
7435 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007436 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7437 usage_event_accumulator_,
7438 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007439 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007440 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007441 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7442 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007443 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007444 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7445 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7446 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7447 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007448 // If called after close(), we can't report, because observer may have
7449 // been deallocated, and therefore pointer is null. Write to log instead.
7450 if (observer_) {
7451 Observer()->OnInterestingUsage(usage_event_accumulator_);
7452 } else {
7453 RTC_LOG(LS_INFO) << "Interesting usage signature "
7454 << usage_event_accumulator_
7455 << " observed after observer shutdown";
7456 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007457 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007458}
7459
Steve Anton0ffaaa22018-02-23 10:31:30 -08007460void PeerConnection::ReportNegotiatedSdpSemantics(
7461 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007462 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007463 switch (answer.description()->msid_signaling()) {
7464 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007465 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007466 break;
7467 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007468 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007469 break;
7470 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007471 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007472 break;
7473 case cricket::kMsidSignalingMediaSection |
7474 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007475 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007476 break;
7477 default:
7478 RTC_NOTREACHED();
7479 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007480 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7481 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007482}
7483
Steve Anton75737c02017-11-06 10:37:17 -08007484// We need to check the local/remote description for the Transport instead of
7485// the session, because a new Transport added during renegotiation may have
7486// them unset while the session has them set from the previous negotiation.
7487// Not doing so may trigger the auto generation of transport description and
7488// mess up DTLS identity information, ICE credential, etc.
7489bool PeerConnection::ReadyToUseRemoteCandidate(
7490 const IceCandidateInterface* candidate,
7491 const SessionDescriptionInterface* remote_desc,
7492 bool* valid) {
7493 *valid = true;
7494
7495 const SessionDescriptionInterface* current_remote_desc =
7496 remote_desc ? remote_desc : remote_description();
7497
7498 if (!current_remote_desc) {
7499 return false;
7500 }
7501
Guido Urdaneta41633172019-05-23 20:12:29 +02007502 RTCErrorOr<const cricket::ContentInfo*> result =
7503 FindContentInfo(current_remote_desc, candidate);
7504 if (!result.ok()) {
7505 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7506 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007507
7508 *valid = false;
7509 return false;
7510 }
7511
Guido Urdaneta41633172019-05-23 20:12:29 +02007512 std::string transport_name = GetTransportName(result.value()->name);
7513 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007514}
7515
7516bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007517 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007518 (dtls_enabled_ ||
7519 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007520}
7521
7522void PeerConnection::OnTransportControllerGatheringState(
7523 cricket::IceGatheringState state) {
7524 RTC_DCHECK(signaling_thread()->IsCurrent());
7525 if (state == cricket::kIceGatheringGathering) {
7526 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7527 } else if (state == cricket::kIceGatheringComplete) {
7528 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7529 }
7530}
7531
7532void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007533 std::map<std::string, std::set<cricket::MediaType>>
7534 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007535 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007536 if (transceiver->internal()->channel()) {
7537 const std::string& transport_name =
7538 transceiver->internal()->channel()->transport_name();
7539 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007540 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007541 }
Steve Anton75737c02017-11-06 10:37:17 -08007542 }
7543 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007544 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7545 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007546 }
Zhi Huange830e682018-03-30 10:48:35 -07007547
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007548 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007549 if (transport_name) {
7550 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007551 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007552 }
Zhi Huange830e682018-03-30 10:48:35 -07007553
Steve Antonc7b964c2018-02-01 14:39:45 -08007554 for (const auto& entry : media_types_by_transport_name) {
7555 const std::string& transport_name = entry.first;
7556 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007557 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007558 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007559 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007560 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007561 }
7562 }
7563}
7564// Walk through the ConnectionInfos to gather best connection usage
7565// for IPv4 and IPv6.
7566void PeerConnection::ReportBestConnectionState(
7567 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007568 for (const cricket::TransportChannelStats& channel_stats :
7569 stats.channel_stats) {
7570 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007571 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007572 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007573 continue;
7574 }
7575
Steve Antonc7b964c2018-02-01 14:39:45 -08007576 const cricket::Candidate& local = connection_info.local_candidate;
7577 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007578
7579 // Increment the counter for IceCandidatePairType.
7580 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7581 (local.type() == RELAY_PORT_TYPE &&
7582 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007583 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7584 GetIceCandidatePairCounter(local, remote),
7585 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007586 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007587 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7588 GetIceCandidatePairCounter(local, remote),
7589 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007590 } else {
7591 RTC_CHECK(0);
7592 }
Steve Anton75737c02017-11-06 10:37:17 -08007593
7594 // Increment the counter for IP type.
7595 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007596 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7597 kBestConnections_IPv4,
7598 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007599 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007600 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7601 kBestConnections_IPv6,
7602 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007603 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007604 RTC_CHECK(!local.address().hostname().empty() &&
7605 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007606 }
7607
7608 return;
7609 }
7610 }
7611}
7612
7613void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007614 const cricket::TransportStats& stats,
7615 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007616 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7617 return;
7618 }
7619
7620 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7621 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7622 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7623 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7624 return;
7625 }
7626
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007627 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7628 for (cricket::MediaType media_type : media_types) {
7629 switch (media_type) {
7630 case cricket::MEDIA_TYPE_AUDIO:
7631 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7632 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7633 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7634 break;
7635 case cricket::MEDIA_TYPE_VIDEO:
7636 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7637 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7638 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7639 break;
7640 case cricket::MEDIA_TYPE_DATA:
7641 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7642 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7643 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7644 break;
7645 default:
7646 RTC_NOTREACHED();
7647 continue;
7648 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007649 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007650 }
7651
7652 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7653 for (cricket::MediaType media_type : media_types) {
7654 switch (media_type) {
7655 case cricket::MEDIA_TYPE_AUDIO:
7656 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7657 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7658 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7659 break;
7660 case cricket::MEDIA_TYPE_VIDEO:
7661 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7662 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7663 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7664 break;
7665 case cricket::MEDIA_TYPE_DATA:
7666 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7667 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7668 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7669 break;
7670 default:
7671 RTC_NOTREACHED();
7672 continue;
7673 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007674 }
Steve Anton75737c02017-11-06 10:37:17 -08007675 }
7676}
7677
7678void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007679 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007680 RTC_DCHECK(call_);
7681 call_->OnSentPacket(sent_packet);
7682}
7683
7684const std::string PeerConnection::GetTransportName(
7685 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007686 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007687 if (channel) {
7688 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007689 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007690 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007691 RTC_DCHECK(sctp_mid_);
7692 if (content_name == *sctp_mid_) {
7693 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007694 }
7695 }
7696 // Return an empty string if failed to retrieve the transport name.
7697 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007698}
7699
Steve Anton6fec8802017-12-04 10:37:29 -08007700void PeerConnection::DestroyTransceiverChannel(
7701 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7702 transceiver) {
7703 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007704
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007705 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007706 if (channel) {
7707 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007708 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007709 }
7710}
7711
7712void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007713 if (rtp_data_channel_) {
7714 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007715 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007716 rtp_data_channel_ = nullptr;
7717 }
7718
7719 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7720 // grab a reference to this PeerConnection. If this is called from the
7721 // PeerConnection destructor, the RefCountedObject vtable will have already
7722 // been destroyed (since it is a subclass of PeerConnection) and using
7723 // rtc::Bind will cause "Pure virtual function called" error to appear.
7724
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007725 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007726 OnDataChannelDestroyed();
7727 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7728 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007729 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007730 });
7731 }
Steve Anton6fec8802017-12-04 10:37:29 -08007732}
7733
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007734void PeerConnection::DestroyChannelInterface(
7735 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007736 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007737 switch (channel->media_type()) {
7738 case cricket::MEDIA_TYPE_AUDIO:
7739 channel_manager()->DestroyVoiceChannel(
7740 static_cast<cricket::VoiceChannel*>(channel));
7741 break;
7742 case cricket::MEDIA_TYPE_VIDEO:
7743 channel_manager()->DestroyVideoChannel(
7744 static_cast<cricket::VideoChannel*>(channel));
7745 break;
7746 case cricket::MEDIA_TYPE_DATA:
7747 channel_manager()->DestroyRtpDataChannel(
7748 static_cast<cricket::RtpDataChannel*>(channel));
7749 break;
7750 default:
7751 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7752 break;
7753 }
Zhi Huange830e682018-03-30 10:48:35 -07007754}
Steve Anton6fec8802017-12-04 10:37:29 -08007755
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007756bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007757 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007758 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007759 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007760 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007761 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007762 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007763 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007764 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007765 auto base_channel = GetChannel(mid);
7766 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007767 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007768 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007769
Karl Wiberg5966c502019-02-21 23:55:09 +01007770 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007771 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007772 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007773
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007774 if (data_channel_transport_ && mid == sctp_mid_ &&
7775 data_channel_transport_ != data_channel_transport) {
7776 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7777 // it's bundled).
7778 data_channel_transport_->SetDataSink(nullptr);
7779 data_channel_transport_ = data_channel_transport;
7780 if (data_channel_transport) {
7781 data_channel_transport->SetDataSink(this);
7782
7783 // There's a new data channel transport. This needs to be signaled to the
7784 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7785 // necessary when bundling is applied.
7786 data_channel_transport_invoker_->AsyncInvoke<void>(
7787 RTC_FROM_HERE, signaling_thread(), [this] {
7788 RTC_DCHECK_RUN_ON(signaling_thread());
7789 for (auto channel : sctp_data_channels_) {
7790 channel->OnTransportChannelCreated();
7791 }
7792 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007793 }
7794 }
7795
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007796 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007797}
7798
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007799void PeerConnection::OnSetStreams() {
7800 RTC_DCHECK_RUN_ON(signaling_thread());
7801 if (IsUnifiedPlan())
7802 UpdateNegotiationNeeded();
7803}
7804
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007805PeerConnectionObserver* PeerConnection::Observer() const {
7806 // In earlier production code, the pointer was not cleared on close,
7807 // which might have led to undefined behavior if the observer was not
7808 // deallocated, or strange crashes if it was.
7809 // We use CHECK in order to catch such behavior if it exists.
7810 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7811 RTC_CHECK(observer_);
7812 return observer_;
7813}
7814
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007815CryptoOptions PeerConnection::GetCryptoOptions() {
7816 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7817 // after it has been removed.
7818 return configuration_.crypto_options.has_value()
7819 ? *configuration_.crypto_options
7820 : factory_->options().crypto_options;
7821}
7822
Harald Alvestrand89061872018-01-02 14:08:34 +01007823void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007824 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007825 if (stats_collector_) {
7826 stats_collector_->ClearCachedStatsReport();
7827 }
7828}
7829
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007830void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007831 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7832 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007833}
7834
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007835void PeerConnection::UpdateNegotiationNeeded() {
7836 RTC_DCHECK_RUN_ON(signaling_thread());
7837 if (!IsUnifiedPlan()) {
7838 Observer()->OnRenegotiationNeeded();
7839 return;
7840 }
7841
7842 // If connection's [[IsClosed]] slot is true, abort these steps.
7843 if (IsClosed())
7844 return;
7845
7846 // If connection's signaling state is not "stable", abort these steps.
7847 if (signaling_state() != kStable)
7848 return;
7849
7850 // NOTE
7851 // The negotiation-needed flag will be updated once the state transitions to
7852 // "stable", as part of the steps for setting an RTCSessionDescription.
7853
7854 // If the result of checking if negotiation is needed is false, clear the
7855 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7856 // to false, and abort these steps.
7857 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7858 if (!is_negotiation_needed) {
7859 is_negotiation_needed_ = false;
7860 return;
7861 }
7862
7863 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7864 // steps.
7865 if (is_negotiation_needed_)
7866 return;
7867
7868 // Set connection's [[NegotiationNeeded]] slot to true.
7869 is_negotiation_needed_ = true;
7870
7871 // Queue a task that runs the following steps:
7872 // If connection's [[IsClosed]] slot is true, abort these steps.
7873 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7874 // Fire an event named negotiationneeded at connection.
7875 Observer()->OnRenegotiationNeeded();
7876}
7877
7878bool PeerConnection::CheckIfNegotiationIsNeeded() {
7879 RTC_DCHECK_RUN_ON(signaling_thread());
7880 // 1. If any implementation-specific negotiation is required, as described at
7881 // the start of this section, return true.
7882
Henrik Boström79b69802019-07-18 11:16:56 +02007883 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7884 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7885 return true;
7886 }
7887
7888 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007889 const SessionDescriptionInterface* description = current_local_description();
7890 if (!description)
7891 return true;
7892
Henrik Boström79b69802019-07-18 11:16:56 +02007893 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007894 // description has been negotiated yet for data, return true.
7895 if (!sctp_data_channels_.empty()) {
7896 if (!cricket::GetFirstDataContent(description->description()->contents()))
7897 return true;
7898 }
7899
Henrik Boström79b69802019-07-18 11:16:56 +02007900 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007901 // following checks:
7902 for (const auto& transceiver : transceivers_) {
7903 const ContentInfo* current_local_msection =
7904 FindTransceiverMSection(transceiver.get(), description);
7905
7906 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7907 transceiver.get(), current_remote_description());
7908
Henrik Boström79b69802019-07-18 11:16:56 +02007909 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007910 // but the associated m= section is not yet rejected in
7911 // connection.[[CurrentLocalDescription]] or
7912 // connection.[[CurrentRemoteDescription]], return true.
7913 if (transceiver->stopped()) {
7914 if (current_local_msection && !current_local_msection->rejected &&
7915 ((current_remote_msection && !current_remote_msection->rejected) ||
7916 !current_remote_msection)) {
7917 return true;
7918 }
7919 continue;
7920 }
7921
Henrik Boström79b69802019-07-18 11:16:56 +02007922 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007923 // section in description, return true.
7924 if (!current_local_msection)
7925 return true;
7926
7927 const MediaContentDescription* current_local_media_description =
7928 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007929 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007930 // in description then perform the following checks:
7931
Henrik Boström79b69802019-07-18 11:16:56 +02007932 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007933 // associated m= section in description either doesn't contain a single
7934 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7935 // m= section, or the MSID values themselves, differ from what is in
7936 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7937 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7938 if (current_local_media_description->streams().size() == 0)
7939 return true;
7940
7941 std::vector<std::string> msection_msids;
7942 for (const auto& stream : current_local_media_description->streams()) {
7943 for (const std::string& msid : stream.stream_ids())
7944 msection_msids.push_back(msid);
7945 }
7946
7947 std::vector<std::string> transceiver_msids =
7948 transceiver->sender()->stream_ids();
7949 if (msection_msids.size() != transceiver_msids.size())
7950 return true;
7951
7952 absl::c_sort(transceiver_msids);
7953 absl::c_sort(msection_msids);
7954 if (transceiver_msids != msection_msids)
7955 return true;
7956 }
7957
Henrik Boström79b69802019-07-18 11:16:56 +02007958 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007959 // associated m= section in neither connection.[[CurrentLocalDescription]]
7960 // nor connection.[[CurrentRemoteDescription]] matches
7961 // transceiver.[[Direction]], return true.
7962 if (description->GetType() == SdpType::kOffer) {
7963 if (!current_remote_description())
7964 return true;
7965
7966 if (!current_remote_msection)
7967 return true;
7968
7969 RtpTransceiverDirection current_local_direction =
7970 current_local_media_description->direction();
7971 RtpTransceiverDirection current_remote_direction =
7972 current_remote_msection->media_description()->direction();
7973 if (transceiver->direction() != current_local_direction &&
7974 transceiver->direction() !=
7975 RtpTransceiverDirectionReversed(current_remote_direction)) {
7976 return true;
7977 }
7978 }
7979
Henrik Boström79b69802019-07-18 11:16:56 +02007980 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007981 // associated m= section in the description does not match
7982 // transceiver.[[Direction]] intersected with the offered direction (as
7983 // described in [JSEP] (section 5.3.1.)), return true.
7984 if (description->GetType() == SdpType::kAnswer) {
7985 if (!remote_description())
7986 return true;
7987
7988 const ContentInfo* offered_remote_msection =
7989 FindTransceiverMSection(transceiver.get(), remote_description());
7990
7991 RtpTransceiverDirection offered_direction =
7992 offered_remote_msection
7993 ? offered_remote_msection->media_description()->direction()
7994 : RtpTransceiverDirection::kInactive;
7995
7996 if (current_local_media_description->direction() !=
7997 (RtpTransceiverDirectionIntersection(
7998 transceiver->direction(),
7999 RtpTransceiverDirectionReversed(offered_direction)))) {
8000 return true;
8001 }
8002 }
8003 }
8004
8005 // If all the preceding checks were performed and true was not returned,
8006 // nothing remains to be negotiated; return false.
8007 return false;
8008}
8009
Eldar Relloead0ec92019-10-21 23:01:31 +03008010RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03008011 auto state = signaling_state();
8012 if (state != PeerConnectionInterface::kHaveLocalOffer &&
8013 state != PeerConnectionInterface::kHaveRemoteOffer) {
8014 return RTCError(RTCErrorType::INVALID_STATE,
8015 "Called in wrong signalingState: " +
8016 GetSignalingStateString(signaling_state()));
8017 }
8018 RTC_DCHECK_RUN_ON(signaling_thread());
8019 RTC_DCHECK(IsUnifiedPlan());
8020
8021 for (auto&& transceivers_stable_state_pair :
8022 transceiver_stable_states_by_transceivers_) {
8023 auto transceiver = transceivers_stable_state_pair.first;
8024 auto state = transceivers_stable_state_pair.second;
8025 RTC_DCHECK(transceiver->internal()->mid().has_value());
8026 std::string mid = transceiver->internal()->mid().value();
8027 transport_controller_->RollbackTransportForMid(mid);
8028 DestroyTransceiverChannel(transceiver);
8029
Eldar Relloead0ec92019-10-21 23:01:31 +03008030 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
8031 transceiver->receiver()) {
8032 Observer()->OnRemoveTrack(transceiver->receiver());
8033 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03008034 if (state.newly_created()) {
8035 // Remove added transceivers with no added track.
8036 if (transceiver->internal()->sender()->track()) {
8037 transceiver->internal()->set_created_by_addtrack(true);
8038 } else {
8039 int remaining_transceiver_count = 0;
8040 for (auto&& t : transceivers_) {
8041 if (t != transceiver) {
8042 transceivers_[remaining_transceiver_count++] = t;
8043 }
8044 }
8045 transceivers_.resize(remaining_transceiver_count);
8046 }
8047 }
8048 transceiver->internal()->sender_internal()->set_transport(nullptr);
8049 transceiver->internal()->receiver_internal()->set_transport(nullptr);
8050 transceiver->internal()->set_direction(state.direction());
8051 transceiver->internal()->set_mid(state.mid());
8052 transceiver->internal()->set_mline_index(state.mline_index());
8053 }
8054 transceiver_stable_states_by_transceivers_.clear();
8055 pending_local_description_.reset();
8056 pending_remote_description_.reset();
8057 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 23:01:31 +03008058
8059 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
8060 // gets called in SetRemoteDescription.
8061 if (sdp_type == SdpType::kRollback) {
8062 UpdateNegotiationNeeded();
8063 if (is_negotiation_needed_) {
8064 Observer()->OnRenegotiationNeeded();
8065 }
8066 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03008067 return RTCError::OK();
8068}
8069
henrike@webrtc.org28e20752013-07-10 00:45:36 +00008070} // namespace webrtc