blob: 65f1283e4942167c4f5da04188ba617aee0f828d [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
Qingsi Wang437077d2019-09-10 17:52:26 +0000613cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
614 switch (type) {
615 case DataMessageType::kText:
616 return cricket::DMT_TEXT;
617 case DataMessageType::kBinary:
618 return cricket::DMT_BINARY;
619 case DataMessageType::kControl:
620 return cricket::DMT_CONTROL;
621 default:
622 return cricket::DMT_NONE;
623 }
624 return cricket::DMT_NONE;
625}
626
627DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
628 switch (type) {
629 case cricket::DMT_TEXT:
630 return DataMessageType::kText;
631 case cricket::DMT_BINARY:
632 return DataMessageType::kBinary;
633 case cricket::DMT_CONTROL:
634 return DataMessageType::kControl;
635 case cricket::DMT_NONE:
636 default:
637 RTC_NOTREACHED();
638 }
639 return DataMessageType::kControl;
640}
641
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800642void ReportSimulcastApiVersion(const char* name,
643 const SessionDescription& session) {
644 bool has_legacy = false;
645 bool has_spec_compliant = false;
646 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200647 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800648 continue;
649 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200650 has_spec_compliant |= content.media_description()->HasSimulcast();
651 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800652 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
653 }
654 }
655
656 if (has_legacy) {
657 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
658 kSimulcastApiVersionMax);
659 }
660 if (has_spec_compliant) {
661 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
662 kSimulcastApiVersionMax);
663 }
664 if (!has_legacy && !has_spec_compliant) {
665 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
666 kSimulcastApiVersionMax);
667 }
668}
669
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200670const ContentInfo* FindTransceiverMSection(
671 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
672 const SessionDescriptionInterface* session_description) {
673 return transceiver->mid()
674 ? session_description->description()->GetContentByName(
675 *transceiver->mid())
676 : nullptr;
677}
678
Steve Anton75737c02017-11-06 10:37:17 -0800679} // namespace
680
Henrik Boström79b69802019-07-18 11:16:56 +0200681class PeerConnection::LocalIceCredentialsToReplace {
682 public:
683 // Sets the ICE credentials that need restarting to the ICE credentials of
684 // the current and pending descriptions.
685 void SetIceCredentialsFromLocalDescriptions(
686 const SessionDescriptionInterface* current_local_description,
687 const SessionDescriptionInterface* pending_local_description) {
688 ice_credentials_.clear();
689 if (current_local_description) {
690 AppendIceCredentialsFromSessionDescription(*current_local_description);
691 }
692 if (pending_local_description) {
693 AppendIceCredentialsFromSessionDescription(*pending_local_description);
694 }
695 }
696
697 void ClearIceCredentials() { ice_credentials_.clear(); }
698
699 // Returns true if we have ICE credentials that need restarting.
700 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
701
702 // Returns true if |local_description| shares no ICE credentials with the
703 // ICE credentials that need restarting.
704 bool SatisfiesIceRestart(
705 const SessionDescriptionInterface& local_description) const {
706 for (const auto& transport_info :
707 local_description.description()->transport_infos()) {
708 if (ice_credentials_.find(std::make_pair(
709 transport_info.description.ice_ufrag,
710 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
711 return false;
712 }
713 }
714 return true;
715 }
716
717 private:
718 void AppendIceCredentialsFromSessionDescription(
719 const SessionDescriptionInterface& desc) {
720 for (const auto& transport_info : desc.description()->transport_infos()) {
721 ice_credentials_.insert(
722 std::make_pair(transport_info.description.ice_ufrag,
723 transport_info.description.ice_pwd));
724 }
725 }
726
727 std::set<std::pair<std::string, std::string>> ice_credentials_;
728};
729
Henrik Boström31638672017-11-23 17:48:32 +0100730// Upon completion, posts a task to execute the callback of the
731// SetSessionDescriptionObserver asynchronously on the same thread. At this
732// point, the state of the peer connection might no longer reflect the effects
733// of the SetRemoteDescription operation, as the peer connection could have been
734// modified during the post.
735// TODO(hbos): Remove this class once we remove the version of
736// PeerConnectionInterface::SetRemoteDescription() that takes a
737// SetSessionDescriptionObserver as an argument.
738class PeerConnection::SetRemoteDescriptionObserverAdapter
739 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
740 public:
741 SetRemoteDescriptionObserverAdapter(
742 rtc::scoped_refptr<PeerConnection> pc,
743 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
744 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
745
746 // SetRemoteDescriptionObserverInterface implementation.
747 void OnSetRemoteDescriptionComplete(RTCError error) override {
748 if (error.ok())
749 pc_->PostSetSessionDescriptionSuccess(wrapper_);
750 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100751 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100752 }
753
754 private:
755 rtc::scoped_refptr<PeerConnection> pc_;
756 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
757};
758
deadbeef293e9262017-01-11 12:28:30 -0800759bool PeerConnectionInterface::RTCConfiguration::operator==(
760 const PeerConnectionInterface::RTCConfiguration& o) const {
761 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700762 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800763 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000764 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700765 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800766 BundlePolicy bundle_policy;
767 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700768 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
769 int ice_candidate_pool_size;
770 bool disable_ipv6;
771 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700772 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100773 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700774 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200775 absl::optional<int> screencast_min_bitrate;
776 absl::optional<bool> combined_audio_video_bwe;
777 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800778 TcpCandidatePolicy tcp_candidate_policy;
779 CandidateNetworkPolicy candidate_network_policy;
780 int audio_jitter_buffer_max_packets;
781 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100782 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100783 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800784 int ice_connection_receiving_timeout;
785 int ice_backup_candidate_pair_ping_interval;
786 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800787 bool prioritize_most_likely_ice_candidate_pairs;
788 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800789 bool prune_turn_ports;
790 bool presume_writable_when_fully_relayed;
791 bool enable_ice_renomination;
792 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700793 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200794 absl::optional<int> ice_check_interval_strong_connectivity;
795 absl::optional<int> ice_check_interval_weak_connectivity;
796 absl::optional<int> ice_check_min_interval;
797 absl::optional<int> ice_unwritable_timeout;
798 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800799 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200800 absl::optional<int> stun_candidate_keepalive_interval;
801 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200802 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800803 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200804 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700805 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700806 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700807 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700808 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700809 absl::optional<bool> use_datagram_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700810 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100811 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200812 std::string turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -0800813 };
814 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
815 "Did you add something to RTCConfiguration and forget to "
816 "update operator==?");
817 return type == o.type && servers == o.servers &&
818 bundle_policy == o.bundle_policy &&
819 rtcp_mux_policy == o.rtcp_mux_policy &&
820 tcp_candidate_policy == o.tcp_candidate_policy &&
821 candidate_network_policy == o.candidate_network_policy &&
822 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
823 audio_jitter_buffer_fast_accelerate ==
824 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100825 audio_jitter_buffer_min_delay_ms ==
826 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100827 audio_jitter_buffer_enable_rtx_handling ==
828 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800829 ice_connection_receiving_timeout ==
830 o.ice_connection_receiving_timeout &&
831 ice_backup_candidate_pair_ping_interval ==
832 o.ice_backup_candidate_pair_ping_interval &&
833 continual_gathering_policy == o.continual_gathering_policy &&
834 certificates == o.certificates &&
835 prioritize_most_likely_ice_candidate_pairs ==
836 o.prioritize_most_likely_ice_candidate_pairs &&
837 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800838 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700839 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100840 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800841 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800842 screencast_min_bitrate == o.screencast_min_bitrate &&
843 combined_audio_video_bwe == o.combined_audio_video_bwe &&
844 enable_dtls_srtp == o.enable_dtls_srtp &&
845 ice_candidate_pool_size == o.ice_candidate_pool_size &&
846 prune_turn_ports == o.prune_turn_ports &&
847 presume_writable_when_fully_relayed ==
848 o.presume_writable_when_fully_relayed &&
849 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800850 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700851 surface_ice_candidates_on_ice_transport_type_changed ==
852 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800853 ice_check_interval_strong_connectivity ==
854 o.ice_check_interval_strong_connectivity &&
855 ice_check_interval_weak_connectivity ==
856 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700857 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700858 ice_unwritable_timeout == o.ice_unwritable_timeout &&
859 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800860 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800861 stun_candidate_keepalive_interval ==
862 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200863 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800864 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800865 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700866 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700867 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700868 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700869 use_media_transport_for_data_channels ==
870 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700871 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700872 use_datagram_transport_for_data_channels ==
873 o.use_datagram_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100874 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200875 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
876 turn_logging_id == o.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -0800877}
878
879bool PeerConnectionInterface::RTCConfiguration::operator!=(
880 const PeerConnectionInterface::RTCConfiguration& o) const {
881 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800882}
883
zhihuang8f65cdf2016-05-06 18:40:30 -0700884// Generate a RTCP CNAME when a PeerConnection is created.
885std::string GenerateRtcpCname() {
886 std::string cname;
887 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100888 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800889 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700890 }
891 return cname;
892}
893
zhihuang1c378ed2017-08-17 14:10:50 -0700894bool ValidateOfferAnswerOptions(
895 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
896 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
897 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700898}
899
zhihuang1c378ed2017-08-17 14:10:50 -0700900// From |rtc_options|, fill parts of |session_options| shared by all generated
901// m= sections (in other words, nothing that involves a map/array).
902void ExtractSharedMediaSessionOptions(
903 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
904 cricket::MediaSessionOptions* session_options) {
905 session_options->vad_enabled = rtc_options.voice_activity_detection;
906 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200907 session_options->raw_packetization_for_video =
908 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700909}
zhihuanga77e6bb2017-08-14 18:17:48 -0700910
zhihuang38ede132017-06-15 12:52:32 -0700911PeerConnection::PeerConnection(PeerConnectionFactory* factory,
912 std::unique_ptr<RtcEventLog> event_log,
913 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700915 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100916 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700917 datagram_transport_config_(
918 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700919 datagram_transport_data_channel_config_(
920 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700921 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700922 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700923 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100924 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200925 call_ptr_(call_.get()),
926 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927
928PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100929 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800930 RTC_DCHECK_RUN_ON(signaling_thread());
931
Steve Anton8af21862017-12-15 11:20:13 -0800932 // Need to stop transceivers before destroying the stats collector because
933 // AudioRtpSender has a reference to the StatsCollector it will update when
934 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100935 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800936 transceiver->Stop();
937 }
Steve Anton4171afb2017-11-20 10:20:22 -0800938
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700939 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800940 if (stats_collector_) {
941 stats_collector_->WaitForPendingRequest();
942 stats_collector_ = nullptr;
943 }
Steve Anton75737c02017-11-06 10:37:17 -0800944
Steve Anton8af21862017-12-15 11:20:13 -0800945 // Don't destroy BaseChannels until after stats has been cleaned up so that
946 // the last stats request can still read from the channels.
947 DestroyAllChannels();
948
Mirko Bonadei675513b2017-11-09 11:09:25 +0100949 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800950
951 webrtc_session_desc_factory_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +0000952 sctp_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800953 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700954 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800955 transport_controller_.reset();
956
deadbeef91dd5672016-05-18 16:55:30 -0700957 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100958 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
959 RTC_DCHECK_RUN_ON(network_thread());
960 port_allocator_.reset();
961 });
eladalon248fd4f2017-09-06 05:18:15 -0700962 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700963 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100964 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700965 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800966 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700967 event_log_.reset();
968 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969}
970
Steve Anton8af21862017-12-15 11:20:13 -0800971void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800972 // Destroy video channels first since they may have a pointer to a voice
973 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100974 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800975 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800976 DestroyTransceiverChannel(transceiver);
977 }
978 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100979 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800980 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800981 DestroyTransceiverChannel(transceiver);
982 }
983 }
984 DestroyDataChannel();
985}
986
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000988 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700989 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100990 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100991 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100992 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700993
994 RTCError config_error = ValidateConfiguration(configuration);
995 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100996 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700997 return false;
998 }
999
Benjamin Wrightcab58882018-05-02 15:12:47 -07001000 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001001 RTC_LOG(LS_ERROR)
1002 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001003 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001004 return false;
1005 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001006
Benjamin Wrightcab58882018-05-02 15:12:47 -07001007 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001008 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001009 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001010 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001011 return false;
1012 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001013
Benjamin Wrightcab58882018-05-02 15:12:47 -07001014 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001015 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001016 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001017 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001018
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001019 cricket::ServerAddresses stun_servers;
1020 std::vector<cricket::RelayServerConfig> turn_servers;
1021
1022 RTCErrorType parse_error =
1023 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1024 if (parse_error != RTCErrorType::NONE) {
1025 return false;
1026 }
1027
Jonas Oreland3c028422019-08-22 16:16:35 +02001028 // Add the turn logging id to all turn servers
1029 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1030 turn_server.turn_logging_id = configuration.turn_logging_id;
1031 }
1032
deadbeef91dd5672016-05-18 16:55:30 -07001033 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001034 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001035 const auto pa_result =
1036 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001037 RTC_FROM_HERE,
1038 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001039 stun_servers, turn_servers, configuration));
1040
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001041 // If initialization was successful, note if STUN or TURN servers
1042 // were supplied.
1043 if (!stun_servers.empty()) {
1044 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1045 }
1046 if (!turn_servers.empty()) {
1047 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1048 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001050 // Send information about IPv4/IPv6 status.
1051 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001052 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001053 address_family = kPeerConnection_IPv6;
1054 } else {
1055 address_family = kPeerConnection_IPv4;
1056 }
1057 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1058 kPeerConnectionAddressFamilyCounter_Max);
1059
Zhi Huange830e682018-03-30 10:48:35 -07001060 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1061
Steve Anton75737c02017-11-06 10:37:17 -08001062 // RFC 3264: The numeric value of the session id and version in the
1063 // o line MUST be representable with a "64 bit signed integer".
1064 // Due to this constraint session id |session_id_| is max limited to
1065 // LLONG_MAX.
1066 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001067 JsepTransportController::Config config;
1068 config.redetermine_role_on_ice_restart =
1069 configuration.redetermine_role_on_ice_restart;
1070 config.ssl_max_version = factory_->options().ssl_max_version;
1071 config.disable_encryption = options.disable_encryption;
1072 config.bundle_policy = configuration.bundle_policy;
1073 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001074 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1075 // stub.
1076 config.crypto_options = configuration.crypto_options.has_value()
1077 ? *configuration.crypto_options
1078 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001079 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001080 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1081 // since the JsepTransportController instance is owned by this PeerConnection
1082 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1083 // pointer.
1084 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1085 int64_t packet_time_us) {
1086 RTC_DCHECK_RUN_ON(network_thread());
1087 rtcp_invoker_.AsyncInvoke<void>(
1088 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1089 RTC_DCHECK_RUN_ON(worker_thread());
1090 // |call_| is reset on the worker thread in the PeerConnection
1091 // destructor, so we check that it's still valid before propagating
1092 // the packet.
1093 if (call_) {
1094 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1095 packet_time_us);
1096 }
1097 });
1098 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001099 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001100#if defined(ENABLE_EXTERNAL_AUTH)
1101 config.enable_external_auth = true;
1102#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001103 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001104
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001105 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001106 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001107 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001108 use_datagram_transport_for_data_channels_ =
1109 datagram_transport_data_channel_config_.enabled &&
1110 configuration.use_datagram_transport_for_data_channels.value_or(
1111 datagram_transport_data_channel_config_.default_value);
1112 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1113 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001114 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001115 if (!factory_->media_transport_factory()) {
1116 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001117 << "PeerConnecton is initialized with use_media_transport = true or "
1118 << "use_media_transport_for_data_channels = true "
1119 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001120 return false;
1121 }
1122
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001123 if (configuration.use_media_transport ||
1124 configuration.use_media_transport_for_data_channels) {
1125 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1126 // RTP media transport is introduced. But until then, we require SDES to
1127 // be enabled.
1128 if (configuration.enable_dtls_srtp.has_value() &&
1129 configuration.enable_dtls_srtp.value()) {
1130 RTC_LOG(LS_WARNING)
1131 << "When media transport is used, SDES must be enabled. Set "
1132 "configuration.enable_dtls_srtp to false. use_media_transport="
1133 << configuration.use_media_transport
1134 << ", use_media_transport_for_data_channels="
1135 << configuration.use_media_transport_for_data_channels;
1136 return false;
1137 }
1138 }
1139
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001140 config.use_media_transport_for_media = configuration.use_media_transport;
1141 config.use_media_transport_for_data_channels =
1142 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001143 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001144 config.use_datagram_transport_for_data_channels =
1145 use_datagram_transport_for_data_channels_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001146 config.media_transport_factory = factory_->media_transport_factory();
1147 }
1148
Zhi Huange830e682018-03-30 10:48:35 -07001149 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001150 signaling_thread(), network_thread(), port_allocator_.get(),
1151 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001152 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001153 this, &PeerConnection::OnTransportControllerConnectionState);
1154 transport_controller_->SignalStandardizedIceConnectionState.connect(
1155 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001156 transport_controller_->SignalConnectionState.connect(
1157 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001158 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001159 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001160 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001161 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001162 transport_controller_->SignalIceCandidateError.connect(
1163 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001164 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001165 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1166 transport_controller_->SignalDtlsHandshakeError.connect(
1167 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001168 transport_controller_->SignalIceCandidatePairChanged.connect(
1169 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001170
Qingsi Wang437077d2019-09-10 17:52:26 +00001171 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1172
deadbeefab9b2d12015-10-14 11:33:11 -07001173 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001174 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175
Steve Antonba818672017-11-06 10:21:57 -08001176 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001177 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001178
Qingsi Wang437077d2019-09-10 17:52:26 +00001179 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1180 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1181 if (!configuration.certificates.empty()) {
1182 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1183 // just picking the first one. The decision should be made based on the DTLS
1184 // handshake. The DTLS negotiations need to know about all certificates.
1185 certificate = configuration.certificates[0];
1186 }
1187
Steve Antond25da372017-11-06 14:50:29 -08001188 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001189
Qingsi Wang437077d2019-09-10 17:52:26 +00001190 if (options.disable_encryption) {
1191 dtls_enabled_ = false;
1192 } else {
1193 // Enable DTLS by default if we have an identity store or a certificate.
1194 dtls_enabled_ = (dependencies.cert_generator || certificate);
1195 // |configuration| can override the default |dtls_enabled_| value.
1196 if (configuration.enable_dtls_srtp) {
1197 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1198 }
1199 }
1200
1201 if (use_datagram_transport_for_data_channels_) {
1202 if (configuration.enable_rtp_data_channel) {
1203 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1204 "use_datagram_transport_for_data_channels are "
1205 "incompatible and cannot both be set to true";
1206 return false;
1207 }
1208 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1209 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1210 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1211 } else {
1212 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1213 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1214 }
1215 } else if (configuration.use_media_transport_for_data_channels) {
1216 if (configuration.enable_rtp_data_channel) {
1217 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1218 "use_media_transport_for_data_channels are "
1219 "incompatible and cannot both be set to true";
1220 return false;
1221 }
1222 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1223 } else if (configuration.enable_rtp_data_channel) {
1224 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1225 // set. It takes precendence over the disable_sctp_data_channels
1226 // PeerConnectionFactoryInterface::Options.
1227 data_channel_type_ = cricket::DCT_RTP;
1228 } else {
1229 // DTLS has to be enabled to use SCTP.
1230 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1231 data_channel_type_ = cricket::DCT_SCTP;
1232 }
1233 }
1234
Steve Anton75737c02017-11-06 10:37:17 -08001235 video_options_.screencast_min_bitrate_kbps =
1236 configuration.screencast_min_bitrate;
1237 audio_options_.combined_audio_video_bwe =
1238 configuration.combined_audio_video_bwe;
1239
1240 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001241 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001242
1243 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001244 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001245
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001246 audio_options_.audio_jitter_buffer_min_delay_ms =
1247 configuration.audio_jitter_buffer_min_delay_ms;
1248
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001249 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1250 configuration.audio_jitter_buffer_enable_rtx_handling;
1251
Steve Anton75737c02017-11-06 10:37:17 -08001252 // Whether the certificate generator/certificate is null or not determines
1253 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1254 // the right instructions by clearing the variables if needed.
1255 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001256 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001257 certificate = nullptr;
1258 } else if (certificate) {
1259 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001260 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001261 }
1262
1263 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1264 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001265 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001266 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1267 this, &PeerConnection::OnCertificateReady);
1268
1269 if (options.disable_encryption) {
1270 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1271 }
1272
1273 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001274 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001275 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276
Steve Anton4171afb2017-11-20 10:20:22 -08001277 // Add default audio/video transceivers for Plan B SDP.
1278 if (!IsUnifiedPlan()) {
1279 transceivers_.push_back(
1280 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1281 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1282 transceivers_.push_back(
1283 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1284 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1285 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001286 int delay_ms =
1287 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001288 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1289 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001290
1291 if (dependencies.video_bitrate_allocator_factory) {
1292 video_bitrate_allocator_factory_ =
1293 std::move(dependencies.video_bitrate_allocator_factory);
1294 } else {
1295 video_bitrate_allocator_factory_ =
1296 CreateBuiltinVideoBitrateAllocatorFactory();
1297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298 return true;
1299}
1300
Steve Anton038834f2017-07-14 15:59:59 -07001301RTCError PeerConnection::ValidateConfiguration(
1302 const RTCConfiguration& config) const {
1303 if (config.ice_regather_interval_range &&
1304 config.continual_gathering_policy == GATHER_ONCE) {
1305 return RTCError(RTCErrorType::INVALID_PARAMETER,
1306 "ice_regather_interval_range specified but continual "
1307 "gathering policy is GATHER_ONCE");
1308 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001309 auto result =
1310 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1311 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001312}
1313
Yves Gerey665174f2018-06-19 15:03:05 +02001314rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001315 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001316 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1317 "Plan SdpSemantics. Please use GetSenders "
1318 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001319 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320}
1321
Yves Gerey665174f2018-06-19 15:03:05 +02001322rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001323 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001324 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1325 "Plan SdpSemantics. Please use GetReceivers "
1326 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001327 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328}
1329
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001330bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001331 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001332 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1333 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001334 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335 if (IsClosed()) {
1336 return false;
1337 }
deadbeefab9b2d12015-10-14 11:33:11 -07001338 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339 return false;
1340 }
deadbeefab9b2d12015-10-14 11:33:11 -07001341
1342 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001343 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1344 observer->SignalAudioTrackAdded.connect(this,
1345 &PeerConnection::OnAudioTrackAdded);
1346 observer->SignalAudioTrackRemoved.connect(
1347 this, &PeerConnection::OnAudioTrackRemoved);
1348 observer->SignalVideoTrackAdded.connect(this,
1349 &PeerConnection::OnVideoTrackAdded);
1350 observer->SignalVideoTrackRemoved.connect(
1351 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001352 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001353
deadbeefab9b2d12015-10-14 11:33:11 -07001354 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001355 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001356 }
1357 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001358 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001359 }
1360
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001361 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001362 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 return true;
1364}
1365
1366void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001367 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001368 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1369 "Plan SdpSemantics. Please use RemoveTrack "
1370 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001371 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001372 if (!IsClosed()) {
1373 for (const auto& track : local_stream->GetAudioTracks()) {
1374 RemoveAudioTrack(track.get(), local_stream);
1375 }
1376 for (const auto& track : local_stream->GetVideoTracks()) {
1377 RemoveVideoTrack(track.get(), local_stream);
1378 }
deadbeefab9b2d12015-10-14 11:33:11 -07001379 }
deadbeefab9b2d12015-10-14 11:33:11 -07001380 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001381 stream_observers_.erase(
1382 std::remove_if(
1383 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001384 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001385 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001386 }),
1387 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001388
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 if (IsClosed()) {
1390 return;
1391 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001392 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393}
1394
Steve Anton2d6c76a2018-01-05 17:10:52 -08001395RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001396 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001397 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001398 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001399 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001400 if (!track) {
1401 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1402 }
1403 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1404 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1405 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1406 "Track has invalid kind: " + track->kind());
1407 }
Steve Antonf9381f02017-12-14 10:23:57 -08001408 if (IsClosed()) {
1409 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1410 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001411 }
Steve Anton4171afb2017-11-20 10:20:22 -08001412 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001413 LOG_AND_RETURN_ERROR(
1414 RTCErrorType::INVALID_PARAMETER,
1415 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001416 }
Steve Antonf9381f02017-12-14 10:23:57 -08001417 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001418 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1419 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001420 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001421 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001422 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001423 }
1424 return sender_or_error;
1425}
deadbeefe1f9d832016-01-14 15:35:42 -08001426
Steve Antonf9381f02017-12-14 10:23:57 -08001427RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1428PeerConnection::AddTrackPlanB(
1429 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001430 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001431 if (stream_ids.size() > 1u) {
1432 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1433 "AddTrack with more than one stream is not "
1434 "supported with Plan B semantics.");
1435 }
1436 std::vector<std::string> adjusted_stream_ids = stream_ids;
1437 if (adjusted_stream_ids.empty()) {
1438 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1439 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001440 cricket::MediaType media_type =
1441 (track->kind() == MediaStreamTrackInterface::kAudioKind
1442 ? cricket::MEDIA_TYPE_AUDIO
1443 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001444 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001445 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001446 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001447 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001448 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001449 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001450 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001451 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001452 if (sender_info) {
1453 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001454 }
Steve Antonf9381f02017-12-14 10:23:57 -08001455 } else {
1456 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001457 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001458 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001459 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001460 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001461 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001462 if (sender_info) {
1463 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001464 }
deadbeefe1f9d832016-01-14 15:35:42 -08001465 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001466 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001467}
deadbeefe1f9d832016-01-14 15:35:42 -08001468
Steve Antonf9381f02017-12-14 10:23:57 -08001469RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1470PeerConnection::AddTrackUnifiedPlan(
1471 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001472 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001473 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1474 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001475 RTC_LOG(LS_INFO) << "Reusing an existing "
1476 << cricket::MediaTypeToString(transceiver->media_type())
1477 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001478 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001479 transceiver->internal()->set_direction(
1480 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001481 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001482 transceiver->internal()->set_direction(
1483 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001484 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001485 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001486 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001487 } else {
1488 cricket::MediaType media_type =
1489 (track->kind() == MediaStreamTrackInterface::kAudioKind
1490 ? cricket::MEDIA_TYPE_AUDIO
1491 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001492 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1493 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001494 std::string sender_id = track->id();
1495 // Avoid creating a sender with an existing ID by generating a random ID.
1496 // This can happen if this is the second time AddTrack has created a sender
1497 // for this track.
1498 if (FindSenderById(sender_id)) {
1499 sender_id = rtc::CreateRandomUuid();
1500 }
Florent Castelli892acf02018-10-01 22:47:20 +02001501 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1503 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001504 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001505 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001506 }
Steve Antonf9381f02017-12-14 10:23:57 -08001507 return transceiver->sender();
1508}
1509
1510rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1511PeerConnection::FindFirstTransceiverForAddedTrack(
1512 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1513 RTC_DCHECK(track);
1514 for (auto transceiver : transceivers_) {
1515 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001516 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001517 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001518 !transceiver->internal()->has_ever_been_used_to_send() &&
1519 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001520 return transceiver;
1521 }
1522 }
1523 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001524}
1525
1526bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1527 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001528 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001529}
1530
Steve Anton24db5732018-07-23 10:27:33 -07001531RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001532 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001533 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001534 if (!sender) {
1535 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1536 }
deadbeefe1f9d832016-01-14 15:35:42 -08001537 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001538 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1539 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001540 }
Steve Antonf9381f02017-12-14 10:23:57 -08001541 if (IsUnifiedPlan()) {
1542 auto transceiver = FindTransceiverBySender(sender);
1543 if (!transceiver || !sender->track()) {
1544 return RTCError::OK();
1545 }
1546 sender->SetTrack(nullptr);
1547 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001548 transceiver->internal()->set_direction(
1549 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001550 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001551 transceiver->internal()->set_direction(
1552 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001553 }
Steve Anton4171afb2017-11-20 10:20:22 -08001554 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001555 bool removed;
1556 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1557 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1558 } else {
1559 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1560 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1561 }
1562 if (!removed) {
1563 LOG_AND_RETURN_ERROR(
1564 RTCErrorType::INVALID_PARAMETER,
1565 "Couldn't find sender " + sender->id() + " to remove.");
1566 }
Steve Anton4171afb2017-11-20 10:20:22 -08001567 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001568 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001569 return RTCError::OK();
1570}
1571
1572rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1573PeerConnection::FindTransceiverBySender(
1574 rtc::scoped_refptr<RtpSenderInterface> sender) {
1575 for (auto transceiver : transceivers_) {
1576 if (transceiver->sender() == sender) {
1577 return transceiver;
1578 }
1579 }
1580 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001581}
1582
Steve Anton9158ef62017-11-27 13:01:52 -08001583RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1584PeerConnection::AddTransceiver(
1585 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1586 return AddTransceiver(track, RtpTransceiverInit());
1587}
1588
1589RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1590PeerConnection::AddTransceiver(
1591 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1592 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001593 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001594 RTC_CHECK(IsUnifiedPlan())
1595 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001596 if (!track) {
1597 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1598 }
1599 cricket::MediaType media_type;
1600 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1601 media_type = cricket::MEDIA_TYPE_AUDIO;
1602 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1603 media_type = cricket::MEDIA_TYPE_VIDEO;
1604 } else {
1605 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1606 "Track kind is not audio or video");
1607 }
1608 return AddTransceiver(media_type, track, init);
1609}
1610
1611RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1612PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1613 return AddTransceiver(media_type, RtpTransceiverInit());
1614}
1615
1616RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1617PeerConnection::AddTransceiver(cricket::MediaType media_type,
1618 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001619 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001620 RTC_CHECK(IsUnifiedPlan())
1621 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001622 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1623 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1624 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1625 "media type is not audio or video");
1626 }
1627 return AddTransceiver(media_type, nullptr, init);
1628}
1629
1630RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1631PeerConnection::AddTransceiver(
1632 cricket::MediaType media_type,
1633 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001634 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001635 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001636 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1637 media_type == cricket::MEDIA_TYPE_VIDEO));
1638 if (track) {
1639 RTC_DCHECK_EQ(media_type,
1640 (track->kind() == MediaStreamTrackInterface::kAudioKind
1641 ? cricket::MEDIA_TYPE_AUDIO
1642 : cricket::MEDIA_TYPE_VIDEO));
1643 }
1644
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001645 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1646 init.send_encodings.size(), 0, 7, 8);
1647
Amit Hilbuchaa584152019-02-06 17:09:52 -08001648 size_t num_rids = absl::c_count_if(init.send_encodings,
1649 [](const RtpEncodingParameters& encoding) {
1650 return !encoding.rid.empty();
1651 });
1652 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001653 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001654 RTCErrorType::INVALID_PARAMETER,
1655 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001656 }
1657
Amit Hilbuchf4770402019-04-08 14:11:57 -07001658 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1659 [](const RtpEncodingParameters& encoding) {
1660 return !IsLegalRsidName(encoding.rid);
1661 })) {
1662 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1663 "Invalid RID value provided.");
1664 }
1665
Amit Hilbuchaa584152019-02-06 17:09:52 -08001666 if (absl::c_any_of(init.send_encodings,
1667 [](const RtpEncodingParameters& encoding) {
1668 return encoding.ssrc.has_value();
1669 })) {
1670 LOG_AND_RETURN_ERROR(
1671 RTCErrorType::UNSUPPORTED_PARAMETER,
1672 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001673 }
1674
1675 RtpParameters parameters;
1676 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001677
1678 // Encodings are dropped from the tail if too many are provided.
1679 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1680 parameters.encodings.erase(
1681 parameters.encodings.begin() + kMaxSimulcastStreams,
1682 parameters.encodings.end());
1683 }
1684
1685 // Single RID should be removed.
1686 if (parameters.encodings.size() == 1 &&
1687 !parameters.encodings[0].rid.empty()) {
1688 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1689 parameters.encodings[0].rid.clear();
1690 }
1691
1692 // If RIDs were not provided, they are generated for simulcast scenario.
1693 if (parameters.encodings.size() > 1 && num_rids == 0) {
1694 rtc::UniqueStringGenerator rid_generator;
1695 for (RtpEncodingParameters& encoding : parameters.encodings) {
1696 encoding.rid = rid_generator();
1697 }
1698 }
1699
Florent Castelli892acf02018-10-01 22:47:20 +02001700 if (UnimplementedRtpParameterHasValue(parameters)) {
1701 LOG_AND_RETURN_ERROR(
1702 RTCErrorType::UNSUPPORTED_PARAMETER,
1703 "Attempted to set an unimplemented parameter of RtpParameters.");
1704 }
Steve Anton9158ef62017-11-27 13:01:52 -08001705
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001706 auto result = cricket::CheckRtpParametersValues(parameters);
1707 if (!result.ok()) {
1708 LOG_AND_RETURN_ERROR(result.type(), result.message());
1709 }
1710
Steve Anton3d954a62018-04-02 11:27:23 -07001711 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1712 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001713 // Set the sender ID equal to the track ID if the track is specified unless
1714 // that sender ID is already in use.
1715 std::string sender_id =
1716 (track && !FindSenderById(track->id()) ? track->id()
1717 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001718 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001719 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001720 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1721 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1722 transceiver->internal()->set_direction(init.direction);
1723
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001724 if (update_negotiation_needed) {
1725 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001726 }
Steve Antonf9381f02017-12-14 10:23:57 -08001727
1728 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1729}
1730
Steve Anton02ee47c2018-01-10 16:26:06 -08001731rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1732PeerConnection::CreateSender(
1733 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001734 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001735 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001736 const std::vector<std::string>& stream_ids,
1737 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001738 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001739 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001740 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1741 RTC_DCHECK(!track ||
1742 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1743 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1744 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001745 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001746 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001747 } else {
1748 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1749 RTC_DCHECK(!track ||
1750 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1751 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001752 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001753 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001754 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001755 bool set_track_succeeded = sender->SetTrack(track);
1756 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001757 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001758 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001759 return sender;
1760}
1761
1762rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1763PeerConnection::CreateReceiver(cricket::MediaType media_type,
1764 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001765 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1766 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001767 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001768 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001769 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1770 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001771 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001772 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001773 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001774 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001775 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1776 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001777 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001778 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001779 return receiver;
1780}
1781
1782rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1783PeerConnection::CreateAndAddTransceiver(
1784 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1785 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1786 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001787 // Ensure that the new sender does not have an ID that is already in use by
1788 // another sender.
1789 // Allow receiver IDs to conflict since those come from remote SDP (which
1790 // could be invalid, but should not cause a crash).
1791 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001792 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001793 signaling_thread(),
1794 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001795 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001796 transceiver->internal()->SignalNegotiationNeeded.connect(
1797 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001798 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001799}
1800
Steve Anton52d86772018-02-20 15:48:12 -08001801void PeerConnection::OnNegotiationNeeded() {
1802 RTC_DCHECK_RUN_ON(signaling_thread());
1803 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001804 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001805}
1806
deadbeeffac06552015-11-25 11:26:01 -08001807rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001808 const std::string& kind,
1809 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001810 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001811 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1812 "Plan SdpSemantics. Please use AddTransceiver "
1813 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001814 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001815 if (IsClosed()) {
1816 return nullptr;
1817 }
Steve Anton4171afb2017-11-20 10:20:22 -08001818
Seth Hampson5b4f0752018-04-02 16:31:36 -07001819 // Internally we need to have one stream with Plan B semantics, so we
1820 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001821 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001822 if (stream_id.empty()) {
1823 stream_ids.push_back(rtc::CreateRandomUuid());
1824 RTC_LOG(LS_INFO)
1825 << "No stream_id specified for sender. Generated stream ID: "
1826 << stream_ids[0];
1827 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001828 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001829 }
1830
Steve Anton4171afb2017-11-20 10:20:22 -08001831 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001832 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001833 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001834 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001835 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001836 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001837 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001838 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001839 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001840 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001841 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001842 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001843 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001844 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001845 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001846 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001847 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001848 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001849 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001850 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001851 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001852
deadbeefe1f9d832016-01-14 15:35:42 -08001853 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001854}
1855
deadbeef70ab1a12015-09-28 16:53:55 -07001856std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1857 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001858 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001859 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001860 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001861 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001862 }
1863 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001864}
1865
Steve Anton4171afb2017-11-20 10:20:22 -08001866std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1867PeerConnection::GetSendersInternal() const {
1868 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1869 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001870 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001871 auto senders = transceiver->internal()->senders();
1872 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1873 }
1874 return all_senders;
1875}
1876
deadbeef70ab1a12015-09-28 16:53:55 -07001877std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1878PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001879 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001880 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001881 for (const auto& receiver : GetReceiversInternal()) {
1882 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001883 }
1884 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001885}
1886
Steve Anton4171afb2017-11-20 10:20:22 -08001887std::vector<
1888 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1889PeerConnection::GetReceiversInternal() const {
1890 std::vector<
1891 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1892 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001893 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001894 auto receivers = transceiver->internal()->receivers();
1895 all_receivers.insert(all_receivers.end(), receivers.begin(),
1896 receivers.end());
1897 }
1898 return all_receivers;
1899}
1900
Steve Anton9158ef62017-11-27 13:01:52 -08001901std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1902PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001903 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001904 RTC_CHECK(IsUnifiedPlan())
1905 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001906 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001907 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001908 all_transceivers.push_back(transceiver);
1909 }
1910 return all_transceivers;
1911}
1912
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001913bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001914 MediaStreamTrackInterface* track,
1915 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001916 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001917 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001918 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001919 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001920 return false;
1921 }
1922
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001923 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001924 // The StatsCollector is used to tell if a track is valid because it may
1925 // remember tracks that the PeerConnection previously removed.
1926 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001927 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1928 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001929 return false;
1930 }
Steve Antonad182762018-09-05 20:22:40 +00001931 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1932 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 return true;
1934}
1935
hbos74e1a4f2016-09-15 23:33:01 -07001936void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001937 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001938 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001939 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001940 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001941 stats_collector_->GetStatsReport(callback);
1942}
1943
Henrik Boström1df1bf82018-03-20 13:24:20 +01001944void PeerConnection::GetStats(
1945 rtc::scoped_refptr<RtpSenderInterface> selector,
1946 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1947 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001948 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001949 RTC_DCHECK(callback);
1950 RTC_DCHECK(stats_collector_);
1951 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1952 if (selector) {
1953 for (const auto& proxy_transceiver : transceivers_) {
1954 for (const auto& proxy_sender :
1955 proxy_transceiver->internal()->senders()) {
1956 if (proxy_sender == selector) {
1957 internal_sender = proxy_sender->internal();
1958 break;
1959 }
1960 }
1961 if (internal_sender)
1962 break;
1963 }
1964 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001965 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001966 // belong to the PeerConnection (in Plan B, senders can be removed from the
1967 // PeerConnection). This means that "all the stats objects representing the
1968 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1969 // produces an empty stats report.
1970 stats_collector_->GetStatsReport(internal_sender, callback);
1971}
1972
1973void PeerConnection::GetStats(
1974 rtc::scoped_refptr<RtpReceiverInterface> selector,
1975 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1976 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001977 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001978 RTC_DCHECK(callback);
1979 RTC_DCHECK(stats_collector_);
1980 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1981 if (selector) {
1982 for (const auto& proxy_transceiver : transceivers_) {
1983 for (const auto& proxy_receiver :
1984 proxy_transceiver->internal()->receivers()) {
1985 if (proxy_receiver == selector) {
1986 internal_receiver = proxy_receiver->internal();
1987 break;
1988 }
1989 }
1990 if (internal_receiver)
1991 break;
1992 }
1993 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001994 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001995 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1996 // the PeerConnection). This means that "all the stats objects representing
1997 // the selector" is an empty set. Invoking GetStatsReport() with a null
1998 // selector produces an empty stats report.
1999 stats_collector_->GetStatsReport(internal_receiver, callback);
2000}
2001
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002003 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 return signaling_state_;
2005}
2006
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007PeerConnectionInterface::IceConnectionState
2008PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002009 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 return ice_connection_state_;
2011}
2012
Alex Loiko9289eda2018-11-23 16:18:59 +00002013PeerConnectionInterface::IceConnectionState
2014PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002015 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00002016 return standardized_ice_connection_state_;
2017}
2018
Jonas Olsson635474e2018-10-18 15:58:17 +02002019PeerConnectionInterface::PeerConnectionState
2020PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002021 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002022 return connection_state_;
2023}
2024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025PeerConnectionInterface::IceGatheringState
2026PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002027 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 return ice_gathering_state_;
2029}
2030
Yves Gerey665174f2018-06-19 15:03:05 +02002031rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032 const std::string& label,
2033 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002034 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002035 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002036
deadbeefab9b2d12015-10-14 11:33:11 -07002037 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002038
kwibergd1fe2812016-04-27 06:47:29 -07002039 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002040 if (config) {
2041 internal_config.reset(new InternalDataChannelInit(*config));
2042 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002043 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002044 InternalCreateDataChannel(label, internal_config.get()));
2045 if (!channel.get()) {
2046 return nullptr;
2047 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002049 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2050 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002051 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002052 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002053 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002054 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002055 return DataChannelProxy::Create(signaling_thread(), channel.get());
2056}
2057
Henrik Boström79b69802019-07-18 11:16:56 +02002058void PeerConnection::RestartIce() {
2059 RTC_DCHECK_RUN_ON(signaling_thread());
2060 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2061 current_local_description_.get(), pending_local_description_.get());
2062 UpdateNegotiationNeeded();
2063}
2064
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002065void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002066 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002067 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002068 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002069
nisse7ce109a2017-01-31 00:57:56 -08002070 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002071 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002072 return;
2073 }
deadbeefab9b2d12015-10-14 11:33:11 -07002074
Steve Anton8d3444d2017-10-20 15:30:51 -07002075 if (IsClosed()) {
2076 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002077 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002078 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002079 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002080 return;
2081 }
2082
Steve Anton25ca0ac2019-06-25 10:40:48 -07002083 // If a session error has occurred the PeerConnection is in a possibly
2084 // inconsistent state so fail right away.
2085 if (session_error() != SessionError::kNone) {
2086 std::string error_message = GetSessionErrorMsg();
2087 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2088 PostCreateSessionDescriptionFailure(
2089 observer,
2090 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2091 return;
2092 }
2093
zhihuang1c378ed2017-08-17 14:10:50 -07002094 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002095 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002096 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002097 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002098 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002099 return;
2100 }
2101
Steve Anton22da89f2018-01-25 13:58:07 -08002102 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2103 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2104 if (IsUnifiedPlan()) {
2105 RTCError error = HandleLegacyOfferOptions(options);
2106 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002107 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002108 return;
2109 }
2110 }
2111
zhihuang1c378ed2017-08-17 14:10:50 -07002112 cricket::MediaSessionOptions session_options;
2113 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002114 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002115}
2116
Steve Anton22da89f2018-01-25 13:58:07 -08002117RTCError PeerConnection::HandleLegacyOfferOptions(
2118 const RTCOfferAnswerOptions& options) {
2119 RTC_DCHECK(IsUnifiedPlan());
2120
2121 if (options.offer_to_receive_audio == 0) {
2122 RemoveRecvDirectionFromReceivingTransceiversOfType(
2123 cricket::MEDIA_TYPE_AUDIO);
2124 } else if (options.offer_to_receive_audio == 1) {
2125 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2126 } else if (options.offer_to_receive_audio > 1) {
2127 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2128 "offer_to_receive_audio > 1 is not supported.");
2129 }
2130
2131 if (options.offer_to_receive_video == 0) {
2132 RemoveRecvDirectionFromReceivingTransceiversOfType(
2133 cricket::MEDIA_TYPE_VIDEO);
2134 } else if (options.offer_to_receive_video == 1) {
2135 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2136 } else if (options.offer_to_receive_video > 1) {
2137 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2138 "offer_to_receive_video > 1 is not supported.");
2139 }
2140
2141 return RTCError::OK();
2142}
2143
2144void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2145 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002146 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002147 RtpTransceiverDirection new_direction =
2148 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2149 if (new_direction != transceiver->direction()) {
2150 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2151 << " transceiver (MID="
2152 << transceiver->mid().value_or("<not set>") << ") from "
2153 << RtpTransceiverDirectionToString(
2154 transceiver->direction())
2155 << " to "
2156 << RtpTransceiverDirectionToString(new_direction)
2157 << " since CreateOffer specified offer_to_receive=0";
2158 transceiver->internal()->set_direction(new_direction);
2159 }
Steve Anton22da89f2018-01-25 13:58:07 -08002160 }
2161}
2162
2163void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2164 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002165 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002166 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002167 RTC_LOG(LS_INFO)
2168 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2169 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002170 RtpTransceiverInit init;
2171 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002172 AddTransceiver(media_type, nullptr, init,
2173 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002174 }
2175}
2176
2177std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2178PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2179 std::vector<
2180 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2181 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002182 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002183 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002184 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2185 receiving_transceivers.push_back(transceiver);
2186 }
2187 }
2188 return receiving_transceivers;
2189}
2190
htaa2a49d92016-03-04 02:51:39 -08002191void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2192 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002193 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002194 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002195 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002196 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002197 return;
2198 }
2199
Steve Anton25ca0ac2019-06-25 10:40:48 -07002200 // If a session error has occurred the PeerConnection is in a possibly
2201 // inconsistent state so fail right away.
2202 if (session_error() != SessionError::kNone) {
2203 std::string error_message = GetSessionErrorMsg();
2204 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2205 PostCreateSessionDescriptionFailure(
2206 observer,
2207 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2208 return;
2209 }
2210
Steve Antondffead82018-02-06 10:31:29 -08002211 if (!(signaling_state_ == kHaveRemoteOffer ||
2212 signaling_state_ == kHaveLocalPrAnswer)) {
2213 std::string error =
2214 "PeerConnection cannot create an answer in a state other than "
2215 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002216 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002217 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002218 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002219 return;
2220 }
2221
Steve Antondffead82018-02-06 10:31:29 -08002222 // The remote description should be set if we're in the right state.
2223 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002224
Steve Anton22da89f2018-01-25 13:58:07 -08002225 if (IsUnifiedPlan()) {
2226 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2227 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2228 "supported with Unified Plan semantics. Use the "
2229 "RtpTransceiver API instead.";
2230 }
2231 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2232 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2233 "supported with Unified Plan semantics. Use the "
2234 "RtpTransceiver API instead.";
2235 }
2236 }
2237
htaa2a49d92016-03-04 02:51:39 -08002238 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002239 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002240
Steve Antond25da372017-11-06 14:50:29 -08002241 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242}
2243
2244void PeerConnection::SetLocalDescription(
2245 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002246 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002247 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002248 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002249
Steve Anton80dd7b52018-02-16 17:08:42 -08002250 // The SetLocalDescription contract is that we take ownership of the session
2251 // description regardless of the outcome, so wrap it in a unique_ptr right
2252 // away. Ideally, SetLocalDescription's signature will be changed to take the
2253 // description as a unique_ptr argument to formalize this agreement.
2254 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2255
nisse7ce109a2017-01-31 00:57:56 -08002256 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002257 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258 return;
2259 }
Steve Anton8a006912017-12-04 15:25:56 -08002260
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002261 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002262 PostSetSessionDescriptionFailure(
2263 observer,
2264 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002265 return;
2266 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002267
Steve Anton80dd7b52018-02-16 17:08:42 -08002268 // If a session error has occurred the PeerConnection is in a possibly
2269 // inconsistent state so fail right away.
2270 if (session_error() != SessionError::kNone) {
2271 std::string error_message = GetSessionErrorMsg();
2272 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002273 PostSetSessionDescriptionFailure(
2274 observer,
2275 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002276 return;
2277 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002278
Steve Anton80dd7b52018-02-16 17:08:42 -08002279 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2280 if (!error.ok()) {
2281 std::string error_message = GetSetDescriptionErrorMessage(
2282 cricket::CS_LOCAL, desc->GetType(), error);
2283 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002284 PostSetSessionDescriptionFailure(
2285 observer,
2286 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002287 return;
2288 }
2289
2290 // Grab the description type before moving ownership to ApplyLocalDescription,
2291 // which may destroy it before returning.
2292 const SdpType type = desc->GetType();
2293
2294 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002295 // |desc| may be destroyed at this point.
2296
2297 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002298 // If ApplyLocalDescription fails, the PeerConnection could be in an
2299 // inconsistent state, so act conservatively here and set the session error
2300 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2301 SetSessionError(SessionError::kContent, error.message());
2302 std::string error_message =
2303 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2304 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002305 PostSetSessionDescriptionFailure(
2306 observer,
2307 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002308 return;
2309 }
Steve Anton8a006912017-12-04 15:25:56 -08002310 RTC_DCHECK(local_description());
2311
2312 PostSetSessionDescriptionSuccess(observer);
2313
Steve Antonad182762018-09-05 20:22:40 +00002314 // MaybeStartGathering needs to be called after posting
2315 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2316 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002317 transport_controller_->MaybeStartGathering();
2318
Steve Antona3a92c22017-12-07 10:27:41 -08002319 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002320 // TODO(deadbeef): We already had to hop to the network thread for
2321 // MaybeStartGathering...
2322 network_thread()->Invoke<void>(
2323 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2324 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002325 // Make UMA notes about what was agreed to.
2326 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002327 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002328
2329 if (IsUnifiedPlan()) {
2330 bool was_negotiation_needed = is_negotiation_needed_;
2331 UpdateNegotiationNeeded();
2332 if (signaling_state() == kStable && was_negotiation_needed &&
2333 is_negotiation_needed_) {
2334 Observer()->OnRenegotiationNeeded();
2335 }
2336 }
2337
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002338 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002339}
2340
2341RTCError PeerConnection::ApplyLocalDescription(
2342 std::unique_ptr<SessionDescriptionInterface> desc) {
2343 RTC_DCHECK_RUN_ON(signaling_thread());
2344 RTC_DCHECK(desc);
2345
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 // Update stats here so that we have the most recent stats for tracks and
2347 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002348 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002349
Steve Antondcc3c022017-12-22 16:02:54 -08002350 // Take a reference to the old local description since it's used below to
2351 // compare against the new local description. When setting the new local
2352 // description, grab ownership of the replaced session description in case it
2353 // is the same as |old_local_description|, to keep it alive for the duration
2354 // of the method.
2355 const SessionDescriptionInterface* old_local_description =
2356 local_description();
2357 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002358 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002359 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002360 replaced_local_description = pending_local_description_
2361 ? std::move(pending_local_description_)
2362 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002363 current_local_description_ = std::move(desc);
2364 pending_local_description_ = nullptr;
2365 current_remote_description_ = std::move(pending_remote_description_);
2366 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002367 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002368 pending_local_description_ = std::move(desc);
2369 }
2370 // The session description to apply now must be accessed by
2371 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002372 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002373
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002374 // Report statistics about any use of simulcast.
2375 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2376 *local_description()->description());
2377
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002378 if (!is_caller_) {
2379 if (remote_description()) {
2380 // Remote description was applied first, so this PC is the callee.
2381 is_caller_ = false;
2382 } else {
2383 // Local description is applied first, so this PC is the caller.
2384 is_caller_ = true;
2385 }
2386 }
2387
Zhi Huange830e682018-03-30 10:48:35 -07002388 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2389 if (!error.ok()) {
2390 return error;
2391 }
2392
Steve Antondcc3c022017-12-22 16:02:54 -08002393 if (IsUnifiedPlan()) {
2394 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002395 cricket::CS_LOCAL, *local_description(), old_local_description,
2396 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002397 if (!error.ok()) {
2398 return error;
2399 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002400 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2401 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002402 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002403 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2404 // Note that code paths that don't set MID won't be able to use
2405 // information about DTLS transports.
2406 if (transceiver->mid()) {
2407 auto dtls_transport =
2408 LookupDtlsTransportByMidInternal(*transceiver->mid());
2409 transceiver->internal()->sender_internal()->set_transport(
2410 dtls_transport);
2411 transceiver->internal()->receiver_internal()->set_transport(
2412 dtls_transport);
2413 }
2414
Steve Antondcc3c022017-12-22 16:02:54 -08002415 const ContentInfo* content =
2416 FindMediaSectionForTransceiver(transceiver, local_description());
2417 if (!content) {
2418 continue;
2419 }
2420 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002421 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2422 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002423 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002424 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2425 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2426 // "recvonly", process the removal of a remote track for the media
2427 // description, given transceiver, removeList, and muteTracks.
2428 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2429 (transceiver->internal()->fired_direction() &&
2430 RtpTransceiverDirectionHasRecv(
2431 *transceiver->internal()->fired_direction()))) {
2432 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2433 &removed_streams);
2434 }
2435 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2436 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002437 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002438 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002439 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002440 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002441 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002442 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002443 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002444 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002445 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002446 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002447 }
2448 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002449 // Media channels will be created only when offer is set. These may use new
2450 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002451 if (type == SdpType::kOffer) {
2452 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2453 // description is applied. Restore back to old description.
2454 RTCError error = CreateChannels(*local_description()->description());
2455 if (!error.ok()) {
2456 return error;
2457 }
2458 }
Steve Antondcc3c022017-12-22 16:02:54 -08002459 // Remove unused channels if MediaContentDescription is rejected.
2460 RemoveUnusedChannels(local_description()->description());
2461 }
Steve Anton8a006912017-12-04 15:25:56 -08002462
Zhi Huange830e682018-03-30 10:48:35 -07002463 error = UpdateSessionState(type, cricket::CS_LOCAL,
2464 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002465 if (!error.ok()) {
2466 return error;
2467 }
Steve Antondcc3c022017-12-22 16:02:54 -08002468
Steve Anton8a006912017-12-04 15:25:56 -08002469 if (remote_description()) {
2470 // Now that we have a local description, we can push down remote candidates.
2471 UseCandidatesInSessionDescription(remote_description());
2472 }
2473
2474 pending_ice_restarts_.clear();
2475 if (session_error() != SessionError::kNone) {
2476 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2477 }
2478
deadbeefab9b2d12015-10-14 11:33:11 -07002479 // If setting the description decided our SSL role, allocate any necessary
2480 // SCTP sids.
2481 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002482 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002483 AllocateSctpSids(role);
2484 }
2485
Steve Antond3679212018-01-17 17:41:02 -08002486 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002487 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002488 const ContentInfo* content =
2489 FindMediaSectionForTransceiver(transceiver, local_description());
2490 if (!content) {
2491 continue;
2492 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002493 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2494 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002495 // 0 is a special value meaning "this sender has no associated send
2496 // stream". Need to call this so the sender won't attempt to configure
2497 // a no longer existing stream and run into DCHECKs in the lower
2498 // layers.
2499 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002500 } else {
2501 // Get the StreamParams from the channel which could generate SSRCs.
2502 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002503 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002504 streams[0].stream_ids());
2505 transceiver->internal()->sender_internal()->SetSsrc(
2506 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002507 }
2508 }
2509 } else {
2510 // Plan B semantics.
2511
Steve Antondcc3c022017-12-22 16:02:54 -08002512 // Update state and SSRC of local MediaStreams and DataChannels based on the
2513 // local session description.
2514 const cricket::ContentInfo* audio_content =
2515 GetFirstAudioContent(local_description()->description());
2516 if (audio_content) {
2517 if (audio_content->rejected) {
2518 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2519 } else {
2520 const cricket::AudioContentDescription* audio_desc =
2521 audio_content->media_description()->as_audio();
2522 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2523 }
deadbeeffaac4972015-11-12 15:33:07 -08002524 }
deadbeefab9b2d12015-10-14 11:33:11 -07002525
Steve Antondcc3c022017-12-22 16:02:54 -08002526 const cricket::ContentInfo* video_content =
2527 GetFirstVideoContent(local_description()->description());
2528 if (video_content) {
2529 if (video_content->rejected) {
2530 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2531 } else {
2532 const cricket::VideoContentDescription* video_desc =
2533 video_content->media_description()->as_video();
2534 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2535 }
deadbeeffaac4972015-11-12 15:33:07 -08002536 }
deadbeefab9b2d12015-10-14 11:33:11 -07002537 }
2538
2539 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002540 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002541 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002542 const cricket::RtpDataContentDescription* rtp_data_desc =
2543 data_content->media_description()->as_rtp_data();
2544 // rtp_data_desc will be null if this is an SCTP description.
2545 if (rtp_data_desc) {
2546 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002547 }
2548 }
2549
Henrik Boström79b69802019-07-18 11:16:56 +02002550 if (type == SdpType::kAnswer &&
2551 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2552 *current_local_description_)) {
2553 local_ice_credentials_to_replace_->ClearIceCredentials();
2554 }
2555
Steve Anton8a006912017-12-04 15:25:56 -08002556 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002557}
2558
Steve Anton06817cd2018-12-18 15:55:30 -08002559// The SDP parser used to populate these values by default for the 'content
2560// name' if an a=mid line was absent.
2561static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2562 switch (media_type) {
2563 case cricket::MEDIA_TYPE_AUDIO:
2564 return cricket::CN_AUDIO;
2565 case cricket::MEDIA_TYPE_VIDEO:
2566 return cricket::CN_VIDEO;
2567 case cricket::MEDIA_TYPE_DATA:
2568 return cricket::CN_DATA;
2569 }
2570 RTC_NOTREACHED();
2571 return "";
2572}
2573
2574void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002575 cricket::SessionDescription* new_remote_description) {
2576 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002577 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002578 const cricket::ContentInfos& local_contents =
2579 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002580 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002581 const cricket::ContentInfos& remote_contents =
2582 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002583 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002584 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2585 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002586 if (!content.name.empty()) {
2587 continue;
2588 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002589 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002590 absl::string_view source_explanation;
2591 if (IsUnifiedPlan()) {
2592 if (i < local_contents.size()) {
2593 new_mid = local_contents[i].name;
2594 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002595 } else if (i < remote_contents.size()) {
2596 new_mid = remote_contents[i].name;
2597 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002598 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002599 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002600 source_explanation = "generated just now";
2601 }
2602 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002603 new_mid = std::string(
2604 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002605 source_explanation = "to match pre-existing behavior";
2606 }
Steve Antond7180cc2019-02-07 10:44:53 -08002607 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002608 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002609 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002610 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2611 << " is missing an a=mid line. Filling in the value '"
2612 << new_mid << "' " << source_explanation << ".";
2613 }
2614}
2615
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002617 SetSessionDescriptionObserver* observer,
2618 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002619 SetRemoteDescription(
2620 std::unique_ptr<SessionDescriptionInterface>(desc),
2621 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2622 new SetRemoteDescriptionObserverAdapter(this, observer)));
2623}
2624
2625void PeerConnection::SetRemoteDescription(
2626 std::unique_ptr<SessionDescriptionInterface> desc,
2627 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002628 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002629 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002630
nisse7ce109a2017-01-31 00:57:56 -08002631 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002632 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002633 return;
2634 }
Steve Anton8a006912017-12-04 15:25:56 -08002635
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002637 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002638 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002639 return;
2640 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002641
Steve Anton80dd7b52018-02-16 17:08:42 -08002642 // If a session error has occurred the PeerConnection is in a possibly
2643 // inconsistent state so fail right away.
2644 if (session_error() != SessionError::kNone) {
2645 std::string error_message = GetSessionErrorMsg();
2646 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2647 observer->OnSetRemoteDescriptionComplete(
2648 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2649 return;
2650 }
Steve Anton71439a62018-02-15 11:53:06 -08002651
Steve Antonba42e992018-04-09 14:10:01 -07002652 if (desc->GetType() == SdpType::kOffer) {
2653 // Report to UMA the format of the received offer.
2654 ReportSdpFormatReceived(*desc);
2655 }
2656
Steve Anton06817cd2018-12-18 15:55:30 -08002657 // Handle remote descriptions missing a=mid lines for interop with legacy end
2658 // points.
2659 FillInMissingRemoteMids(desc->description());
2660
Steve Anton80dd7b52018-02-16 17:08:42 -08002661 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002662 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002663 std::string error_message = GetSetDescriptionErrorMessage(
2664 cricket::CS_REMOTE, desc->GetType(), error);
2665 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002666 observer->OnSetRemoteDescriptionComplete(
2667 RTCError(error.type(), std::move(error_message)));
2668 return;
2669 }
Steve Anton71439a62018-02-15 11:53:06 -08002670
Steve Anton80dd7b52018-02-16 17:08:42 -08002671 // Grab the description type before moving ownership to
2672 // ApplyRemoteDescription, which may destroy it before returning.
2673 const SdpType type = desc->GetType();
2674
2675 error = ApplyRemoteDescription(std::move(desc));
2676 // |desc| may be destroyed at this point.
2677
2678 if (!error.ok()) {
2679 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2680 // inconsistent state, so act conservatively here and set the session error
2681 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2682 SetSessionError(SessionError::kContent, error.message());
2683 std::string error_message =
2684 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2685 RTC_LOG(LS_ERROR) << error_message;
2686 observer->OnSetRemoteDescriptionComplete(
2687 RTCError(error.type(), std::move(error_message)));
2688 return;
2689 }
2690 RTC_DCHECK(remote_description());
2691
2692 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002693 // TODO(deadbeef): We already had to hop to the network thread for
2694 // MaybeStartGathering...
2695 network_thread()->Invoke<void>(
2696 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2697 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002698 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002699 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002700 }
2701
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002702 if (IsUnifiedPlan()) {
2703 bool was_negotiation_needed = is_negotiation_needed_;
2704 UpdateNegotiationNeeded();
2705 if (signaling_state() == kStable && was_negotiation_needed &&
2706 is_negotiation_needed_) {
2707 Observer()->OnRenegotiationNeeded();
2708 }
2709 }
2710
Steve Anton8a006912017-12-04 15:25:56 -08002711 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002712 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002713}
2714
2715RTCError PeerConnection::ApplyRemoteDescription(
2716 std::unique_ptr<SessionDescriptionInterface> desc) {
2717 RTC_DCHECK_RUN_ON(signaling_thread());
2718 RTC_DCHECK(desc);
2719
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002720 // Update stats here so that we have the most recent stats for tracks and
2721 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002722 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002723
Steve Antondcc3c022017-12-22 16:02:54 -08002724 // Take a reference to the old remote description since it's used below to
2725 // compare against the new remote description. When setting the new remote
2726 // description, grab ownership of the replaced session description in case it
2727 // is the same as |old_remote_description|, to keep it alive for the duration
2728 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002729 const SessionDescriptionInterface* old_remote_description =
2730 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002731 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002732 SdpType type = desc->GetType();
2733 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002734 replaced_remote_description = pending_remote_description_
2735 ? std::move(pending_remote_description_)
2736 : std::move(current_remote_description_);
2737 current_remote_description_ = std::move(desc);
2738 pending_remote_description_ = nullptr;
2739 current_local_description_ = std::move(pending_local_description_);
2740 } else {
2741 replaced_remote_description = std::move(pending_remote_description_);
2742 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002743 }
Steve Anton8a006912017-12-04 15:25:56 -08002744 // The session description to apply now must be accessed by
2745 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002746 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002748 // Report statistics about any use of simulcast.
2749 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2750 *remote_description()->description());
2751
Zhi Huange830e682018-03-30 10:48:35 -07002752 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2753 if (!error.ok()) {
2754 return error;
2755 }
Steve Anton8a006912017-12-04 15:25:56 -08002756 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002757 if (IsUnifiedPlan()) {
2758 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002759 cricket::CS_REMOTE, *remote_description(), local_description(),
2760 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002761 if (!error.ok()) {
2762 return error;
2763 }
Steve Antondcc3c022017-12-22 16:02:54 -08002764 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002765 // Media channels will be created only when offer is set. These may use new
2766 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002767 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002768 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002769 // description is applied. Restore back to old description.
2770 RTCError error = CreateChannels(*remote_description()->description());
2771 if (!error.ok()) {
2772 return error;
2773 }
2774 }
Steve Antondcc3c022017-12-22 16:02:54 -08002775 // Remove unused channels if MediaContentDescription is rejected.
2776 RemoveUnusedChannels(remote_description()->description());
2777 }
Steve Anton8a006912017-12-04 15:25:56 -08002778
Zhi Huange830e682018-03-30 10:48:35 -07002779 // NOTE: Candidates allocation will be initiated only when
2780 // SetLocalDescription is called.
2781 error = UpdateSessionState(type, cricket::CS_REMOTE,
2782 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002783 if (!error.ok()) {
2784 return error;
2785 }
2786
2787 if (local_description() &&
2788 !UseCandidatesInSessionDescription(remote_description())) {
2789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2790 }
2791
2792 if (old_remote_description) {
2793 for (const cricket::ContentInfo& content :
2794 old_remote_description->description()->contents()) {
2795 // Check if this new SessionDescription contains new ICE ufrag and
2796 // password that indicates the remote peer requests an ICE restart.
2797 // TODO(deadbeef): When we start storing both the current and pending
2798 // remote description, this should reset pending_ice_restarts and compare
2799 // against the current description.
2800 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2801 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002802 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002803 pending_ice_restarts_.insert(content.name);
2804 }
2805 } else {
2806 // We retain all received candidates only if ICE is not restarted.
2807 // When ICE is restarted, all previous candidates belong to an old
2808 // generation and should not be kept.
2809 // TODO(deadbeef): This goes against the W3C spec which says the remote
2810 // description should only contain candidates from the last set remote
2811 // description plus any candidates added since then. We should remove
2812 // this once we're sure it won't break anything.
2813 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2814 old_remote_description, content.name, mutable_remote_description());
2815 }
2816 }
2817 }
2818
2819 if (session_error() != SessionError::kNone) {
2820 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2821 }
2822
2823 // Set the the ICE connection state to connecting since the connection may
2824 // become writable with peer reflexive candidates before any remote candidate
2825 // is signaled.
2826 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2827 // is to have a new signal the indicates a change in checking state from the
2828 // transport and expose a new checking() member from transport that can be
2829 // read to determine the current checking state. The existing SignalConnecting
2830 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002831 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002832 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002833 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2834 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2835 }
2836
deadbeefab9b2d12015-10-14 11:33:11 -07002837 // If setting the description decided our SSL role, allocate any necessary
2838 // SCTP sids.
2839 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002840 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002841 AllocateSctpSids(role);
2842 }
2843
Steve Antondcc3c022017-12-22 16:02:54 -08002844 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002845 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002846 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002847 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002848 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002849 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002850 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002851 const ContentInfo* content =
2852 FindMediaSectionForTransceiver(transceiver, remote_description());
2853 if (!content) {
2854 continue;
2855 }
2856 const MediaContentDescription* media_desc = content->media_description();
2857 RtpTransceiverDirection local_direction =
2858 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002859 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2860 // RTCSessionDescription: Set the associated remote streams given
2861 // transceiver.[[Receiver]], msids, addList, and removeList".
2862 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2863 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2864 std::vector<std::string> stream_ids;
2865 if (!media_desc->streams().empty()) {
2866 // The remote description has signaled the stream IDs.
2867 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002868 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002869 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2870 << " (" << GetStreamIdsString(stream_ids) << ").";
2871 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2872 stream_ids, &added_streams,
2873 &removed_streams);
2874 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2875 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2876 // and transceiver's current direction is neither sendrecv nor recvonly,
2877 // process the addition of a remote track for the media description.
2878 if (!transceiver->fired_direction() ||
2879 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2880 RTC_LOG(LS_INFO)
2881 << "Processing the addition of a remote track for MID="
2882 << content->name << ".";
2883 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002884 }
Steve Antondcc3c022017-12-22 16:02:54 -08002885 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002886 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002887 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2888 // removal of a remote track for the media description, given transceiver,
2889 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002890 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002891 (transceiver->fired_direction() &&
2892 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2893 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2894 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002895 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002896 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002897 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002898 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002899 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002900 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002901 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002902 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002903 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002904 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2905 if (transceiver->mid()) {
2906 auto dtls_transport =
2907 LookupDtlsTransportByMidInternal(*transceiver->mid());
2908 transceiver->internal()->sender_internal()->set_transport(
2909 dtls_transport);
2910 transceiver->internal()->receiver_internal()->set_transport(
2911 dtls_transport);
2912 }
Steve Antondcc3c022017-12-22 16:02:54 -08002913 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002914 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002915 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002916 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002917 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2918 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002919 transceiver->Stop();
2920 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002921 if (!content->rejected &&
2922 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002923 if (!media_desc->streams().empty() &&
2924 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07002925 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
2926 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
2927 } else {
2928 transceiver->internal()
2929 ->receiver_internal()
2930 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002931 }
Steve Antond3679212018-01-17 17:41:02 -08002932 }
Steve Antondcc3c022017-12-22 16:02:54 -08002933 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002934 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002935 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002936 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002937 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002938 observer->OnTrack(transceiver);
2939 observer->OnAddTrack(transceiver->receiver(),
2940 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002941 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002942 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002943 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002944 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002945 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002946 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002947 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002948 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002949 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002950 }
Steve Antondcc3c022017-12-22 16:02:54 -08002951 }
2952
Henrik Boströmfdb92012017-11-09 19:55:44 +01002953 const cricket::ContentInfo* audio_content =
2954 GetFirstAudioContent(remote_description()->description());
2955 const cricket::ContentInfo* video_content =
2956 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002957 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002958 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002959 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002960 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002961 const cricket::RtpDataContentDescription* rtp_data_desc =
2962 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002963
2964 // Check if the descriptions include streams, just in case the peer supports
2965 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002966 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002967 (audio_desc && !audio_desc->streams().empty()) ||
2968 (video_desc && !video_desc->streams().empty())) {
2969 remote_peer_supports_msid_ = true;
2970 }
deadbeefab9b2d12015-10-14 11:33:11 -07002971
2972 // We wait to signal new streams until we finish processing the description,
2973 // since only at that point will new streams have all their tracks.
2974 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2975
Steve Antondcc3c022017-12-22 16:02:54 -08002976 if (!IsUnifiedPlan()) {
2977 // TODO(steveanton): When removing RTP senders/receivers in response to a
2978 // rejected media section, there is some cleanup logic that expects the
2979 // voice/ video channel to still be set. But in this method the voice/video
2980 // channel would have been destroyed by the SetRemoteDescription caller
2981 // above so the cleanup that relies on them fails to run. The RemoveSenders
2982 // calls should be moved to right before the DestroyChannel calls to fix
2983 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002984
Steve Antondcc3c022017-12-22 16:02:54 -08002985 // Find all audio rtp streams and create corresponding remote AudioTracks
2986 // and MediaStreams.
2987 if (audio_content) {
2988 if (audio_content->rejected) {
2989 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2990 } else {
2991 bool default_audio_track_needed =
2992 !remote_peer_supports_msid_ &&
2993 RtpTransceiverDirectionHasSend(audio_desc->direction());
2994 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2995 default_audio_track_needed, audio_desc->type(),
2996 new_streams);
2997 }
deadbeeffaac4972015-11-12 15:33:07 -08002998 }
deadbeefab9b2d12015-10-14 11:33:11 -07002999
Steve Antondcc3c022017-12-22 16:02:54 -08003000 // Find all video rtp streams and create corresponding remote VideoTracks
3001 // and MediaStreams.
3002 if (video_content) {
3003 if (video_content->rejected) {
3004 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3005 } else {
3006 bool default_video_track_needed =
3007 !remote_peer_supports_msid_ &&
3008 RtpTransceiverDirectionHasSend(video_desc->direction());
3009 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3010 default_video_track_needed, video_desc->type(),
3011 new_streams);
3012 }
deadbeeffaac4972015-11-12 15:33:07 -08003013 }
deadbeefab9b2d12015-10-14 11:33:11 -07003014
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003015 // If this is an RTP data transport, update the DataChannels with the
3016 // information from the remote peer.
3017 if (rtp_data_desc) {
3018 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003019 }
deadbeefab9b2d12015-10-14 11:33:11 -07003020
Steve Antondcc3c022017-12-22 16:02:54 -08003021 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003022 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003023 for (size_t i = 0; i < new_streams->count(); ++i) {
3024 MediaStreamInterface* new_stream = new_streams->at(i);
3025 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003026 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003027 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3028 }
deadbeefab9b2d12015-10-14 11:33:11 -07003029
Steve Antondcc3c022017-12-22 16:02:54 -08003030 UpdateEndedRemoteMediaStreams();
3031 }
deadbeefab9b2d12015-10-14 11:33:11 -07003032
Henrik Boström79b69802019-07-18 11:16:56 +02003033 if (type == SdpType::kAnswer &&
3034 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3035 *current_local_description_)) {
3036 local_ice_credentials_to_replace_->ClearIceCredentials();
3037 }
3038
Steve Anton8a006912017-12-04 15:25:56 -08003039 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003040}
3041
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003042void PeerConnection::SetAssociatedRemoteStreams(
3043 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3044 const std::vector<std::string>& stream_ids,
3045 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3046 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3047 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3048 for (const std::string& stream_id : stream_ids) {
3049 rtc::scoped_refptr<MediaStreamInterface> stream =
3050 remote_streams_->find(stream_id);
3051 if (!stream) {
3052 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3053 MediaStream::Create(stream_id));
3054 remote_streams_->AddStream(stream);
3055 added_streams->push_back(stream);
3056 }
3057 media_streams.push_back(stream);
3058 }
3059 // Special case: "a=msid" missing, use random stream ID.
3060 if (media_streams.empty() &&
3061 !(remote_description()->description()->msid_signaling() &
3062 cricket::kMsidSignalingMediaSection)) {
3063 if (!missing_msid_default_stream_) {
3064 missing_msid_default_stream_ = MediaStreamProxy::Create(
3065 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3066 added_streams->push_back(missing_msid_default_stream_);
3067 }
3068 media_streams.push_back(missing_msid_default_stream_);
3069 }
3070 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3071 receiver->streams();
3072 // SetStreams() will add/remove the receiver's track to/from the streams. This
3073 // differs from the spec - the spec uses an "addList" and "removeList" to
3074 // update the stream-track relationships in a later step. We do this earlier,
3075 // changing the order of things, but the end-result is the same.
3076 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3077 // instead. https://crbug.com/webrtc/9480
3078 receiver->SetStreams(media_streams);
3079 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3080}
3081
Steve Anton0f5400a2018-07-17 14:25:36 -07003082void PeerConnection::ProcessRemovalOfRemoteTrack(
3083 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3084 transceiver,
3085 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3086 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3087 RTC_DCHECK(transceiver->mid());
3088 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3089 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003090 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003091 transceiver->internal()->receiver_internal()->streams();
3092 // This will remove the remote track from the streams.
3093 transceiver->internal()->receiver_internal()->set_stream_ids({});
3094 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003095 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3096}
3097
3098void PeerConnection::RemoveRemoteStreamsIfEmpty(
3099 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3100 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3101 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3102 // streams, see if the stream was removed by checking if this was the last
3103 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003104 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003105 if (remote_stream->GetAudioTracks().empty() &&
3106 remote_stream->GetVideoTracks().empty()) {
3107 remote_streams_->RemoveStream(remote_stream);
3108 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003109 }
3110 }
3111}
3112
Steve Antondcc3c022017-12-22 16:02:54 -08003113RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3114 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003115 const SessionDescriptionInterface& new_session,
3116 const SessionDescriptionInterface* old_local_description,
3117 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003118 RTC_DCHECK(IsUnifiedPlan());
3119
Steve Anton7464fca2018-01-19 11:10:37 -08003120 const cricket::ContentGroup* bundle_group = nullptr;
3121 if (new_session.GetType() == SdpType::kOffer) {
3122 auto bundle_group_or_error =
3123 GetEarlyBundleGroup(*new_session.description());
3124 if (!bundle_group_or_error.ok()) {
3125 return bundle_group_or_error.MoveError();
3126 }
3127 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003128 }
Steve Antondcc3c022017-12-22 16:02:54 -08003129
Steve Antondcc3c022017-12-22 16:02:54 -08003130 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003131 for (size_t i = 0; i < new_contents.size(); ++i) {
3132 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003133 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003134 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003135 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3136 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003137 const cricket::ContentInfo* old_local_content = nullptr;
3138 if (old_local_description &&
3139 i < old_local_description->description()->contents().size()) {
3140 old_local_content =
3141 &old_local_description->description()->contents()[i];
3142 }
3143 const cricket::ContentInfo* old_remote_content = nullptr;
3144 if (old_remote_description &&
3145 i < old_remote_description->description()->contents().size()) {
3146 old_remote_content =
3147 &old_remote_description->description()->contents()[i];
3148 }
Steve Antondcc3c022017-12-22 16:02:54 -08003149 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003150 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3151 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003152 if (!transceiver_or_error.ok()) {
3153 return transceiver_or_error.MoveError();
3154 }
3155 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003156 RTCError error =
3157 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3158 if (!error.ok()) {
3159 return error;
3160 }
3161 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003162 if (GetDataMid() && new_content.name != *GetDataMid()) {
3163 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003164 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3165 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003166 continue;
3167 }
3168 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3169 if (!error.ok()) {
3170 return error;
3171 }
Steve Antondcc3c022017-12-22 16:02:54 -08003172 } else {
3173 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3174 "Unknown section type.");
3175 }
3176 }
3177
3178 return RTCError::OK();
3179}
3180
3181RTCError PeerConnection::UpdateTransceiverChannel(
3182 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3183 transceiver,
3184 const cricket::ContentInfo& content,
3185 const cricket::ContentGroup* bundle_group) {
3186 RTC_DCHECK(IsUnifiedPlan());
3187 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003188 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003189 if (content.rejected) {
3190 if (channel) {
3191 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003192 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003193 }
3194 } else {
3195 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003196 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003197 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003198 } else {
Steve Anton69470252018-02-09 11:43:08 -08003199 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003200 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003201 }
3202 if (!channel) {
3203 LOG_AND_RETURN_ERROR(
3204 RTCErrorType::INTERNAL_ERROR,
3205 "Failed to create channel for mid=" + content.name);
3206 }
3207 transceiver->internal()->SetChannel(channel);
3208 }
3209 }
3210 return RTCError::OK();
3211}
3212
Steve Antonfa2260d2017-12-28 16:38:23 -08003213RTCError PeerConnection::UpdateDataChannel(
3214 cricket::ContentSource source,
3215 const cricket::ContentInfo& content,
3216 const cricket::ContentGroup* bundle_group) {
3217 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003218 // If data channels are disabled, ignore this media section. CreateAnswer
3219 // will take care of rejecting it.
3220 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003221 }
3222 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003223 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003224 DestroyDataChannel();
3225 } else {
Qingsi Wang437077d2019-09-10 17:52:26 +00003226 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003227 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003228 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003229 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3230 "Failed to create data channel.");
3231 }
3232 }
3233 if (source == cricket::CS_REMOTE) {
3234 const MediaContentDescription* data_desc = content.media_description();
3235 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3236 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3237 }
3238 }
3239 }
3240 return RTCError::OK();
3241}
3242
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003243// This method will extract any send encodings that were sent by the remote
3244// connection. This is currently only relevant for Simulcast scenario (where
3245// the number of layers may be communicated by the server).
3246static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3247 const MediaContentDescription& desc) {
3248 if (!desc.HasSimulcast()) {
3249 return {};
3250 }
3251 std::vector<RtpEncodingParameters> result;
3252 const SimulcastDescription& simulcast = desc.simulcast_description();
3253
3254 // This is a remote description, the parameters we are after should appear
3255 // as receive streams.
3256 for (const auto& alternatives : simulcast.receive_layers()) {
3257 RTC_DCHECK(!alternatives.empty());
3258 // There is currently no way to specify or choose from alternatives.
3259 // We will always use the first alternative, which is the most preferred.
3260 const SimulcastLayer& layer = alternatives[0];
3261 RtpEncodingParameters parameters;
3262 parameters.rid = layer.rid;
3263 parameters.active = !layer.is_paused;
3264 result.push_back(parameters);
3265 }
3266
3267 return result;
3268}
3269
3270static RTCError UpdateSimulcastLayerStatusInSender(
3271 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003272 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003273 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003274 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003275 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003276
3277 // The simulcast envelope cannot be changed, only the status of the streams.
3278 // So we will iterate over the send encodings rather than the layers.
3279 for (RtpEncodingParameters& encoding : parameters.encodings) {
3280 auto iter = std::find_if(layers.begin(), layers.end(),
3281 [&encoding](const SimulcastLayer& layer) {
3282 return layer.rid == encoding.rid;
3283 });
3284 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003285 if (iter == layers.end()) {
3286 disabled_layers.push_back(encoding.rid);
3287 continue;
3288 }
3289
3290 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003291 }
3292
Amit Hilbuch619b2942019-02-26 15:55:19 -08003293 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003294 if (result.ok()) {
3295 result = sender->DisableEncodingLayers(disabled_layers);
3296 }
3297
3298 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003299}
3300
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003301static bool SimulcastIsRejected(
3302 const ContentInfo* local_content,
3303 const MediaContentDescription& answer_media_desc) {
3304 bool simulcast_offered = local_content &&
3305 local_content->media_description() &&
3306 local_content->media_description()->HasSimulcast();
3307 bool simulcast_answered = answer_media_desc.HasSimulcast();
3308 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3309 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3310 return simulcast_offered && (!simulcast_answered || !rids_supported);
3311}
3312
Amit Hilbuch2297d332019-02-19 12:49:22 -08003313static RTCError DisableSimulcastInSender(
3314 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003315 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003316 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003317 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003318 return RTCError::OK();
3319 }
3320
Amit Hilbuch2297d332019-02-19 12:49:22 -08003321 std::vector<std::string> disabled_layers;
3322 std::transform(
3323 parameters.encodings.begin() + 1, parameters.encodings.end(),
3324 std::back_inserter(disabled_layers),
3325 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3326 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003327}
3328
Steve Antondcc3c022017-12-22 16:02:54 -08003329RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3330PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003331 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003332 size_t mline_index,
3333 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003334 const ContentInfo* old_local_content,
3335 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003336 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003337 // If this is an offer then the m= section might be recycled. If the m=
3338 // section is being recycled (defined as: rejected in the current local or
3339 // remote description and not rejected in new description), dissociate the
3340 // currently associated RtpTransceiver by setting its mid property to null,
3341 // and discard the mapping between the transceiver and its m= section index.
3342 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3343 old_remote_content)) {
3344 // We want to dissociate the transceiver that has the rejected mid.
3345 const std::string& old_mid =
3346 (old_local_content && old_local_content->rejected)
3347 ? old_local_content->name
3348 : old_remote_content->name;
3349 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003350 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003351 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3352 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003353 old_transceiver->internal()->set_mid(absl::nullopt);
3354 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003355 }
3356 }
3357 const MediaContentDescription* media_desc = content.media_description();
3358 auto transceiver = GetAssociatedTransceiver(content.name);
3359 if (source == cricket::CS_LOCAL) {
3360 // Find the RtpTransceiver that corresponds to this m= section, using the
3361 // mapping between transceivers and m= section indices established when
3362 // creating the offer.
3363 if (!transceiver) {
3364 transceiver = GetTransceiverByMLineIndex(mline_index);
3365 }
3366 if (!transceiver) {
3367 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3368 "Unknown transceiver");
3369 }
3370 } else {
3371 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3372 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3373 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003374 // When simulcast is requested, a transceiver cannot be associated because
3375 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003376 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003377 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3378 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003379 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3380 }
3381 // If no RtpTransceiver was found in the previous step, create one with a
3382 // recvonly direction.
3383 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003384 RTC_LOG(LS_INFO) << "Adding "
3385 << cricket::MediaTypeToString(media_desc->type())
3386 << " transceiver for MID=" << content.name
3387 << " at i=" << mline_index
3388 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003389 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003390 std::vector<RtpEncodingParameters> send_encodings =
3391 GetSendEncodingsFromRemoteDescription(*media_desc);
3392 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3393 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003394 std::string receiver_id;
3395 if (!media_desc->streams().empty()) {
3396 receiver_id = media_desc->streams()[0].id;
3397 } else {
3398 receiver_id = rtc::CreateRandomUuid();
3399 }
3400 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003401 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003402 transceiver->internal()->set_direction(
3403 RtpTransceiverDirection::kRecvOnly);
3404 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003405
3406 // Check if the offer indicated simulcast but the answer rejected it.
3407 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003408 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003409 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003410 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003411 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003412 if (!error.ok()) {
3413 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3414 return std::move(error);
3415 }
3416 }
Steve Antondcc3c022017-12-22 16:02:54 -08003417 }
3418 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003419 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003420 LOG_AND_RETURN_ERROR(
3421 RTCErrorType::INVALID_PARAMETER,
3422 "Transceiver type does not match media description type.");
3423 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003424 if (media_desc->HasSimulcast()) {
3425 std::vector<SimulcastLayer> layers =
3426 source == cricket::CS_LOCAL
3427 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3428 : media_desc->simulcast_description()
3429 .receive_layers()
3430 .GetAllLayers();
3431 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003432 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003433 if (!error.ok()) {
3434 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3435 return std::move(error);
3436 }
3437 }
Steve Antondcc3c022017-12-22 16:02:54 -08003438 // Associate the found or created RtpTransceiver with the m= section by
3439 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3440 // section, and establish a mapping between the transceiver and the index of
3441 // the m= section.
3442 transceiver->internal()->set_mid(content.name);
3443 transceiver->internal()->set_mline_index(mline_index);
3444 return std::move(transceiver);
3445}
3446
3447rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3448PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3449 RTC_DCHECK(IsUnifiedPlan());
3450 for (auto transceiver : transceivers_) {
3451 if (transceiver->mid() == mid) {
3452 return transceiver;
3453 }
3454 }
3455 return nullptr;
3456}
3457
3458rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3459PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3460 RTC_DCHECK(IsUnifiedPlan());
3461 for (auto transceiver : transceivers_) {
3462 if (transceiver->internal()->mline_index() == mline_index) {
3463 return transceiver;
3464 }
3465 }
3466 return nullptr;
3467}
3468
3469rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3470PeerConnection::FindAvailableTransceiverToReceive(
3471 cricket::MediaType media_type) const {
3472 RTC_DCHECK(IsUnifiedPlan());
3473 // From JSEP section 5.10 (Applying a Remote Description):
3474 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3475 // the same type that were added to the PeerConnection by addTrack and are not
3476 // associated with any m= section and are not stopped, find the first such
3477 // RtpTransceiver.
3478 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003479 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003480 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3481 !transceiver->stopped()) {
3482 return transceiver;
3483 }
3484 }
3485 return nullptr;
3486}
3487
Steve Antoned10bd92017-12-05 10:52:59 -08003488const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3489 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3490 transceiver,
3491 const SessionDescriptionInterface* sdesc) const {
3492 RTC_DCHECK(transceiver);
3493 RTC_DCHECK(sdesc);
3494 if (IsUnifiedPlan()) {
3495 if (!transceiver->internal()->mid()) {
3496 // This transceiver is not associated with a media section yet.
3497 return nullptr;
3498 }
3499 return sdesc->description()->GetContentByName(
3500 *transceiver->internal()->mid());
3501 } else {
3502 // Plan B only allows at most one audio and one video section, so use the
3503 // first media section of that type.
3504 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003505 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003506 }
3507}
3508
deadbeef46c73892016-11-16 19:42:04 -08003509PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003510 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003511 return configuration_;
3512}
3513
Niels Möller2579f0c2019-08-19 09:58:17 +02003514RTCError PeerConnection::SetConfiguration(
3515 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003516 RTC_DCHECK_RUN_ON(signaling_thread());
3517 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003518 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003519 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003520 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3521 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003522 }
3523
Qingsi Wanga2d60672018-04-11 16:57:45 -07003524 // According to JSEP, after setLocalDescription, changing the candidate pool
3525 // size is not allowed, and changing the set of ICE servers will not result
3526 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003527 if (local_description() && configuration.ice_candidate_pool_size !=
3528 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003529 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3530 "Can't change candidate pool size after calling "
3531 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003532 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003533
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003534 if (local_description() &&
3535 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003536 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3537 "Can't change media_transport after calling "
3538 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003539 }
3540
3541 if (remote_description() &&
3542 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003543 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3544 "Can't change media_transport after calling "
3545 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003546 }
3547
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003548 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003549 configuration.use_media_transport_for_data_channels !=
3550 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003551 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3552 "Can't change media_transport_for_data_channels "
3553 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003554 }
3555
3556 if (remote_description() &&
3557 configuration.use_media_transport_for_data_channels !=
3558 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3560 "Can't change media_transport_for_data_channels "
3561 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003562 }
3563
3564 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003565 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003566 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3567 "Can't change crypto_options after calling "
3568 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003569 }
3570
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003571 if (local_description() && configuration.use_datagram_transport !=
3572 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003573 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3574 "Can't change use_datagram_transport "
3575 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003576 }
3577
3578 if (remote_description() && configuration.use_datagram_transport !=
3579 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003580 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3581 "Can't change use_datagram_transport "
3582 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003583 }
3584
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003585 if (local_description() &&
3586 configuration.use_datagram_transport_for_data_channels !=
3587 configuration_.use_datagram_transport_for_data_channels) {
3588 LOG_AND_RETURN_ERROR(
3589 RTCErrorType::INVALID_MODIFICATION,
3590 "Can't change use_datagram_transport_for_data_channels "
3591 "after calling SetLocalDescription.");
3592 }
3593
3594 if (remote_description() &&
3595 configuration.use_datagram_transport_for_data_channels !=
3596 configuration_.use_datagram_transport_for_data_channels) {
3597 LOG_AND_RETURN_ERROR(
3598 RTCErrorType::INVALID_MODIFICATION,
3599 "Can't change use_datagram_transport_for_data_channels "
3600 "after calling SetRemoteDescription.");
3601 }
3602
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003603 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003604 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003605 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003606 *configuration.use_datagram_transport) ||
3607 (configuration.use_datagram_transport_for_data_channels &&
3608 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003609 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3610 << "Media transport requires MaxBundle policy.";
3611 }
3612
deadbeef293e9262017-01-11 12:28:30 -08003613 // The simplest (and most future-compatible) way to tell if the config was
3614 // modified in an invalid way is to copy each property we do support
3615 // modifying, then use operator==. There are far more properties we don't
3616 // support modifying than those we do, and more could be added.
3617 RTCConfiguration modified_config = configuration_;
3618 modified_config.servers = configuration.servers;
3619 modified_config.type = configuration.type;
3620 modified_config.ice_candidate_pool_size =
3621 configuration.ice_candidate_pool_size;
3622 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003623 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3624 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003625 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003626 modified_config.ice_check_interval_strong_connectivity =
3627 configuration.ice_check_interval_strong_connectivity;
3628 modified_config.ice_check_interval_weak_connectivity =
3629 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003630 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3631 modified_config.ice_unwritable_min_checks =
3632 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003633 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003634 modified_config.stun_candidate_keepalive_interval =
3635 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003636 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003637 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003638 modified_config.active_reset_srtp_params =
3639 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003640 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003641 modified_config.use_media_transport_for_data_channels =
3642 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003643 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003644 modified_config.use_datagram_transport_for_data_channels =
3645 configuration.use_datagram_transport_for_data_channels;
Jonas Oreland3c028422019-08-22 16:16:35 +02003646 modified_config.turn_logging_id = configuration.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -08003647 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003648 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3649 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003650 }
3651
Steve Anton038834f2017-07-14 15:59:59 -07003652 // Validate the modified configuration.
3653 RTCError validate_error = ValidateConfiguration(modified_config);
3654 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003655 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003656 }
3657
deadbeef293e9262017-01-11 12:28:30 -08003658 // Note that this isn't possible through chromium, since it's an unsigned
3659 // short in WebIDL.
3660 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003661 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003662 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003663 }
3664
3665 // Parse ICE servers before hopping to network thread.
3666 cricket::ServerAddresses stun_servers;
3667 std::vector<cricket::RelayServerConfig> turn_servers;
3668 RTCErrorType parse_error =
3669 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3670 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003671 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003672 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003673 // Add the turn logging id to all turn servers
3674 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3675 turn_server.turn_logging_id = configuration.turn_logging_id;
3676 }
3677
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003678 // Note if STUN or TURN servers were supplied.
3679 if (!stun_servers.empty()) {
3680 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3681 }
3682 if (!turn_servers.empty()) {
3683 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3684 }
deadbeef293e9262017-01-11 12:28:30 -08003685
3686 // In theory this shouldn't fail.
3687 if (!network_thread()->Invoke<bool>(
3688 RTC_FROM_HERE,
3689 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3690 stun_servers, turn_servers, modified_config.type,
3691 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003692 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003693 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003694 modified_config.stun_candidate_keepalive_interval,
3695 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003696 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3697 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003698 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003699
deadbeefd1a38b52016-12-10 13:15:33 -08003700 // As described in JSEP, calling setConfiguration with new ICE servers or
3701 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3702 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003703 if (modified_config.servers != configuration_.servers ||
3704 modified_config.type != configuration_.type ||
3705 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003706 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003707 }
skvladd1f5fda2017-02-03 16:54:05 -08003708
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003709 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003710
3711 use_datagram_transport_ = datagram_transport_config_.enabled &&
3712 modified_config.use_datagram_transport.value_or(
3713 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003714 use_datagram_transport_for_data_channels_ =
3715 datagram_transport_data_channel_config_.enabled &&
3716 modified_config.use_datagram_transport_for_data_channels.value_or(
3717 datagram_transport_data_channel_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003718 transport_controller_->SetMediaTransportSettings(
3719 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003720 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003721 use_datagram_transport_, use_datagram_transport_for_data_channels_);
skvladd1f5fda2017-02-03 16:54:05 -08003722
Zhi Huangb57e1692018-06-12 11:41:11 -07003723 if (configuration_.active_reset_srtp_params !=
3724 modified_config.active_reset_srtp_params) {
3725 transport_controller_->SetActiveResetSrtpParams(
3726 modified_config.active_reset_srtp_params);
3727 }
3728
deadbeef293e9262017-01-11 12:28:30 -08003729 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003730 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003731 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003732}
3733
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003734bool PeerConnection::AddIceCandidate(
3735 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003736 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003737 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003738 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003739 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003740 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003741 return false;
3742 }
Steve Antond25da372017-11-06 14:50:29 -08003743
3744 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003745 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003746 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003747 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003748 return false;
3749 }
3750
3751 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003752 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003753 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003754 return false;
3755 }
3756
3757 bool valid = false;
3758 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3759 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003760 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003761 return false;
3762 }
3763
3764 // Add this candidate to the remote session description.
3765 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003766 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003767 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003768 return false;
3769 }
3770
3771 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003772 bool result = UseCandidate(ice_candidate);
3773 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003774 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003775 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3776 } else {
3777 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3778 }
3779 return result;
Steve Antond25da372017-11-06 14:50:29 -08003780 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003781 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003782 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003783 return true;
3784 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003785}
3786
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003787bool PeerConnection::RemoveIceCandidates(
3788 const std::vector<cricket::Candidate>& candidates) {
3789 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003790 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003791 if (IsClosed()) {
3792 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3793 return false;
3794 }
3795
Steve Antond25da372017-11-06 14:50:29 -08003796 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003797 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3798 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003799 return false;
3800 }
3801
3802 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003803 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003804 return false;
3805 }
3806
3807 size_t number_removed =
3808 mutable_remote_description()->RemoveCandidates(candidates);
3809 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003810 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003811 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003812 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003813 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003814 }
3815
3816 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003817 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3818 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003819 RTC_LOG(LS_ERROR)
3820 << "RemoveIceCandidates: Error when removing remote candidates: "
3821 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003822 }
3823 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003824}
3825
Niels Möller0c4f7be2018-05-07 14:01:37 +02003826RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003827 if (!worker_thread()->IsCurrent()) {
3828 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003829 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003830 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003831 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003832
Niels Möller0c4f7be2018-05-07 14:01:37 +02003833 const bool has_min = bitrate.min_bitrate_bps.has_value();
3834 const bool has_start = bitrate.start_bitrate_bps.has_value();
3835 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003836 if (has_min && *bitrate.min_bitrate_bps < 0) {
3837 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3838 "min_bitrate_bps <= 0");
3839 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003840 if (has_start) {
3841 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003842 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003843 "start_bitrate_bps < min_bitrate_bps");
3844 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003845 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3846 "curent_bitrate_bps < 0");
3847 }
3848 }
3849 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003850 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003851 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003852 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003853 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3854 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3855 "max_bitrate_bps < min_bitrate_bps");
3856 } else if (*bitrate.max_bitrate_bps < 0) {
3857 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3858 "max_bitrate_bps < 0");
3859 }
3860 }
3861
zstein4b979802017-06-02 14:37:37 -07003862 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003863 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003864
3865 return RTCError::OK();
3866}
3867
henrika5f6bf242017-11-01 11:06:56 +01003868void PeerConnection::SetAudioPlayout(bool playout) {
3869 if (!worker_thread()->IsCurrent()) {
3870 worker_thread()->Invoke<void>(
3871 RTC_FROM_HERE,
3872 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3873 return;
3874 }
3875 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003876 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003877 audio_state->SetPlayout(playout);
3878}
3879
3880void PeerConnection::SetAudioRecording(bool recording) {
3881 if (!worker_thread()->IsCurrent()) {
3882 worker_thread()->Invoke<void>(
3883 RTC_FROM_HERE,
3884 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3885 return;
3886 }
3887 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003888 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003889 audio_state->SetRecording(recording);
3890}
3891
Steve Anton8c0f7a72017-10-03 10:03:10 -07003892std::unique_ptr<rtc::SSLCertificate>
3893PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003894 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3895 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003896 return nullptr;
3897 }
Steve Antonf25303e2018-10-16 15:23:31 -07003898 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003899}
3900
Zhi Huang70b820f2018-01-27 14:16:15 -08003901std::unique_ptr<rtc::SSLCertChain>
3902PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003903 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003904 auto audio_transceiver = GetFirstAudioTransceiver();
3905 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003906 return nullptr;
3907 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003908 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003909 audio_transceiver->internal()->channel()->transport_name());
3910}
3911
3912rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3913PeerConnection::GetFirstAudioTransceiver() const {
3914 for (auto transceiver : transceivers_) {
3915 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3916 return transceiver;
3917 }
3918 }
3919 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003920}
3921
Bjorn Tereliusde939432017-11-20 17:38:14 +01003922bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3923 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003924 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02003925 RTC_FROM_HERE,
3926 [this, output = std::move(output), output_period_ms]() mutable {
3927 return StartRtcEventLog_w(std::move(output), output_period_ms);
3928 });
ivoc14d5dbe2016-07-04 07:06:55 -07003929}
3930
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003931bool PeerConnection::StartRtcEventLog(
3932 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003933 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3934 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3935 output_period_ms = 5000;
3936 }
3937 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003938}
3939
ivoc14d5dbe2016-07-04 07:06:55 -07003940void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003941 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003942 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3943}
3944
Harald Alvestrandad88c882018-11-28 16:47:46 +01003945rtc::scoped_refptr<DtlsTransportInterface>
3946PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003947 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003948 return transport_controller_->LookupDtlsTransportByMid(mid);
3949}
3950
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003951rtc::scoped_refptr<DtlsTransport>
3952PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003953 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003954 return transport_controller_->LookupDtlsTransportByMid(mid);
3955}
3956
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003957rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3958 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003959 RTC_DCHECK_RUN_ON(signaling_thread());
Qingsi Wang437077d2019-09-10 17:52:26 +00003960 return sctp_transport_;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003961}
3962
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003963const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003964 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003965 return pending_local_description_ ? pending_local_description_.get()
3966 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003967}
3968
3969const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003970 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003971 return pending_remote_description_ ? pending_remote_description_.get()
3972 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003973}
3974
deadbeeffe4a8a42016-12-20 17:56:17 -08003975const SessionDescriptionInterface* PeerConnection::current_local_description()
3976 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003977 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003978 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003979}
3980
3981const SessionDescriptionInterface* PeerConnection::current_remote_description()
3982 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003983 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003984 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003985}
3986
3987const SessionDescriptionInterface* PeerConnection::pending_local_description()
3988 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003989 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003990 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003991}
3992
3993const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3994 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003995 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003996 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003997}
3998
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003999void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004000 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004001 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004002 // Update stats here so that we have the most recent stats for tracks and
4003 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004004 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004005
Steve Anton75737c02017-11-06 10:37:17 -08004006 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004007 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004008
Mirko Bonadei739baf02019-01-27 17:29:42 +01004009 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004010 transceiver->Stop();
4011 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004012
4013 // Ensure that all asynchronous stats requests are completed before destroying
4014 // the transport controller below.
4015 if (stats_collector_) {
4016 stats_collector_->WaitForPendingRequest();
4017 }
4018
4019 // Don't destroy BaseChannels until after stats has been cleaned up so that
4020 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004021 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004022
Qingsi Wang93a84392018-01-30 17:13:09 -08004023 // The event log is used in the transport controller, which must be outlived
4024 // by the former. CreateOffer by the peer connection is implemented
4025 // asynchronously and if the peer connection is closed without resetting the
4026 // WebRTC session description factory, the session description factory would
4027 // call the transport controller.
4028 webrtc_session_desc_factory_.reset();
4029 transport_controller_.reset();
4030
deadbeef42a42632017-03-10 15:18:00 -08004031 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004032 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4033 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004034
Steve Anton978b8762017-09-29 12:15:02 -07004035 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004036 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004037 call_.reset();
4038 // The event log must outlive call (and any other object that uses it).
4039 event_log_.reset();
4040 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004041 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004042 // The .h file says that observer can be discarded after close() returns.
4043 // Make sure this is true.
4044 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004045}
4046
Steve Antonad182762018-09-05 20:22:40 +00004047void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004048 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004049 switch (msg->message_id) {
4050 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4051 SetSessionDescriptionMsg* param =
4052 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4053 param->observer->OnSuccess();
4054 delete param;
4055 break;
4056 }
4057 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4058 SetSessionDescriptionMsg* param =
4059 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4060 param->observer->OnFailure(std::move(param->error));
4061 delete param;
4062 break;
4063 }
4064 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4065 CreateSessionDescriptionMsg* param =
4066 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4067 param->observer->OnFailure(std::move(param->error));
4068 delete param;
4069 break;
4070 }
4071 case MSG_GETSTATS: {
4072 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4073 StatsReports reports;
4074 stats_->GetStats(param->track, &reports);
4075 param->observer->OnComplete(reports);
4076 delete param;
4077 break;
4078 }
4079 case MSG_FREE_DATACHANNELS: {
4080 sctp_data_channels_to_free_.clear();
4081 break;
4082 }
4083 case MSG_REPORT_USAGE_PATTERN: {
4084 ReportUsagePattern();
4085 break;
4086 }
4087 default:
4088 RTC_NOTREACHED() << "Not implemented";
4089 break;
4090 }
4091}
4092
Steve Antonafb0bb72018-02-20 11:35:37 -08004093cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4094 RTC_DCHECK(!IsUnifiedPlan());
4095 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4096 GetAudioTransceiver()->internal()->channel());
4097 if (voice_channel) {
4098 return voice_channel->media_channel();
4099 } else {
4100 return nullptr;
4101 }
4102}
4103
4104cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4105 RTC_DCHECK(!IsUnifiedPlan());
4106 auto* video_channel = static_cast<cricket::VideoChannel*>(
4107 GetVideoTransceiver()->internal()->channel());
4108 if (video_channel) {
4109 return video_channel->media_channel();
4110 } else {
4111 return nullptr;
4112 }
4113}
4114
Steve Anton4171afb2017-11-20 10:20:22 -08004115void PeerConnection::CreateAudioReceiver(
4116 MediaStreamInterface* stream,
4117 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004118 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4119 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004120 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4121 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004122 auto* audio_receiver = new AudioRtpReceiver(
4123 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004124 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004125 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4126 audio_receiver->SetupUnsignaledMediaChannel();
4127 } else {
4128 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4129 }
Steve Antond3679212018-01-17 17:41:02 -08004130 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4131 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004132 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004133 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004134 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004135}
4136
Steve Anton4171afb2017-11-20 10:20:22 -08004137void PeerConnection::CreateVideoReceiver(
4138 MediaStreamInterface* stream,
4139 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004140 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4141 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004142 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4143 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004144 auto* video_receiver = new VideoRtpReceiver(
4145 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004146 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004147 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4148 video_receiver->SetupUnsignaledMediaChannel();
4149 } else {
4150 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4151 }
Steve Antond3679212018-01-17 17:41:02 -08004152 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4153 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004154 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004155 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004156 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004157}
4158
deadbeef70ab1a12015-09-28 16:53:55 -07004159// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4160// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004161rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004162 const RtpSenderInfo& remote_sender_info) {
4163 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4164 if (!receiver) {
4165 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4166 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004167 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004168 }
Steve Anton4171afb2017-11-20 10:20:22 -08004169 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4170 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4171 } else {
4172 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4173 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004174 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004175}
4176
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004177void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4178 MediaStreamInterface* stream) {
4179 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004180 RTC_DCHECK(track);
4181 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004182 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004183 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004184 // We already have a sender for this track, so just change the stream_id
4185 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004186 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004187 return;
4188 }
4189
4190 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004191 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004192 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004193 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004194 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004195 // If the sender has already been configured in SDP, we call SetSsrc,
4196 // which will connect the sender to the underlying transport. This can
4197 // occur if a local session description that contains the ID of the sender
4198 // is set before AddStream is called. It can also occur if the local
4199 // session description is not changed and RemoveStream is called, and
4200 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004201 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004202 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004203 if (sender_info) {
4204 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004205 }
4206}
4207
4208// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4209// indefinitely, when we have unified plan SDP.
4210void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4211 MediaStreamInterface* stream) {
4212 RTC_DCHECK(!IsClosed());
4213 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004214 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004215 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4216 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004217 return;
4218 }
Steve Anton4171afb2017-11-20 10:20:22 -08004219 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004220}
4221
4222void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4223 MediaStreamInterface* stream) {
4224 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004225 RTC_DCHECK(track);
4226 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004227 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004228 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004229 // We already have a sender for this track, so just change the stream_id
4230 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004231 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004232 return;
4233 }
4234
4235 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004236 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004237 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004238 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004239 GetVideoTransceiver()->internal()->AddSender(new_sender);
4240 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004241 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004242 if (sender_info) {
4243 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004244 }
4245}
4246
4247void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4248 MediaStreamInterface* stream) {
4249 RTC_DCHECK(!IsClosed());
4250 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004251 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004252 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4253 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004254 return;
4255 }
Steve Anton4171afb2017-11-20 10:20:22 -08004256 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004257}
4258
Steve Antonba818672017-11-06 10:21:57 -08004259void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004260 if (ice_connection_state_ == new_state) {
4261 return;
4262 }
4263
deadbeefcbecd352015-09-23 11:50:27 -07004264 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004265 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004266 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004267 return;
4268 }
Steve Antonba818672017-11-06 10:21:57 -08004269
Mirko Bonadei675513b2017-11-09 11:09:25 +01004270 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4271 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004272 RTC_DCHECK(ice_connection_state_ !=
4273 PeerConnectionInterface::kIceConnectionClosed);
4274
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004275 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004276 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004277}
4278
Alex Loiko9289eda2018-11-23 16:18:59 +00004279void PeerConnection::SetStandardizedIceConnectionState(
4280 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004281 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004282 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004283 }
4284
4285 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004286 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004287 }
4288
4289 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4290 << standardized_ice_connection_state_ << " => " << new_state;
4291
Alex Loiko9289eda2018-11-23 16:18:59 +00004292 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004293 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004294}
4295
Jonas Olsson635474e2018-10-18 15:58:17 +02004296void PeerConnection::SetConnectionState(
4297 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004298 if (connection_state_ == new_state)
4299 return;
4300 if (IsClosed())
4301 return;
4302 connection_state_ = new_state;
4303 Observer()->OnConnectionChange(new_state);
4304}
4305
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004306void PeerConnection::OnIceGatheringChange(
4307 PeerConnectionInterface::IceGatheringState new_state) {
4308 if (IsClosed()) {
4309 return;
4310 }
4311 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004312 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004313}
4314
jbauch81bf7b02017-03-25 08:31:12 -07004315void PeerConnection::OnIceCandidate(
4316 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004317 if (IsClosed()) {
4318 return;
4319 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004320 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004321 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004322}
4323
Eldar Relloda13ea22019-06-01 12:23:43 +03004324void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4325 const std::string& url,
4326 int error_code,
4327 const std::string& error_text) {
4328 if (IsClosed()) {
4329 return;
4330 }
4331 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4332}
4333
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004334void PeerConnection::OnIceCandidatesRemoved(
4335 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004336 if (IsClosed()) {
4337 return;
4338 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004339 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004340}
4341
Alex Drake00c7ecf2019-08-06 10:54:47 -07004342void PeerConnection::OnSelectedCandidatePairChanged(
4343 const cricket::CandidatePairChangeEvent& event) {
4344 if (IsClosed()) {
4345 return;
4346 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004347
Qingsi Wangcc46b102019-09-12 11:19:01 -07004348 if (event.selected_candidate_pair.local_candidate().type() ==
4349 LOCAL_PORT_TYPE &&
4350 event.selected_candidate_pair.remote_candidate().type() ==
4351 LOCAL_PORT_TYPE) {
4352 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4353 }
4354
Alex Drake00c7ecf2019-08-06 10:54:47 -07004355 Observer()->OnIceSelectedCandidatePairChanged(event);
4356}
4357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004358void PeerConnection::ChangeSignalingState(
4359 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004360 if (signaling_state_ == signaling_state) {
4361 return;
4362 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004363 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4364 << GetSignalingStateString(signaling_state_)
4365 << " New state: "
4366 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004367 signaling_state_ = signaling_state;
4368 if (signaling_state == kClosed) {
4369 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004370 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004371 standardized_ice_connection_state_ =
4372 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004373 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4374 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004375 if (ice_gathering_state_ != kIceGatheringComplete) {
4376 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004377 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004378 }
4379 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004380 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004381}
4382
deadbeefeb459812015-12-15 19:24:43 -08004383void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4384 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004385 if (IsClosed()) {
4386 return;
4387 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004388 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004389 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004390}
4391
deadbeefeb459812015-12-15 19:24:43 -08004392void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4393 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004394 if (IsClosed()) {
4395 return;
4396 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004397 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004398 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004399}
4400
4401void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4402 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004403 if (IsClosed()) {
4404 return;
4405 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004406 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004407 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004408}
4409
4410void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4411 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004412 if (IsClosed()) {
4413 return;
4414 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004415 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004416 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004417}
4418
Henrik Boström31638672017-11-23 17:48:32 +01004419void PeerConnection::PostSetSessionDescriptionSuccess(
4420 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004421 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4422 signaling_thread()->Post(RTC_FROM_HERE, this,
4423 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004424}
4425
deadbeefab9b2d12015-10-14 11:33:11 -07004426void PeerConnection::PostSetSessionDescriptionFailure(
4427 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004428 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004429 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004430 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4431 msg->error = std::move(error);
4432 signaling_thread()->Post(RTC_FROM_HERE, this,
4433 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004434}
4435
4436void PeerConnection::PostCreateSessionDescriptionFailure(
4437 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004438 RTCError error) {
4439 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004440 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4441 msg->error = std::move(error);
4442 signaling_thread()->Post(RTC_FROM_HERE, this,
4443 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004444}
4445
zhihuang1c378ed2017-08-17 14:10:50 -07004446void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004447 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004448 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004449 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004450
Steve Antondcc3c022017-12-22 16:02:54 -08004451 if (IsUnifiedPlan()) {
4452 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4453 } else {
4454 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4455 }
4456
Steve Antonfa2260d2017-12-28 16:38:23 -08004457 // Intentionally unset the data channel type for RTP data channel with the
4458 // second condition. Otherwise the RTP data channels would be successfully
4459 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4460 // when building with chromium. We want to leave RTP data channels broken, so
4461 // people won't try to use them.
4462 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4463 session_options->data_channel_type = data_channel_type();
4464 }
4465
Steve Antondcc3c022017-12-22 16:02:54 -08004466 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004467 bool ice_restart = offer_answer_options.ice_restart ||
4468 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004469 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004470 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004471 options.transport_options.enable_ice_renomination =
4472 configuration_.enable_ice_renomination;
4473 }
4474
4475 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004476 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004477 session_options->pooled_ice_credentials =
4478 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4479 RTC_FROM_HERE,
4480 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4481 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004482 session_options->offer_extmap_allow_mixed =
4483 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004484
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004485 if (configuration_.use_media_transport ||
4486 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004487 session_options->media_transport_settings =
4488 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4489 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004490
4491 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004492 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004493 for (auto& options : session_options->media_description_options) {
4494 options.transport_options.opaque_parameters =
4495 transport_controller_->GetTransportParameters(options.mid);
4496 }
4497 }
4498
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004499 // Allow fallback for using obsolete SCTP syntax.
4500 // Note that the default in |session_options| is true, while
4501 // the default in |options| is false.
4502 session_options->use_obsolete_sctp_sdp =
4503 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004504}
4505
4506void PeerConnection::GetOptionsForPlanBOffer(
4507 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4508 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004509 // Figure out transceiver directional preferences.
4510 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4511 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4512
4513 // By default, generate sendrecv/recvonly m= sections.
4514 bool recv_audio = true;
4515 bool recv_video = true;
4516
4517 // By default, only offer a new m= section if we have media to send with it.
4518 bool offer_new_audio_description = send_audio;
4519 bool offer_new_video_description = send_video;
4520 bool offer_new_data_description = HasDataChannels();
4521
4522 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004523 if (offer_answer_options.offer_to_receive_audio !=
4524 RTCOfferAnswerOptions::kUndefined) {
4525 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004526 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004527 offer_new_audio_description ||
4528 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004529 }
Steve Antondcc3c022017-12-22 16:02:54 -08004530 if (offer_answer_options.offer_to_receive_video !=
4531 RTCOfferAnswerOptions::kUndefined) {
4532 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004533 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004534 offer_new_video_description ||
4535 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004536 }
4537
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004538 absl::optional<size_t> audio_index;
4539 absl::optional<size_t> video_index;
4540 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004541 // If a current description exists, generate m= sections in the same order,
4542 // using the first audio/video/data section that appears and rejecting
4543 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004544 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004545 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004546 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004547 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4548 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4549 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004550 }
4551
zhihuang1c378ed2017-08-17 14:10:50 -07004552 // Add audio/video/data m= sections to the end if needed.
4553 if (!audio_index && offer_new_audio_description) {
4554 session_options->media_description_options.push_back(
4555 cricket::MediaDescriptionOptions(
4556 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004557 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4558 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004559 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004560 }
zhihuang1c378ed2017-08-17 14:10:50 -07004561 if (!video_index && offer_new_video_description) {
4562 session_options->media_description_options.push_back(
4563 cricket::MediaDescriptionOptions(
4564 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004565 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4566 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004567 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004568 }
zhihuang1c378ed2017-08-17 14:10:50 -07004569 if (!data_index && offer_new_data_description) {
4570 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004571 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004572 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004573 }
4574
4575 cricket::MediaDescriptionOptions* audio_media_description_options =
4576 !audio_index ? nullptr
4577 : &session_options->media_description_options[*audio_index];
4578 cricket::MediaDescriptionOptions* video_media_description_options =
4579 !video_index ? nullptr
4580 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004581
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004582 AddPlanBRtpSenderOptions(GetSendersInternal(),
4583 audio_media_description_options,
4584 video_media_description_options,
4585 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004586}
4587
Steve Antondcc3c022017-12-22 16:02:54 -08004588static cricket::MediaDescriptionOptions
4589GetMediaDescriptionOptionsForTransceiver(
4590 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4591 transceiver,
4592 const std::string& mid) {
4593 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004594 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004595 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004596 media_description_options.codec_preferences =
4597 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004598 // This behavior is specified in JSEP. The gist is that:
4599 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4600 // sendrecv.
4601 // 2. If the MSID is included, then it must be included in any subsequent
4602 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004603 if (transceiver->stopped() ||
4604 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4605 !transceiver->internal()->has_ever_been_used_to_send())) {
4606 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004607 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004608
4609 cricket::SenderOptions sender_options;
4610 sender_options.track_id = transceiver->sender()->id();
4611 sender_options.stream_ids = transceiver->sender()->stream_ids();
4612
4613 // The following sets up RIDs and Simulcast.
4614 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004615 RtpParameters send_parameters =
4616 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004617 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4618 send_parameters.encodings.end(),
4619 [](const RtpEncodingParameters& encoding) {
4620 return !encoding.rid.empty();
4621 });
4622
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004623 std::vector<RidDescription> send_rids;
4624 SimulcastLayerList send_layers;
4625 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4626 if (encoding.rid.empty()) {
4627 continue;
4628 }
4629 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4630 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4631 }
4632
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004633 if (has_rids) {
4634 sender_options.rids = send_rids;
4635 }
4636
4637 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004638 // When RIDs are configured, we must set num_sim_layers to 0 to.
4639 // Otherwise, num_sim_layers must be 1 because either there is no
4640 // simulcast, or simulcast is acheived by munging the SDP.
4641 sender_options.num_sim_layers = has_rids ? 0 : 1;
4642 media_description_options.sender_options.push_back(sender_options);
4643
Steve Antondcc3c022017-12-22 16:02:54 -08004644 return media_description_options;
4645}
4646
Steve Anton5c72e712018-12-10 14:25:30 -08004647// Returns the ContentInfo at mline index |i|, or null if none exists.
4648static const ContentInfo* GetContentByIndex(
4649 const SessionDescriptionInterface* sdesc,
4650 size_t i) {
4651 if (!sdesc) {
4652 return nullptr;
4653 }
4654 const ContentInfos& contents = sdesc->description()->contents();
4655 return (i < contents.size() ? &contents[i] : nullptr);
4656}
4657
Steve Antondcc3c022017-12-22 16:02:54 -08004658void PeerConnection::GetOptionsForUnifiedPlanOffer(
4659 const RTCOfferAnswerOptions& offer_answer_options,
4660 cricket::MediaSessionOptions* session_options) {
4661 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4662 // Offers) and 5.2.2 (Subsequent Offers).
4663 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004664 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004665 const ContentInfos& local_contents =
4666 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004667 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004668 const ContentInfos& remote_contents =
4669 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004670 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004671 // The mline indices that can be recycled. New transceivers should reuse these
4672 // slots first.
4673 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004674 // First, go through each media section that exists in either the local or
4675 // remote description and generate a media section in this offer for the
4676 // associated transceiver. If a media section can be recycled, generate a
4677 // default, rejected media section here that can be later overwritten.
4678 for (size_t i = 0;
4679 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4680 // Either |local_content| or |remote_content| is non-null.
4681 const ContentInfo* local_content =
4682 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004683 const ContentInfo* current_local_content =
4684 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004685 const ContentInfo* remote_content =
4686 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004687 const ContentInfo* current_remote_content =
4688 GetContentByIndex(current_remote_description(), i);
4689 bool had_been_rejected =
4690 (current_local_content && current_local_content->rejected) ||
4691 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004692 const std::string& mid =
4693 (local_content ? local_content->name : remote_content->name);
4694 cricket::MediaType media_type =
4695 (local_content ? local_content->media_description()->type()
4696 : remote_content->media_description()->type());
4697 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4698 media_type == cricket::MEDIA_TYPE_VIDEO) {
4699 auto transceiver = GetAssociatedTransceiver(mid);
4700 RTC_CHECK(transceiver);
4701 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004702 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004703 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004704 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004705 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4706 RtpTransceiverDirection::kInactive,
4707 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004708 recycleable_mline_indices.push(i);
4709 } else {
4710 session_options->media_description_options.push_back(
4711 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4712 // CreateOffer shouldn't really cause any state changes in
4713 // PeerConnection, but we need a way to match new transceivers to new
4714 // media sections in SetLocalDescription and JSEP specifies this is done
4715 // by recording the index of the media section generated for the
4716 // transceiver in the offer.
4717 transceiver->internal()->set_mline_index(i);
4718 }
4719 } else {
4720 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004721 RTC_CHECK(GetDataMid());
4722 if (had_been_rejected || mid != *GetDataMid()) {
4723 session_options->media_description_options.push_back(
4724 GetMediaDescriptionOptionsForRejectedData(mid));
4725 } else {
4726 session_options->media_description_options.push_back(
4727 GetMediaDescriptionOptionsForActiveData(mid));
4728 }
Steve Antondcc3c022017-12-22 16:02:54 -08004729 }
4730 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004731
Steve Antondcc3c022017-12-22 16:02:54 -08004732 // Next, look for transceivers that are newly added (that is, are not stopped
4733 // and not associated). Reuse media sections marked as recyclable first,
4734 // otherwise append to the end of the offer. New media sections should be
4735 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004736 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004737 if (transceiver->mid() || transceiver->stopped()) {
4738 continue;
4739 }
4740 size_t mline_index;
4741 if (!recycleable_mline_indices.empty()) {
4742 mline_index = recycleable_mline_indices.front();
4743 recycleable_mline_indices.pop();
4744 session_options->media_description_options[mline_index] =
4745 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004746 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004747 } else {
4748 mline_index = session_options->media_description_options.size();
4749 session_options->media_description_options.push_back(
4750 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004751 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004752 }
4753 // See comment above for why CreateOffer changes the transceiver's state.
4754 transceiver->internal()->set_mline_index(mline_index);
4755 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004756 // Lastly, add a m-section if we have local data channels and an m section
4757 // does not already exist.
4758 if (!GetDataMid() && HasDataChannels()) {
4759 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004760 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004761 }
Steve Antondcc3c022017-12-22 16:02:54 -08004762}
4763
4764void PeerConnection::GetOptionsForAnswer(
4765 const RTCOfferAnswerOptions& offer_answer_options,
4766 cricket::MediaSessionOptions* session_options) {
4767 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4768
4769 if (IsUnifiedPlan()) {
4770 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4771 } else {
4772 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4773 }
4774
Steve Antonfa2260d2017-12-28 16:38:23 -08004775 // Intentionally unset the data channel type for RTP data channel. Otherwise
4776 // the RTP data channels would be successfully negotiated by default and the
4777 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4778 // We want to leave RTP data channels broken, so people won't try to use them.
4779 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4780 session_options->data_channel_type = data_channel_type();
4781 }
4782
Steve Antondcc3c022017-12-22 16:02:54 -08004783 // Apply ICE renomination flag.
4784 for (auto& options : session_options->media_description_options) {
4785 options.transport_options.enable_ice_renomination =
4786 configuration_.enable_ice_renomination;
4787 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004788
4789 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004790 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004791 session_options->pooled_ice_credentials =
4792 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4793 RTC_FROM_HERE,
4794 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4795 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004796
4797 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004798 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004799 for (auto& options : session_options->media_description_options) {
4800 options.transport_options.opaque_parameters =
4801 transport_controller_->GetTransportParameters(options.mid);
4802 }
4803 }
deadbeefab9b2d12015-10-14 11:33:11 -07004804}
4805
Steve Antondcc3c022017-12-22 16:02:54 -08004806void PeerConnection::GetOptionsForPlanBAnswer(
4807 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004808 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004809 // Figure out transceiver directional preferences.
4810 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4811 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4812
4813 // By default, generate sendrecv/recvonly m= sections. The direction is also
4814 // restricted by the direction in the offer.
4815 bool recv_audio = true;
4816 bool recv_video = true;
4817
4818 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004819 if (offer_answer_options.offer_to_receive_audio !=
4820 RTCOfferAnswerOptions::kUndefined) {
4821 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004822 }
Steve Antondcc3c022017-12-22 16:02:54 -08004823 if (offer_answer_options.offer_to_receive_video !=
4824 RTCOfferAnswerOptions::kUndefined) {
4825 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004826 }
4827
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004828 absl::optional<size_t> audio_index;
4829 absl::optional<size_t> video_index;
4830 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004831
4832 // Generate m= sections that match those in the offer.
4833 // Note that mediasession.cc will handle intersection our preferred
4834 // direction with the offered direction.
4835 GenerateMediaDescriptionOptions(
4836 remote_description(),
4837 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4838 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4839 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004840
4841 cricket::MediaDescriptionOptions* audio_media_description_options =
4842 !audio_index ? nullptr
4843 : &session_options->media_description_options[*audio_index];
4844 cricket::MediaDescriptionOptions* video_media_description_options =
4845 !video_index ? nullptr
4846 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004847
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004848 AddPlanBRtpSenderOptions(GetSendersInternal(),
4849 audio_media_description_options,
4850 video_media_description_options,
4851 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004852}
zhihuangaf388472016-11-02 16:49:48 -07004853
Steve Antondcc3c022017-12-22 16:02:54 -08004854void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4855 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4856 cricket::MediaSessionOptions* session_options) {
4857 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4858 // Answers) and 5.3.2 (Subsequent Answers).
4859 RTC_DCHECK(remote_description());
4860 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4861 for (const ContentInfo& content :
4862 remote_description()->description()->contents()) {
4863 cricket::MediaType media_type = content.media_description()->type();
4864 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4865 media_type == cricket::MEDIA_TYPE_VIDEO) {
4866 auto transceiver = GetAssociatedTransceiver(content.name);
4867 RTC_CHECK(transceiver);
4868 session_options->media_description_options.push_back(
4869 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4870 } else {
4871 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004872 // Reject all data sections if data channels are disabled.
4873 // Reject a data section if it has already been rejected.
4874 // Reject all data sections except for the first one.
4875 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4876 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004877 session_options->media_description_options.push_back(
4878 GetMediaDescriptionOptionsForRejectedData(content.name));
4879 } else {
4880 session_options->media_description_options.push_back(
4881 GetMediaDescriptionOptionsForActiveData(content.name));
4882 }
Steve Antondcc3c022017-12-22 16:02:54 -08004883 }
4884 }
htaa2a49d92016-03-04 02:51:39 -08004885}
4886
zhihuang1c378ed2017-08-17 14:10:50 -07004887void PeerConnection::GenerateMediaDescriptionOptions(
4888 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004889 RtpTransceiverDirection audio_direction,
4890 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004891 absl::optional<size_t>* audio_index,
4892 absl::optional<size_t>* video_index,
4893 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004894 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004895 for (const cricket::ContentInfo& content :
4896 session_desc->description()->contents()) {
4897 if (IsAudioContent(&content)) {
4898 // If we already have an audio m= section, reject this extra one.
4899 if (*audio_index) {
4900 session_options->media_description_options.push_back(
4901 cricket::MediaDescriptionOptions(
4902 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004903 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004904 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004905 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004906 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004907 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4908 content.name, audio_direction,
4909 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004910 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004911 }
4912 } else if (IsVideoContent(&content)) {
4913 // If we already have an video m= section, reject this extra one.
4914 if (*video_index) {
4915 session_options->media_description_options.push_back(
4916 cricket::MediaDescriptionOptions(
4917 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004918 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004919 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004920 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004921 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004922 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4923 content.name, video_direction,
4924 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004925 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004926 }
4927 } else {
4928 RTC_DCHECK(IsDataContent(&content));
4929 // If we already have an data m= section, reject this extra one.
4930 if (*data_index) {
4931 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004932 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004933 } else {
4934 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004935 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004936 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004937 }
4938 }
htaa2a49d92016-03-04 02:51:39 -08004939 }
deadbeefab9b2d12015-10-14 11:33:11 -07004940}
4941
Steve Antonfa2260d2017-12-28 16:38:23 -08004942cricket::MediaDescriptionOptions
4943PeerConnection::GetMediaDescriptionOptionsForActiveData(
4944 const std::string& mid) const {
4945 // Direction for data sections is meaningless, but legacy endpoints might
4946 // expect sendrecv.
4947 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4948 RtpTransceiverDirection::kSendRecv,
4949 /*stopped=*/false);
4950 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4951 return options;
4952}
4953
4954cricket::MediaDescriptionOptions
4955PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4956 const std::string& mid) const {
4957 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4958 RtpTransceiverDirection::kInactive,
4959 /*stopped=*/true);
4960 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4961 return options;
4962}
4963
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004964absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004965 switch (data_channel_type_) {
4966 case cricket::DCT_RTP:
4967 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004968 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004969 }
4970 return rtp_data_channel_->content_name();
4971 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004972 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004973 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
4974 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
4975 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004976 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004977 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004978 }
4979}
4980
Steve Anton4171afb2017-11-20 10:20:22 -08004981void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4982 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4983 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004984 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004985}
4986
Steve Anton4171afb2017-11-20 10:20:22 -08004987void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004988 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004989 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004990 cricket::MediaType media_type,
4991 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004992 RTC_DCHECK(!IsUnifiedPlan());
4993
Steve Anton4171afb2017-11-20 10:20:22 -08004994 std::vector<RtpSenderInfo>* current_senders =
4995 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004996
Steve Anton4171afb2017-11-20 10:20:22 -08004997 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004998 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004999 for (auto sender_it = current_senders->begin();
5000 sender_it != current_senders->end();
5001 /* incremented manually */) {
5002 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005003 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005004 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005005 std::string params_stream_id;
5006 if (params) {
5007 params_stream_id =
5008 (!params->first_stream_id().empty() ? params->first_stream_id()
5009 : kDefaultStreamId);
5010 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005011 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005012 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005013 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005014 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005015 sender_exists) {
5016 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005017 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005018 OnRemoteSenderRemoved(info, media_type);
5019 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005020 }
5021 }
5022
Steve Anton4171afb2017-11-20 10:20:22 -08005023 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005024 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005025 if (!params.has_ssrcs()) {
5026 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5027 // sender, this means it is coming from a Unified Plan endpoint,so we just
5028 // create a default.
5029 default_sender_needed = true;
5030 break;
5031 }
5032
Seth Hampson845e8782018-03-02 11:34:10 -08005033 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005034 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005035 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5036 // not supported in Plan B, we just take the first here and create the
5037 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005038 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005039 (!params.first_stream_id().empty() ? params.first_stream_id()
5040 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005041 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005042 uint32_t ssrc = params.first_ssrc();
5043
5044 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005045 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005046 if (!stream) {
5047 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005048 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005049 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005050 remote_streams_->AddStream(stream);
5051 new_streams->AddStream(stream);
5052 }
5053
Steve Anton4171afb2017-11-20 10:20:22 -08005054 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005055 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005056 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005057 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005058 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005059 }
5060 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005061
Steve Anton4171afb2017-11-20 10:20:22 -08005062 // Add default sender if necessary.
5063 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005064 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005065 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005066 if (!default_stream) {
5067 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005068 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005069 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005070 remote_streams_->AddStream(default_stream);
5071 new_streams->AddStream(default_stream);
5072 }
Steve Anton4171afb2017-11-20 10:20:22 -08005073 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5074 ? kDefaultAudioSenderId
5075 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005076 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005077 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005078 if (!default_sender_info) {
5079 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005080 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005081 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005082 }
5083 }
deadbeefab9b2d12015-10-14 11:33:11 -07005084}
5085
Steve Anton4171afb2017-11-20 10:20:22 -08005086void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5087 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005088 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5089 << " receiver for track_id=" << sender_info.sender_id
5090 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005091
Steve Anton3d954a62018-04-02 11:27:23 -07005092 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005093 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005094 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005095 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005096 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005097 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005098 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005099 }
5100}
5101
Steve Anton4171afb2017-11-20 10:20:22 -08005102void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5103 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005104 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5105 << " receiver for track_id=" << sender_info.sender_id
5106 << " and stream_id=" << sender_info.stream_id;
5107
Seth Hampson845e8782018-03-02 11:34:10 -08005108 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005109
Henrik Boström933d8b02017-10-10 10:05:16 -07005110 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005111 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005112 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5113 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005114 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005115 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005116 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005117 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005118 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005119 }
5120 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005121 // Stopping or destroying a VideoRtpReceiver will end the
5122 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005123 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005124 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005125 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005126 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005127 // There's no guarantee the track is still available, e.g. the track may
5128 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005129 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005130 }
5131 } else {
nisseede5da42017-01-12 05:15:36 -08005132 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005133 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005134 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005135 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005136 }
deadbeefab9b2d12015-10-14 11:33:11 -07005137}
5138
5139void PeerConnection::UpdateEndedRemoteMediaStreams() {
5140 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5141 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5142 MediaStreamInterface* stream = remote_streams_->at(i);
5143 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5144 streams_to_remove.push_back(stream);
5145 }
5146 }
5147
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005148 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005149 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005150 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005151 }
5152}
5153
Steve Anton4171afb2017-11-20 10:20:22 -08005154void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005155 const std::vector<cricket::StreamParams>& streams,
5156 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005157 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005158
Seth Hampson845e8782018-03-02 11:34:10 -08005159 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005160 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005161 for (auto sender_it = current_senders->begin();
5162 sender_it != current_senders->end();
5163 /* incremented manually */) {
5164 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005165 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005166 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5167 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005168 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005169 OnLocalSenderRemoved(info, media_type);
5170 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005171 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005172 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005173 }
5174 }
5175
Steve Anton4171afb2017-11-20 10:20:22 -08005176 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005177 for (const cricket::StreamParams& params : streams) {
5178 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005179 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005180 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005181 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005182 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005183 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005184 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005185 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005186 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005187 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005188 }
5189 }
5190}
5191
Steve Anton4171afb2017-11-20 10:20:22 -08005192void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5193 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005194 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005195 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005196 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005197 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5198 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005199 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005200 return;
5201 }
5202
deadbeeffac06552015-11-25 11:26:01 -08005203 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005204 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005205 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005206 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005207 }
deadbeeffac06552015-11-25 11:26:01 -08005208
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005209 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005210 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005211}
5212
Steve Anton4171afb2017-11-20 10:20:22 -08005213void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5214 cricket::MediaType media_type) {
5215 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005216 if (!sender) {
5217 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005218 // SessionDescriptions has been renegotiated.
5219 return;
5220 }
deadbeeffac06552015-11-25 11:26:01 -08005221
5222 // A sender has been removed from the SessionDescription but it's still
5223 // associated with the PeerConnection. This only occurs if the SDP doesn't
5224 // match with the calls to CreateSender, AddStream and RemoveStream.
5225 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005226 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005227 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005228 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005229 }
deadbeeffac06552015-11-25 11:26:01 -08005230
Steve Anton4171afb2017-11-20 10:20:22 -08005231 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005232}
5233
5234void PeerConnection::UpdateLocalRtpDataChannels(
5235 const cricket::StreamParamsVec& streams) {
5236 std::vector<std::string> existing_channels;
5237
5238 // Find new and active data channels.
5239 for (const cricket::StreamParams& params : streams) {
5240 // |it->sync_label| is actually the data channel label. The reason is that
5241 // we use the same naming of data channels as we do for
5242 // MediaStreams and Tracks.
5243 // For MediaStreams, the sync_label is the MediaStream label and the
5244 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005245 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005246 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005247 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005248 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005249 continue;
5250 }
5251 // Set the SSRC the data channel should use for sending.
5252 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5253 existing_channels.push_back(data_channel_it->first);
5254 }
5255
5256 UpdateClosingRtpDataChannels(existing_channels, true);
5257}
5258
5259void PeerConnection::UpdateRemoteRtpDataChannels(
5260 const cricket::StreamParamsVec& streams) {
5261 std::vector<std::string> existing_channels;
5262
5263 // Find new and active data channels.
5264 for (const cricket::StreamParams& params : streams) {
5265 // The data channel label is either the mslabel or the SSRC if the mslabel
5266 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005267 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005268 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005269 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005270 auto data_channel_it = rtp_data_channels_.find(label);
5271 if (data_channel_it == rtp_data_channels_.end()) {
5272 // This is a new data channel.
5273 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5274 } else {
5275 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5276 }
5277 existing_channels.push_back(label);
5278 }
5279
5280 UpdateClosingRtpDataChannels(existing_channels, false);
5281}
5282
5283void PeerConnection::UpdateClosingRtpDataChannels(
5284 const std::vector<std::string>& active_channels,
5285 bool is_local_update) {
5286 auto it = rtp_data_channels_.begin();
5287 while (it != rtp_data_channels_.end()) {
5288 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005289 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005290 ++it;
5291 continue;
5292 }
5293
5294 if (is_local_update) {
5295 data_channel->SetSendSsrc(0);
5296 } else {
5297 data_channel->RemotePeerRequestClose();
5298 }
5299
5300 if (data_channel->state() == DataChannel::kClosed) {
5301 rtp_data_channels_.erase(it);
5302 it = rtp_data_channels_.begin();
5303 } else {
5304 ++it;
5305 }
5306 }
5307}
5308
5309void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5310 uint32_t remote_ssrc) {
5311 rtc::scoped_refptr<DataChannel> channel(
5312 InternalCreateDataChannel(label, nullptr));
5313 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005314 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005315 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005316 return;
5317 }
5318 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005319 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5320 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005321 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005322}
5323
5324rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5325 const std::string& label,
5326 const InternalDataChannelInit* config) {
5327 if (IsClosed()) {
5328 return nullptr;
5329 }
Steve Anton75737c02017-11-06 10:37:17 -08005330 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005331 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005332 << "InternalCreateDataChannel: Data is not supported in this call.";
5333 return nullptr;
5334 }
5335 InternalDataChannelInit new_config =
5336 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005337 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005338 if (new_config.id < 0) {
5339 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005340 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005341 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005342 RTC_LOG(LS_ERROR)
5343 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005344 return nullptr;
5345 }
5346 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005347 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005348 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005349 return nullptr;
5350 }
5351 }
5352
Steve Anton75737c02017-11-06 10:37:17 -08005353 rtc::scoped_refptr<DataChannel> channel(
5354 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005355 if (!channel) {
5356 sid_allocator_.ReleaseSid(new_config.id);
5357 return nullptr;
5358 }
5359
5360 if (channel->data_channel_type() == cricket::DCT_RTP) {
5361 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005362 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5363 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005364 return nullptr;
5365 }
5366 rtp_data_channels_[channel->label()] = channel;
5367 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005368 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005369 sctp_data_channels_.push_back(channel);
5370 channel->SignalClosed.connect(this,
5371 &PeerConnection::OnSctpDataChannelClosed);
5372 }
5373
Steve Anton2d8609c2018-01-23 16:38:46 -08005374 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005375 return channel;
5376}
5377
5378bool PeerConnection::HasDataChannels() const {
5379 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5380}
5381
5382void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005383 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005384 for (const auto& channel : sctp_data_channels_) {
5385 if (channel->id() < 0) {
5386 int sid;
5387 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005388 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5389 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005390 continue;
5391 }
5392 channel->SetSctpSid(sid);
5393 }
5394 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005395 // Since closing modifies the list of channels, we have to do the actual
5396 // closing outside the loop.
5397 for (const auto& channel : channels_to_close) {
5398 channel->CloseAbruptly();
5399 }
deadbeefab9b2d12015-10-14 11:33:11 -07005400}
5401
5402void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005403 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005404 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5405 ++it) {
5406 if (it->get() == channel) {
5407 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005408 // After the closing procedure is done, it's safe to use this ID for
5409 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005410 sid_allocator_.ReleaseSid(channel->id());
5411 }
deadbeefbd292462015-12-14 18:15:29 -08005412 // Since this method is triggered by a signal from the DataChannel,
5413 // we can't free it directly here; we need to free it asynchronously.
5414 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005415 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005416 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5417 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005418 return;
5419 }
5420 }
5421}
5422
deadbeefab9b2d12015-10-14 11:33:11 -07005423void PeerConnection::OnDataChannelDestroyed() {
5424 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5425 // DataChannel may callback to us and try to modify the list.
5426 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5427 temp_rtp_dcs.swap(rtp_data_channels_);
5428 for (const auto& kv : temp_rtp_dcs) {
5429 kv.second->OnTransportChannelDestroyed();
5430 }
5431
5432 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5433 temp_sctp_dcs.swap(sctp_data_channels_);
5434 for (const auto& channel : temp_sctp_dcs) {
5435 channel->OnTransportChannelDestroyed();
5436 }
5437}
5438
5439void PeerConnection::OnDataChannelOpenMessage(
5440 const std::string& label,
5441 const InternalDataChannelInit& config) {
5442 rtc::scoped_refptr<DataChannel> channel(
5443 InternalCreateDataChannel(label, &config));
5444 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005445 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005446 return;
5447 }
5448
deadbeefa601f5c2016-06-06 14:27:39 -07005449 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5450 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005451 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005452 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005453}
5454
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005455bool PeerConnection::HandleOpenMessage_s(
5456 const cricket::ReceiveDataParams& params,
5457 const rtc::CopyOnWriteBuffer& buffer) {
5458 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5459 // Received OPEN message; parse and signal that a new data channel should
5460 // be created.
5461 std::string label;
5462 InternalDataChannelInit config;
5463 config.id = params.ssrc;
5464 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5465 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5466 << params.ssrc;
5467 return true;
5468 }
5469 config.open_handshake_role = InternalDataChannelInit::kAcker;
5470 OnDataChannelOpenMessage(label, config);
5471 return true;
5472 }
5473 return false;
5474}
5475
Steve Anton4171afb2017-11-20 10:20:22 -08005476rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5477PeerConnection::GetAudioTransceiver() const {
5478 // This method only works with Plan B SDP, where there is a single
5479 // audio/video transceiver.
5480 RTC_DCHECK(!IsUnifiedPlan());
5481 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005482 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005483 return transceiver;
5484 }
5485 }
5486 RTC_NOTREACHED();
5487 return nullptr;
5488}
5489
5490rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5491PeerConnection::GetVideoTransceiver() const {
5492 // This method only works with Plan B SDP, where there is a single
5493 // audio/video transceiver.
5494 RTC_DCHECK(!IsUnifiedPlan());
5495 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005496 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005497 return transceiver;
5498 }
5499 }
5500 RTC_NOTREACHED();
5501 return nullptr;
5502}
5503
5504// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5505// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005506bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005507 switch (type) {
5508 case cricket::MEDIA_TYPE_AUDIO:
5509 return !GetAudioTransceiver()->internal()->senders().empty();
5510 case cricket::MEDIA_TYPE_VIDEO:
5511 return !GetVideoTransceiver()->internal()->senders().empty();
5512 case cricket::MEDIA_TYPE_DATA:
5513 return false;
5514 }
5515 RTC_NOTREACHED();
5516 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005517}
5518
Steve Anton4171afb2017-11-20 10:20:22 -08005519rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5520PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005521 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005522 for (auto sender : transceiver->internal()->senders()) {
5523 if (sender->track() == track) {
5524 return sender;
5525 }
5526 }
5527 }
5528 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005529}
5530
Steve Anton4171afb2017-11-20 10:20:22 -08005531rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5532PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005533 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005534 for (auto sender : transceiver->internal()->senders()) {
5535 if (sender->id() == sender_id) {
5536 return sender;
5537 }
5538 }
5539 }
5540 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005541}
5542
Steve Anton4171afb2017-11-20 10:20:22 -08005543rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5544PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005545 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005546 for (auto receiver : transceiver->internal()->receivers()) {
5547 if (receiver->id() == receiver_id) {
5548 return receiver;
5549 }
5550 }
5551 }
5552 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005553}
5554
Steve Anton4171afb2017-11-20 10:20:22 -08005555std::vector<PeerConnection::RtpSenderInfo>*
5556PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5557 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5558 media_type == cricket::MEDIA_TYPE_VIDEO);
5559 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5560 ? &remote_audio_sender_infos_
5561 : &remote_video_sender_infos_;
5562}
5563
5564std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005565 cricket::MediaType media_type) {
5566 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5567 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005568 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5569 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005570}
5571
Steve Anton4171afb2017-11-20 10:20:22 -08005572const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5573 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005574 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005575 const std::string sender_id) const {
5576 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005577 if (sender_info.stream_id == stream_id &&
5578 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005579 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005580 }
5581 }
5582 return nullptr;
5583}
5584
5585DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5586 for (const auto& channel : sctp_data_channels_) {
5587 if (channel->id() == sid) {
5588 return channel;
5589 }
5590 }
5591 return nullptr;
5592}
5593
Karl Wibergfb3be392019-03-22 14:13:22 +01005594PeerConnection::InitializePortAllocatorResult
5595PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005596 const cricket::ServerAddresses& stun_servers,
5597 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005598 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005599 RTC_DCHECK_RUN_ON(network_thread());
5600
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005601 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005602 // To handle both internal and externally created port allocator, we will
5603 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005604 int port_allocator_flags = port_allocator_->flags();
5605 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5606 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5607 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005608 // If the disable-IPv6 flag was specified, we'll not override it
5609 // by experiment.
5610 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005611 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005612 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5613 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005614 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005615 }
5616
zhihuangb09b3f92017-03-07 14:40:51 -08005617 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005618 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005619 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005620 }
5621
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005622 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005623 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005624 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005625 }
5626
honghaiz60347052016-05-31 18:29:12 -07005627 if (configuration.candidate_network_policy ==
5628 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005629 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005630 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005631 }
5632
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005633 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005634 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005635 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5636 }
5637
Karl Wibergfb3be392019-03-22 14:13:22 +01005638 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005639 // No step delay is used while allocating ports.
5640 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005641 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005642 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005643 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005644
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005645 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005646 for (auto& turn_server : turn_servers_copy) {
5647 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005648 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005649 // Call this last since it may create pooled allocator sessions using the
5650 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005651 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005652 stun_servers, std::move(turn_servers_copy),
5653 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5654 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005655 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005656
5657 InitializePortAllocatorResult res;
5658 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5659 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005660}
5661
deadbeef91dd5672016-05-18 16:55:30 -07005662bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005663 const cricket::ServerAddresses& stun_servers,
5664 const std::vector<cricket::RelayServerConfig>& turn_servers,
5665 IceTransportsType type,
5666 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005667 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005668 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005669 absl::optional<int> stun_candidate_keepalive_interval,
5670 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005671 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005672 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005673 // According to JSEP, after setLocalDescription, changing the candidate pool
5674 // size is not allowed, and changing the set of ICE servers will not result
5675 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005676 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005677 port_allocator_->FreezeCandidatePool();
5678 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005679 // Add the custom tls turn servers if they exist.
5680 auto turn_servers_copy = turn_servers;
5681 for (auto& turn_server : turn_servers_copy) {
5682 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5683 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005684 // Call this last since it may create pooled allocator sessions using the
5685 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005686 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005687 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5688 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005689}
5690
Steve Antonba818672017-11-06 10:21:57 -08005691cricket::ChannelManager* PeerConnection::channel_manager() const {
5692 return factory_->channel_manager();
5693}
5694
Elad Alon99c3fe52017-10-13 16:29:40 +02005695bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005696 std::unique_ptr<RtcEventLogOutput> output,
5697 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005698 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005699 if (!event_log_) {
5700 return false;
5701 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005702 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005703}
5704
5705void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005706 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005707 if (event_log_) {
5708 event_log_->StopLogging();
5709 }
ivoc14d5dbe2016-07-04 07:06:55 -07005710}
nisseeaabdf62017-05-05 02:23:02 -07005711
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005712cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005713 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005714 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005715 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005716 if (channel && channel->content_name() == content_name) {
5717 return channel;
5718 }
Steve Anton75737c02017-11-06 10:37:17 -08005719 }
5720 if (rtp_data_channel() &&
5721 rtp_data_channel()->content_name() == content_name) {
5722 return rtp_data_channel();
5723 }
5724 return nullptr;
5725}
5726
5727bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005728 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005729 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005730 RTC_LOG(LS_INFO)
5731 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005732 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005733 return false;
5734 }
Qingsi Wang437077d2019-09-10 17:52:26 +00005735 if (!sctp_transport_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005736 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005737 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005738 return false;
5739 }
5740
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005741 absl::optional<rtc::SSLRole> dtls_role;
Qingsi Wang437077d2019-09-10 17:52:26 +00005742 if (sctp_mid_ && sctp_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005743 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Qingsi Wang437077d2019-09-10 17:52:26 +00005744 } else if (is_caller_) {
5745 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5746 }
5747 if (dtls_role) {
Zhi Huange830e682018-03-30 10:48:35 -07005748 *role = *dtls_role;
5749 return true;
5750 }
5751 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005752}
5753
5754bool PeerConnection::GetSslRole(const std::string& content_name,
5755 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005756 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005757 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005758 RTC_LOG(LS_INFO)
5759 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005760 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005761 return false;
5762 }
5763
Zhi Huange830e682018-03-30 10:48:35 -07005764 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5765 if (dtls_role) {
5766 *role = *dtls_role;
5767 return true;
5768 }
5769 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005770}
5771
Steve Antonf8470812017-12-04 10:46:21 -08005772void PeerConnection::SetSessionError(SessionError error,
5773 const std::string& error_desc) {
5774 RTC_DCHECK_RUN_ON(signaling_thread());
5775 if (error != session_error_) {
5776 session_error_ = error;
5777 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005778 }
5779}
5780
Zhi Huange830e682018-03-30 10:48:35 -07005781RTCError PeerConnection::UpdateSessionState(
5782 SdpType type,
5783 cricket::ContentSource source,
5784 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005785 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005786
5787 // If there's already a pending error then no state transition should happen.
5788 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005789 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005790
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005791 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005792 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005793 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005794 }
5795
5796 // Update the signaling state according to the specified state machine (see
5797 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005798 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005799 ChangeSignalingState(source == cricket::CS_LOCAL
5800 ? PeerConnectionInterface::kHaveLocalOffer
5801 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005802 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005803 ChangeSignalingState(source == cricket::CS_LOCAL
5804 ? PeerConnectionInterface::kHaveLocalPrAnswer
5805 : PeerConnectionInterface::kHaveRemotePrAnswer);
5806 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005807 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005808 ChangeSignalingState(PeerConnectionInterface::kStable);
5809 }
5810
5811 // Update internal objects according to the session description's media
5812 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005813 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005814 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005815 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005816 }
5817
Steve Anton8a006912017-12-04 15:25:56 -08005818 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005819}
5820
Steve Anton8a006912017-12-04 15:25:56 -08005821RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005822 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005823 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005824 const SessionDescriptionInterface* sdesc =
5825 (source == cricket::CS_LOCAL ? local_description()
5826 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005827 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005828
5829 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005830 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005831 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005832 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005833 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005834 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005835 continue;
5836 }
5837 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005838 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005839 if (!content_desc) {
5840 continue;
5841 }
5842 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005843 bool success = (source == cricket::CS_LOCAL)
5844 ? channel->SetLocalContent(content_desc, type, &error)
5845 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005846 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005847 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005848 }
5849 }
5850
5851 // If using the RtpDataChannel, push down the new SDP section for it too.
5852 if (rtp_data_channel_) {
5853 const ContentInfo* data_content =
5854 cricket::GetFirstDataContent(sdesc->description());
5855 if (data_content && !data_content->rejected) {
5856 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005857 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005858 if (data_desc) {
5859 std::string error;
5860 bool success =
5861 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005862 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005863 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005864 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005865 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005866 }
Steve Anton75737c02017-11-06 10:37:17 -08005867 }
5868 }
5869 }
Steve Antoned10bd92017-12-05 10:52:59 -08005870
Steve Anton75737c02017-11-06 10:37:17 -08005871 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5872 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Qingsi Wang437077d2019-09-10 17:52:26 +00005873 if (sctp_transport_ && local_description() && remote_description()) {
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005874 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5875 local_description()->description());
5876 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5877 remote_description()->description());
Qingsi Wang437077d2019-09-10 17:52:26 +00005878 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005879 int max_message_size;
5880 // A remote max message size of zero means "any size supported".
5881 // We configure the connection with our own max message size.
5882 if (remote_sctp_description->max_message_size() == 0) {
5883 max_message_size = local_sctp_description->max_message_size();
5884 } else {
5885 max_message_size =
5886 std::min(local_sctp_description->max_message_size(),
5887 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005888 }
Qingsi Wang437077d2019-09-10 17:52:26 +00005889 sctp_transport_->Start(local_sctp_description->port(),
5890 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005891 }
Steve Anton75737c02017-11-06 10:37:17 -08005892 }
Steve Antoned10bd92017-12-05 10:52:59 -08005893
Steve Anton8a006912017-12-04 15:25:56 -08005894 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005895}
5896
Steve Anton8a006912017-12-04 15:25:56 -08005897RTCError PeerConnection::PushdownTransportDescription(
5898 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005899 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005900 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005901
Zhi Huange830e682018-03-30 10:48:35 -07005902 if (source == cricket::CS_LOCAL) {
5903 const SessionDescriptionInterface* sdesc = local_description();
5904 RTC_DCHECK(sdesc);
5905 return transport_controller_->SetLocalDescription(type,
5906 sdesc->description());
5907 } else {
5908 const SessionDescriptionInterface* sdesc = remote_description();
5909 RTC_DCHECK(sdesc);
5910 return transport_controller_->SetRemoteDescription(type,
5911 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005912 }
Steve Anton75737c02017-11-06 10:37:17 -08005913}
5914
5915bool PeerConnection::GetTransportDescription(
5916 const SessionDescription* description,
5917 const std::string& content_name,
5918 cricket::TransportDescription* tdesc) {
5919 if (!description || !tdesc) {
5920 return false;
5921 }
5922 const TransportInfo* transport_info =
5923 description->GetTransportInfoByName(content_name);
5924 if (!transport_info) {
5925 return false;
5926 }
5927 *tdesc = transport_info->description;
5928 return true;
5929}
5930
Steve Anton75737c02017-11-06 10:37:17 -08005931cricket::IceConfig PeerConnection::ParseIceConfig(
5932 const PeerConnectionInterface::RTCConfiguration& config) const {
5933 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005934 switch (config.continual_gathering_policy) {
5935 case PeerConnectionInterface::GATHER_ONCE:
5936 gathering_policy = cricket::GATHER_ONCE;
5937 break;
5938 case PeerConnectionInterface::GATHER_CONTINUALLY:
5939 gathering_policy = cricket::GATHER_CONTINUALLY;
5940 break;
5941 default:
5942 RTC_NOTREACHED();
5943 gathering_policy = cricket::GATHER_ONCE;
5944 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005945
Steve Anton75737c02017-11-06 10:37:17 -08005946 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005947 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5948 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005949 ice_config.prioritize_most_likely_candidate_pairs =
5950 config.prioritize_most_likely_ice_candidate_pairs;
5951 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005952 RTCConfigurationToIceConfigOptionalInt(
5953 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005954 ice_config.continual_gathering_policy = gathering_policy;
5955 ice_config.presume_writable_when_fully_relayed =
5956 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005957 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5958 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005959 ice_config.ice_check_interval_strong_connectivity =
5960 config.ice_check_interval_strong_connectivity;
5961 ice_config.ice_check_interval_weak_connectivity =
5962 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005963 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005964 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5965 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005966 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005967 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005968 ice_config.regather_all_networks_interval_range =
5969 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005970 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005971 return ice_config;
5972}
5973
Steve Anton75737c02017-11-06 10:37:17 -08005974bool PeerConnection::SendData(const cricket::SendDataParams& params,
5975 const rtc::CopyOnWriteBuffer& payload,
5976 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005977 RTC_DCHECK_RUN_ON(signaling_thread());
Qingsi Wang437077d2019-09-10 17:52:26 +00005978 if (data_channel_transport_ && data_channel_transport_negotiated_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005979 SendDataParams send_params;
5980 send_params.type = ToWebrtcDataMessageType(params.type);
5981 send_params.ordered = params.ordered;
5982 if (params.max_rtx_count >= 0) {
5983 send_params.max_rtx_count = params.max_rtx_count;
5984 } else if (params.max_rtx_ms >= 0) {
5985 send_params.max_rtx_ms = params.max_rtx_ms;
5986 }
Qingsi Wang437077d2019-09-10 17:52:26 +00005987 return data_channel_transport_->SendData(params.sid, send_params, payload)
5988 .ok();
5989 } else if (sctp_transport_ && sctp_negotiated_) {
5990 return network_thread()->Invoke<bool>(
5991 RTC_FROM_HERE, Bind(&cricket::SctpTransportInternal::SendData,
5992 cricket_sctp_transport(), params, payload, result));
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005993 } else if (rtp_data_channel_) {
5994 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005995 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005996 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
5997 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005998}
5999
6000bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006001 RTC_DCHECK_RUN_ON(signaling_thread());
Qingsi Wang437077d2019-09-10 17:52:26 +00006002 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006003 // Don't log an error here, because DataChannels are expected to call
6004 // ConnectDataChannel in this state. It's the only way to initially tell
6005 // whether or not the underlying transport is ready.
6006 return false;
6007 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006008 if (data_channel_transport_) {
6009 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6010 &DataChannel::OnChannelReady);
6011 SignalDataChannelTransportReceivedData_s.connect(
6012 webrtc_data_channel, &DataChannel::OnDataReceived);
6013 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006014 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006015 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006016 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006017 }
6018 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006019 rtp_data_channel_->SignalReadyToSendData.connect(
6020 webrtc_data_channel, &DataChannel::OnChannelReady);
6021 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6022 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006023 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006024 if (sctp_transport_) {
6025 SignalSctpReadyToSendData.connect(webrtc_data_channel,
6026 &DataChannel::OnChannelReady);
6027 SignalSctpDataReceived.connect(webrtc_data_channel,
6028 &DataChannel::OnDataReceived);
6029 SignalSctpClosingProcedureStartedRemotely.connect(
6030 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
6031 SignalSctpClosingProcedureComplete.connect(
6032 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
6033 }
Steve Anton75737c02017-11-06 10:37:17 -08006034 return true;
6035}
6036
6037void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006038 RTC_DCHECK_RUN_ON(signaling_thread());
Qingsi Wang437077d2019-09-10 17:52:26 +00006039 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006040 RTC_LOG(LS_ERROR)
6041 << "DisconnectDataChannel called when rtp_data_channel_ and "
6042 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006043 return;
6044 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006045 if (data_channel_transport_) {
6046 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6047 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6048 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6049 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6050 }
6051 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006052 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6053 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006054 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006055 if (sctp_transport_) {
6056 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
6057 SignalSctpDataReceived.disconnect(webrtc_data_channel);
6058 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
6059 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
6060 }
Steve Anton75737c02017-11-06 10:37:17 -08006061}
6062
6063void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006064 if (data_channel_transport_) {
Qingsi Wang437077d2019-09-10 17:52:26 +00006065 data_channel_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006066 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006067 if (!sctp_transport_) {
6068 RTC_LOG(LS_ERROR)
6069 << "AddSctpDataStream called when sctp_transport_ is NULL.";
6070 return;
6071 }
6072 network_thread()->Invoke<void>(
6073 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
6074 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006075}
6076
6077void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006078 if (data_channel_transport_) {
Qingsi Wang437077d2019-09-10 17:52:26 +00006079 data_channel_transport_->CloseChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006080 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006081 if (!sctp_transport_) {
6082 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
6083 "NULL.";
6084 return;
6085 }
6086 network_thread()->Invoke<void>(
6087 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
6088 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006089}
6090
6091bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006092 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006093 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Qingsi Wang437077d2019-09-10 17:52:26 +00006094 (data_channel_transport_ && data_channel_transport_ready_to_send_ &&
6095 data_channel_transport_negotiated_) ||
6096 (sctp_ready_to_send_data_ && sctp_negotiated_);
Steve Anton75737c02017-11-06 10:37:17 -08006097}
6098
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006099void PeerConnection::OnDataReceived(int channel_id,
6100 DataMessageType type,
6101 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006102 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006103 cricket::ReceiveDataParams params;
6104 params.sid = channel_id;
6105 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006106 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006107 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6108 RTC_DCHECK_RUN_ON(signaling_thread());
6109 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006110 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006111 }
6112 });
6113}
6114
6115void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006116 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006117 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006118 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6119 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006120 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006121 });
6122}
6123
6124void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006125 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006126 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006127 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6128 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006129 SignalDataChannelTransportChannelClosed_s(channel_id);
6130 });
6131}
6132
6133void PeerConnection::OnReadyToSend() {
6134 RTC_DCHECK_RUN_ON(network_thread());
6135 data_channel_transport_invoker_->AsyncInvoke<void>(
6136 RTC_FROM_HERE, signaling_thread(), [this] {
6137 RTC_DCHECK_RUN_ON(signaling_thread());
6138 data_channel_transport_ready_to_send_ = true;
Qingsi Wang437077d2019-09-10 17:52:26 +00006139 if (data_channel_transport_negotiated_) {
6140 SignalDataChannelTransportWritable_s(
6141 data_channel_transport_ready_to_send_);
6142 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006143 });
6144}
6145
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006146absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006147 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006148 if (sctp_mid_ && transport_controller_) {
6149 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6150 if (dtls_transport) {
6151 return dtls_transport->transport_name();
6152 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006153 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006154 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006155 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006156}
6157
Qingsi Wang72a43a12018-02-20 16:03:18 -08006158cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6159 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006160 network_thread()->Invoke<void>(
6161 RTC_FROM_HERE,
6162 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6163 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006164 return candidate_states_list;
6165}
6166
Steve Anton5dfde182018-02-06 10:34:40 -08006167std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6168 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006169 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006170 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006171 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006172 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006173 if (channel) {
6174 transport_names_by_mid[channel->content_name()] =
6175 channel->transport_name();
6176 }
Steve Anton75737c02017-11-06 10:37:17 -08006177 }
Steve Anton5dfde182018-02-06 10:34:40 -08006178 if (rtp_data_channel_) {
6179 transport_names_by_mid[rtp_data_channel_->content_name()] =
6180 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006181 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006182 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006183 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006184 RTC_DCHECK(transport_name);
6185 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006186 }
Steve Anton5dfde182018-02-06 10:34:40 -08006187 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006188}
6189
Steve Anton5dfde182018-02-06 10:34:40 -08006190std::map<std::string, cricket::TransportStats>
6191PeerConnection::GetTransportStatsByNames(
6192 const std::set<std::string>& transport_names) {
6193 if (!network_thread()->IsCurrent()) {
6194 return network_thread()
6195 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6196 RTC_FROM_HERE,
6197 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006198 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006199 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006200 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6201 for (const std::string& transport_name : transport_names) {
6202 cricket::TransportStats transport_stats;
6203 bool success =
6204 transport_controller_->GetStats(transport_name, &transport_stats);
6205 if (success) {
6206 transport_stats_by_name[transport_name] = std::move(transport_stats);
6207 } else {
6208 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6209 << transport_name;
6210 }
6211 }
6212 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006213}
6214
6215bool PeerConnection::GetLocalCertificate(
6216 const std::string& transport_name,
6217 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006218 if (!certificate) {
6219 return false;
6220 }
6221 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6222 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006223}
6224
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006225std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006226 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006227 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006228}
6229
6230cricket::DataChannelType PeerConnection::data_channel_type() const {
6231 return data_channel_type_;
6232}
6233
6234bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006235 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006236 return pending_ice_restarts_.find(content_name) !=
6237 pending_ice_restarts_.end();
6238}
6239
Steve Anton75737c02017-11-06 10:37:17 -08006240bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6241 return transport_controller_->NeedsIceRestart(content_name);
6242}
6243
6244void PeerConnection::OnCertificateReady(
6245 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6246 transport_controller_->SetLocalCertificate(certificate);
6247}
6248
6249void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006250 SetSessionError(SessionError::kTransport,
6251 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006252}
6253
Alex Loiko9289eda2018-11-23 16:18:59 +00006254void PeerConnection::OnTransportControllerConnectionState(
6255 cricket::IceConnectionState state) {
6256 switch (state) {
6257 case cricket::kIceConnectionConnecting:
6258 // If the current state is Connected or Completed, then there were
6259 // writable channels but now there are not, so the next state must
6260 // be Disconnected.
6261 // kIceConnectionConnecting is currently used as the default,
6262 // un-connected state by the TransportController, so its only use is
6263 // detecting disconnections.
6264 if (ice_connection_state_ ==
6265 PeerConnectionInterface::kIceConnectionConnected ||
6266 ice_connection_state_ ==
6267 PeerConnectionInterface::kIceConnectionCompleted) {
6268 SetIceConnectionState(
6269 PeerConnectionInterface::kIceConnectionDisconnected);
6270 }
6271 break;
6272 case cricket::kIceConnectionFailed:
6273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6274 break;
6275 case cricket::kIceConnectionConnected:
6276 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6277 "all transports are writable.";
6278 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6279 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6280 break;
6281 case cricket::kIceConnectionCompleted:
6282 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6283 "all transports are complete.";
6284 if (ice_connection_state_ !=
6285 PeerConnectionInterface::kIceConnectionConnected) {
6286 // If jumping directly from "checking" to "connected",
6287 // signal "connected" first.
6288 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6289 }
6290 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6291 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6292 ReportTransportStats();
6293 break;
6294 default:
6295 RTC_NOTREACHED();
6296 }
6297}
6298
Steve Anton75737c02017-11-06 10:37:17 -08006299void PeerConnection::OnTransportControllerCandidatesGathered(
6300 const std::string& transport_name,
6301 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006302 int sdp_mline_index;
6303 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006304 RTC_LOG(LS_ERROR)
6305 << "OnTransportControllerCandidatesGathered: content name "
6306 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006307 return;
6308 }
6309
6310 for (cricket::Candidates::const_iterator citer = candidates.begin();
6311 citer != candidates.end(); ++citer) {
6312 // Use transport_name as the candidate media id.
6313 std::unique_ptr<JsepIceCandidate> candidate(
6314 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6315 if (local_description()) {
6316 mutable_local_description()->AddCandidate(candidate.get());
6317 }
6318 OnIceCandidate(std::move(candidate));
6319 }
6320}
6321
Eldar Relloda13ea22019-06-01 12:23:43 +03006322void PeerConnection::OnTransportControllerCandidateError(
6323 const cricket::IceCandidateErrorEvent& event) {
6324 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6325 event.error_text);
6326}
6327
Steve Anton75737c02017-11-06 10:37:17 -08006328void PeerConnection::OnTransportControllerCandidatesRemoved(
6329 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006330 // Sanity check.
6331 for (const cricket::Candidate& candidate : candidates) {
6332 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006333 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006334 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006335 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006336 return;
6337 }
6338 }
6339
6340 if (local_description()) {
6341 mutable_local_description()->RemoveCandidates(candidates);
6342 }
6343 OnIceCandidatesRemoved(candidates);
6344}
6345
Alex Drake00c7ecf2019-08-06 10:54:47 -07006346void PeerConnection::OnTransportControllerCandidateChanged(
6347 const cricket::CandidatePairChangeEvent& event) {
6348 OnSelectedCandidatePairChanged(event);
6349}
6350
Steve Anton75737c02017-11-06 10:37:17 -08006351void PeerConnection::OnTransportControllerDtlsHandshakeError(
6352 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006353 RTC_HISTOGRAM_ENUMERATION(
6354 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6355 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006356}
6357
Steve Antoned10bd92017-12-05 10:52:59 -08006358void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006359 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006360 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006361 if (channel && !channel->enabled()) {
6362 channel->Enable(true);
6363 }
Steve Anton75737c02017-11-06 10:37:17 -08006364 }
6365
Steve Anton4171afb2017-11-20 10:20:22 -08006366 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006367 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006368 }
Steve Anton75737c02017-11-06 10:37:17 -08006369}
6370
6371// Returns the media index for a local ice candidate given the content name.
6372bool PeerConnection::GetLocalCandidateMediaIndex(
6373 const std::string& content_name,
6374 int* sdp_mline_index) {
6375 if (!local_description() || !sdp_mline_index) {
6376 return false;
6377 }
6378
6379 bool content_found = false;
6380 const ContentInfos& contents = local_description()->description()->contents();
6381 for (size_t index = 0; index < contents.size(); ++index) {
6382 if (contents[index].name == content_name) {
6383 *sdp_mline_index = static_cast<int>(index);
6384 content_found = true;
6385 break;
6386 }
6387 }
6388 return content_found;
6389}
6390
6391bool PeerConnection::UseCandidatesInSessionDescription(
6392 const SessionDescriptionInterface* remote_desc) {
6393 if (!remote_desc) {
6394 return true;
6395 }
6396 bool ret = true;
6397
6398 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6399 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6400 for (size_t n = 0; n < candidates->count(); ++n) {
6401 const IceCandidateInterface* candidate = candidates->at(n);
6402 bool valid = false;
6403 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6404 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006405 RTC_LOG(LS_INFO)
6406 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006407 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006408 }
6409 continue;
6410 }
6411 ret = UseCandidate(candidate);
6412 if (!ret) {
6413 break;
6414 }
6415 }
6416 }
6417 return ret;
6418}
6419
6420bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006421 RTCErrorOr<const cricket::ContentInfo*> result =
6422 FindContentInfo(remote_description(), candidate);
6423 if (!result.ok()) {
6424 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6425 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006426 return false;
6427 }
Steve Anton75737c02017-11-06 10:37:17 -08006428 std::vector<cricket::Candidate> candidates;
6429 candidates.push_back(candidate->candidate());
6430 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006431 RTCError error = transport_controller_->AddRemoteCandidates(
6432 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006433 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006434 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006435 // Candidates successfully submitted for checking.
6436 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6437 ice_connection_state_ ==
6438 PeerConnectionInterface::kIceConnectionDisconnected) {
6439 // If state is New, then the session has just gotten its first remote ICE
6440 // candidates, so go to Checking.
6441 // If state is Disconnected, the session is re-using old candidates or
6442 // receiving additional ones, so go to Checking.
6443 // If state is Connected, stay Connected.
6444 // TODO(bemasc): If state is Connected, and the new candidates are for a
6445 // newly added transport, then the state actually _should_ move to
6446 // checking. Add a way to distinguish that case.
6447 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6448 }
6449 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006450 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006451 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006452 }
6453 return true;
6454}
6455
Guido Urdaneta41633172019-05-23 20:12:29 +02006456RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6457 const SessionDescriptionInterface* description,
6458 const IceCandidateInterface* candidate) {
6459 if (candidate->sdp_mline_index() >= 0) {
6460 size_t mediacontent_index =
6461 static_cast<size_t>(candidate->sdp_mline_index());
6462 size_t content_size = description->description()->contents().size();
6463 if (mediacontent_index < content_size) {
6464 return &description->description()->contents()[mediacontent_index];
6465 } else {
6466 return RTCError(RTCErrorType::INVALID_RANGE,
6467 "Media line index (" +
6468 rtc::ToString(candidate->sdp_mline_index()) +
6469 ") out of range (number of mlines: " +
6470 rtc::ToString(content_size) + ").");
6471 }
6472 } else if (!candidate->sdp_mid().empty()) {
6473 auto& contents = description->description()->contents();
6474 auto it = absl::c_find_if(
6475 contents, [candidate](const cricket::ContentInfo& content_info) {
6476 return content_info.mid() == candidate->sdp_mid();
6477 });
6478 if (it == contents.end()) {
6479 return RTCError(
6480 RTCErrorType::INVALID_PARAMETER,
6481 "Mid " + candidate->sdp_mid() +
6482 " specified but no media section with that mid found.");
6483 } else {
6484 return &*it;
6485 }
6486 }
6487
6488 return RTCError(RTCErrorType::INVALID_PARAMETER,
6489 "Neither sdp_mline_index nor sdp_mid specified.");
6490}
6491
Steve Anton75737c02017-11-06 10:37:17 -08006492void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006493 // Destroy video channel first since it may have a pointer to the
6494 // voice channel.
6495 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006496 if (!video_info || video_info->rejected) {
6497 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006498 }
6499
Steve Anton6fec8802017-12-04 10:37:29 -08006500 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6501 if (!audio_info || audio_info->rejected) {
6502 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006503 }
6504
6505 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6506 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006507 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006508 }
6509}
6510
Steve Antondcc3c022017-12-22 16:02:54 -08006511RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6512 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006513 const cricket::ContentGroup* bundle_group = nullptr;
6514 if (configuration_.bundle_policy ==
6515 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006516 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006517 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6519 "max-bundle configured but session description "
6520 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006521 }
6522 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006523 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006524}
6525
6526RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006527 // Creating the media channels. Transports should already have been created
6528 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006529 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006530 if (voice && !voice->rejected &&
6531 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006532 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006533 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006534 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6535 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006536 }
6537 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6538 }
6539
Steve Antondcc3c022017-12-22 16:02:54 -08006540 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006541 if (video && !video->rejected &&
6542 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006543 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006544 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006545 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6546 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006547 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006548 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006549 }
6550
Steve Antondcc3c022017-12-22 16:02:54 -08006551 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006552 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Qingsi Wang437077d2019-09-10 17:52:26 +00006553 !rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006554 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006555 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6556 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006557 }
6558 }
6559
Steve Anton8a006912017-12-04 15:25:56 -08006560 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006561}
6562
Steve Anton4171afb2017-11-20 10:20:22 -08006563// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006564cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006565 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006566 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006567 MediaTransportConfig media_transport_config =
6568 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006569
Steve Anton75737c02017-11-06 10:37:17 -08006570 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006571 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006572 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6573 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006574 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006575 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006576 }
Steve Anton75737c02017-11-06 10:37:17 -08006577 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6578 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006579 voice_channel->SignalSentPacket.connect(this,
6580 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006581 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006582
Steve Antoneda6ccd2017-12-04 10:21:55 -08006583 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006584}
6585
Steve Anton4171afb2017-11-20 10:20:22 -08006586// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006587cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006588 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006589 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006590 MediaTransportConfig media_transport_config =
6591 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006592
Steve Anton75737c02017-11-06 10:37:17 -08006593 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006594 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006595 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6596 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006597 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006598 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006599 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006600 }
Steve Anton75737c02017-11-06 10:37:17 -08006601 video_channel->SignalDtlsSrtpSetupFailure.connect(
6602 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006603 video_channel->SignalSentPacket.connect(this,
6604 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006605 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006606
Steve Antoneda6ccd2017-12-04 10:21:55 -08006607 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006608}
6609
Zhi Huange830e682018-03-30 10:48:35 -07006610bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006611 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006612 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006613 // Only using SCTP transport. No more setup required. Since SCTP is
6614 // the only option, it doesn't need to wait for negotiation.
6615 sctp_negotiated_ = true;
6616 if (!CreateSctpDataChannel(mid)) {
Henrik Boström8b14b0d2019-08-30 12:31:06 +00006617 return false;
6618 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006619 break;
6620 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
6621 // Setup a data channel transport with SCTP as a fallback. Which one is
6622 // used will be determined later in negotiation.
6623 if (!CreateSctpDataChannel(mid)) {
6624 return false;
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006625 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006626 if (!SetupDataChannelTransport(mid)) {
6627 return false;
6628 }
6629 break;
6630 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6631 case cricket::DCT_MEDIA_TRANSPORT:
6632 // Using data channel transport without a fallback. It is the only
6633 // option. Data channel transport doesn't need to be negotiated.
6634 data_channel_transport_negotiated_ = true;
6635 if (!SetupDataChannelTransport(mid)) {
6636 return false;
6637 }
6638 break;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006639 case cricket::DCT_RTP:
6640 default:
6641 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6642 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6643 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006644 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006645 if (!rtp_data_channel_) {
6646 return false;
6647 }
6648 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6649 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6650 rtp_data_channel_->SignalSentPacket.connect(
6651 this, &PeerConnection::OnSentPacket_w);
6652 rtp_data_channel_->SetRtpTransport(rtp_transport);
6653 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006654 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006655
6656 // All non-RTP data channels must initialize |sctp_data_channels_|.
6657 for (const auto& channel : sctp_data_channels_) {
6658 channel->OnTransportChannelCreated();
6659 }
6660 return true;
6661}
6662
6663bool PeerConnection::CreateSctpDataChannel(const std::string& mid) {
6664 if (!sctp_factory_) {
6665 RTC_LOG(LS_ERROR)
6666 << "Trying to create SCTP transport, but didn't compile with "
6667 "SCTP support (HAVE_SCTP)";
6668 return false;
6669 }
6670 if (!network_thread()->Invoke<bool>(
6671 RTC_FROM_HERE,
6672 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6673 return false;
6674 }
6675 return true;
6676}
6677
6678bool PeerConnection::SetupDataChannelTransport(const std::string& mid) {
6679 if (!network_thread()->Invoke<bool>(
6680 RTC_FROM_HERE,
6681 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this, mid))) {
6682 return false;
6683 }
6684 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006685}
6686
6687Call::Stats PeerConnection::GetCallStats() {
6688 if (!worker_thread()->IsCurrent()) {
6689 return worker_thread()->Invoke<Call::Stats>(
6690 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6691 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006692 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006693 if (call_) {
6694 return call_->GetStats();
6695 } else {
6696 return Call::Stats();
6697 }
6698}
6699
Qingsi Wang437077d2019-09-10 17:52:26 +00006700bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
6701 RTC_DCHECK_RUN_ON(network_thread());
6702 RTC_DCHECK(sctp_factory_);
6703 RTC_LOG(LS_INFO) << "Creating SCTP transport for mid=" << mid;
6704
6705 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6706 transport_controller_->LookupDtlsTransportByMid(mid);
6707 cricket::DtlsTransportInternal* dtls_transport =
6708 webrtc_dtls_transport->internal();
6709 RTC_DCHECK(dtls_transport);
6710 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6711 sctp_factory_->CreateSctpTransport(dtls_transport);
6712 RTC_DCHECK(cricket_sctp_transport);
6713 sctp_invoker_.reset(new rtc::AsyncInvoker());
6714 cricket_sctp_transport->SignalReadyToSendData.connect(
6715 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6716 cricket_sctp_transport->SignalDataReceived.connect(
6717 this, &PeerConnection::OnSctpTransportDataReceived_n);
6718 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6719 // another thread. Would be nice if there was a helper class similar to
6720 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6721 // code.
6722 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
6723 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6724 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
6725 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
6726 sctp_mid_ = mid;
6727 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6728 std::move(cricket_sctp_transport));
6729 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
6730 return true;
6731}
6732
6733void PeerConnection::DestroySctpTransport_n() {
6734 RTC_DCHECK_RUN_ON(network_thread());
6735 RTC_LOG(LS_INFO) << "Destroying SCTP transport for mid=" << *sctp_mid_;
6736
6737 sctp_transport_->Clear();
6738 sctp_transport_ = nullptr;
6739 // |sctp_mid_| may still be active through a data channel transport. If not,
6740 // unset it.
6741 if (!data_channel_transport_) {
6742 sctp_mid_.reset();
6743 }
6744 sctp_invoker_.reset(nullptr);
6745}
6746
6747void PeerConnection::OnSctpTransportReadyToSendData_n() {
6748 RTC_DCHECK_RUN_ON(network_thread());
6749 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6750 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
6751 // Note: Cannot use rtc::Bind here because it will grab a reference to
6752 // PeerConnection and potentially cause PeerConnection to live longer than
6753 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6754 // be destroyed before PeerConnection is destroyed, and at that point all
6755 // pending tasks will be cleared.
6756 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6757 OnSctpTransportReadyToSendData_s(true);
6758 });
6759}
6760
6761void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6762 RTC_DCHECK_RUN_ON(signaling_thread());
6763 sctp_ready_to_send_data_ = ready;
6764 if (sctp_negotiated_) {
6765 SignalSctpReadyToSendData(ready);
6766 }
6767}
6768
6769void PeerConnection::OnSctpTransportDataReceived_n(
6770 const cricket::ReceiveDataParams& params,
6771 const rtc::CopyOnWriteBuffer& payload) {
6772 RTC_DCHECK_RUN_ON(network_thread());
6773 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6774 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
6775 // Note: Cannot use rtc::Bind here because it will grab a reference to
6776 // PeerConnection and potentially cause PeerConnection to live longer than
6777 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6778 // be destroyed before PeerConnection is destroyed, and at that point all
6779 // pending tasks will be cleared.
6780 sctp_invoker_->AsyncInvoke<void>(
6781 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6782 OnSctpTransportDataReceived_s(params, payload);
6783 });
6784}
6785
6786void PeerConnection::OnSctpTransportDataReceived_s(
6787 const cricket::ReceiveDataParams& params,
6788 const rtc::CopyOnWriteBuffer& payload) {
6789 RTC_DCHECK_RUN_ON(signaling_thread());
6790 if (!HandleOpenMessage_s(params, payload)) {
6791 SignalSctpDataReceived(params, payload);
6792 }
6793}
6794
6795void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
6796 RTC_DCHECK_RUN_ON(network_thread());
6797 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6798 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
6799 sctp_invoker_->AsyncInvoke<void>(
6800 RTC_FROM_HERE, signaling_thread(),
6801 rtc::Bind(&sigslot::signal1<int>::operator(),
6802 &SignalSctpClosingProcedureStartedRemotely, sid));
6803}
6804
6805void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6806 RTC_DCHECK_RUN_ON(network_thread());
6807 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6808 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
6809 sctp_invoker_->AsyncInvoke<void>(
6810 RTC_FROM_HERE, signaling_thread(),
6811 rtc::Bind(&sigslot::signal1<int>::operator(),
6812 &SignalSctpClosingProcedureComplete, sid));
6813}
6814
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006815bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Qingsi Wang437077d2019-09-10 17:52:26 +00006816 data_channel_transport_ = transport_controller_->GetDataChannelTransport(mid);
6817 if (!data_channel_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006818 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006819 << "Data channel transport is not available for data channels, mid="
6820 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006821 return false;
6822 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006823 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006824
Mirko Bonadei317a1f02019-09-17 17:06:18 +02006825 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Qingsi Wang437077d2019-09-10 17:52:26 +00006826 data_channel_transport_->SetDataSink(this);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006827 sctp_mid_ = mid;
6828 // TODO(mellem): Handling data channel state through media transport is
6829 // deprecated. Delete these lines when downstream implementations call
6830 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006831 transport_controller_->SignalMediaTransportStateChanged.connect(
6832 this, &PeerConnection::OnMediaTransportStateChanged_n);
6833 // Check the initial state right away, in case transport is already writable.
6834 OnMediaTransportStateChanged_n();
6835 return true;
6836}
6837
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006838void PeerConnection::TeardownDataChannelTransport_n() {
Qingsi Wang437077d2019-09-10 17:52:26 +00006839 if (!data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006840 return;
6841 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006842 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6843 << *sctp_mid_;
6844
6845 // TODO(mellem): Delete this line when downstream implementations call
6846 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006847 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006848 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6849 // it.
Qingsi Wang437077d2019-09-10 17:52:26 +00006850 if (!sctp_transport_) {
6851 sctp_mid_.reset();
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006852 }
Qingsi Wang437077d2019-09-10 17:52:26 +00006853 data_channel_transport_->SetDataSink(nullptr);
6854 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006855 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006856}
6857
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006858// TODO(mellem): Handling of data channel state through the media transport
6859// callback is deprecated. This function should be deleted once downstream
6860// implementations call DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006861void PeerConnection::OnMediaTransportStateChanged_n() {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006862 if (!sctp_mid_ || transport_controller_->GetMediaTransportState(*sctp_mid_) !=
6863 MediaTransportState::kWritable) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006864 return;
6865 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006866 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006867 RTC_FROM_HERE, signaling_thread(), [this] {
6868 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006869 data_channel_transport_ready_to_send_ = true;
Qingsi Wang437077d2019-09-10 17:52:26 +00006870 if (data_channel_transport_negotiated_) {
6871 SignalDataChannelTransportWritable_s(
6872 data_channel_transport_ready_to_send_);
6873 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006874 });
6875}
6876
Steve Anton75737c02017-11-06 10:37:17 -08006877// Returns false if bundle is enabled and rtcp_mux is disabled.
6878bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6879 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6880 if (!bundle_enabled)
6881 return true;
6882
6883 const cricket::ContentGroup* bundle_group =
6884 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6885 RTC_DCHECK(bundle_group != NULL);
6886
6887 const cricket::ContentInfos& contents = desc->contents();
6888 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6889 citer != contents.end(); ++citer) {
6890 const cricket::ContentInfo* content = (&*citer);
6891 RTC_DCHECK(content != NULL);
6892 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006893 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006894 if (!HasRtcpMuxEnabled(content))
6895 return false;
6896 }
6897 }
6898 // RTCP-MUX is enabled in all the contents.
6899 return true;
6900}
6901
6902bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006903 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006904}
6905
Steve Anton06817cd2018-12-18 15:55:30 -08006906static RTCError ValidateMids(const cricket::SessionDescription& description) {
6907 std::set<std::string> mids;
6908 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006909 if (content.name.empty()) {
6910 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6911 "A media section is missing a MID attribute.");
6912 }
Steve Anton06817cd2018-12-18 15:55:30 -08006913 if (!mids.insert(content.name).second) {
6914 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6915 "Duplicate a=mid value '" + content.name + "'.");
6916 }
6917 }
6918 return RTCError::OK();
6919}
6920
Steve Anton8a006912017-12-04 15:25:56 -08006921RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006922 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006923 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006924 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006925 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006926 }
6927
6928 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006929 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006930 }
6931
Steve Anton3828c062017-12-06 10:34:51 -08006932 SdpType type = sdesc->GetType();
6933 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6934 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006935 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006936 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006937 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006938 }
6939
Steve Anton06817cd2018-12-18 15:55:30 -08006940 RTCError error = ValidateMids(*sdesc->description());
6941 if (!error.ok()) {
6942 return error;
6943 }
6944
Steve Anton75737c02017-11-06 10:37:17 -08006945 // Verify crypto settings.
6946 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006947 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6948 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006949 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006950 if (!crypto_error.ok()) {
6951 return crypto_error;
6952 }
Steve Anton75737c02017-11-06 10:37:17 -08006953 }
6954
6955 // Verify ice-ufrag and ice-pwd.
6956 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006957 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6958 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006959 }
6960
6961 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006962 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6963 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006964 }
6965
6966 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6967 // m-lines that do not rtcp-mux enabled.
6968
6969 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006970 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006971 // With an answer we want to compare the new answer session description with
6972 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006973 const cricket::SessionDescription* offer_desc =
6974 (source == cricket::CS_LOCAL) ? remote_description()->description()
6975 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006976 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6977 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6978 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006979 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6980 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006981 }
6982 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006983 // The re-offers should respect the order of m= sections in current
6984 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006985 // With a re-offer, either the current local or current remote descriptions
6986 // could be the most up to date, so we would like to check against both of
6987 // them if they exist. It could be the case that one of them has a 0 port
6988 // for a media section, but the other does not. This is important to check
6989 // against in the case that we are recycling an m= section.
6990 const cricket::SessionDescription* current_desc = nullptr;
6991 const cricket::SessionDescription* secondary_current_desc = nullptr;
6992 if (local_description()) {
6993 current_desc = local_description()->description();
6994 if (remote_description()) {
6995 secondary_current_desc = remote_description()->description();
6996 }
6997 } else if (remote_description()) {
6998 current_desc = remote_description()->description();
6999 }
Steve Anton75737c02017-11-06 10:37:17 -08007000 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007001 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
7002 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007003 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7004 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08007005 }
7006 }
7007
Steve Antonba42e992018-04-09 14:10:01 -07007008 if (IsUnifiedPlan()) {
7009 // Ensure that each audio and video media section has at most one
7010 // "StreamParams". This will return an error if receiving a session
7011 // description from a "Plan B" endpoint which adds multiple tracks of the
7012 // same type. With Unified Plan, there can only be at most one track per
7013 // media section.
7014 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02007015 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07007016 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
7017 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
7018 desc.streams().size() > 1u) {
7019 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7020 "Media section has more than one track specified "
7021 "with a=ssrc lines which is not supported with "
7022 "Unified Plan.");
7023 }
7024 }
7025 }
7026
Steve Anton8a006912017-12-04 15:25:56 -08007027 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007028}
7029
Steve Anton3828c062017-12-06 10:34:51 -08007030bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007031 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007032 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007033 return (state == PeerConnectionInterface::kStable) ||
7034 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08007035 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007036 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007037 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7038 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7039 }
7040}
7041
Steve Anton3828c062017-12-06 10:34:51 -08007042bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007043 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007044 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007045 return (state == PeerConnectionInterface::kStable) ||
7046 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08007047 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007048 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007049 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7050 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7051 }
7052}
7053
Steve Antonf8470812017-12-04 10:46:21 -08007054const char* PeerConnection::SessionErrorToString(SessionError error) const {
7055 switch (error) {
7056 case SessionError::kNone:
7057 return "ERROR_NONE";
7058 case SessionError::kContent:
7059 return "ERROR_CONTENT";
7060 case SessionError::kTransport:
7061 return "ERROR_TRANSPORT";
7062 }
7063 RTC_NOTREACHED();
7064 return "";
7065}
7066
Steve Anton75737c02017-11-06 10:37:17 -08007067std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02007068 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08007069 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7070 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02007071 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08007072}
7073
Steve Anton8e20f172018-03-06 10:55:04 -08007074void PeerConnection::ReportSdpFormatReceived(
7075 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08007076 int num_audio_mlines = 0;
7077 int num_video_mlines = 0;
7078 int num_audio_tracks = 0;
7079 int num_video_tracks = 0;
7080 for (const ContentInfo& content : remote_offer.description()->contents()) {
7081 cricket::MediaType media_type = content.media_description()->type();
7082 int num_tracks = std::max(
7083 1, static_cast<int>(content.media_description()->streams().size()));
7084 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7085 num_audio_mlines += 1;
7086 num_audio_tracks += num_tracks;
7087 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7088 num_video_mlines += 1;
7089 num_video_tracks += num_tracks;
7090 }
7091 }
7092 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7093 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7094 format = kSdpFormatReceivedComplexUnifiedPlan;
7095 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7096 format = kSdpFormatReceivedComplexPlanB;
7097 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7098 format = kSdpFormatReceivedSimple;
7099 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007100 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7101 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007102}
7103
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007104void PeerConnection::ReportIceCandidateCollected(
7105 const cricket::Candidate& candidate) {
7106 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7107 if (candidate.address().IsPrivateIP()) {
7108 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7109 }
7110 if (candidate.address().IsUnresolvedIP()) {
7111 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7112 }
7113 if (candidate.address().family() == AF_INET6) {
7114 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7115 }
7116}
7117
7118void PeerConnection::ReportRemoteIceCandidateAdded(
7119 const cricket::Candidate& candidate) {
7120 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7121 if (candidate.address().IsPrivateIP()) {
7122 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7123 }
7124 if (candidate.address().IsUnresolvedIP()) {
7125 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7126 }
7127 if (candidate.address().family() == AF_INET6) {
7128 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7129 }
7130}
7131
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007132void PeerConnection::NoteUsageEvent(UsageEvent event) {
7133 RTC_DCHECK_RUN_ON(signaling_thread());
7134 usage_event_accumulator_ |= static_cast<int>(event);
7135}
7136
7137void PeerConnection::ReportUsagePattern() const {
7138 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007139 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7140 usage_event_accumulator_,
7141 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007142 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007143 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007144 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7145 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007146 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007147 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7148 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7149 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7150 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007151 // If called after close(), we can't report, because observer may have
7152 // been deallocated, and therefore pointer is null. Write to log instead.
7153 if (observer_) {
7154 Observer()->OnInterestingUsage(usage_event_accumulator_);
7155 } else {
7156 RTC_LOG(LS_INFO) << "Interesting usage signature "
7157 << usage_event_accumulator_
7158 << " observed after observer shutdown";
7159 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007160 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007161}
7162
Steve Anton0ffaaa22018-02-23 10:31:30 -08007163void PeerConnection::ReportNegotiatedSdpSemantics(
7164 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007165 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007166 switch (answer.description()->msid_signaling()) {
7167 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007168 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007169 break;
7170 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007171 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007172 break;
7173 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007174 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007175 break;
7176 case cricket::kMsidSignalingMediaSection |
7177 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007178 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007179 break;
7180 default:
7181 RTC_NOTREACHED();
7182 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007183 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7184 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007185}
7186
Steve Anton75737c02017-11-06 10:37:17 -08007187// We need to check the local/remote description for the Transport instead of
7188// the session, because a new Transport added during renegotiation may have
7189// them unset while the session has them set from the previous negotiation.
7190// Not doing so may trigger the auto generation of transport description and
7191// mess up DTLS identity information, ICE credential, etc.
7192bool PeerConnection::ReadyToUseRemoteCandidate(
7193 const IceCandidateInterface* candidate,
7194 const SessionDescriptionInterface* remote_desc,
7195 bool* valid) {
7196 *valid = true;
7197
7198 const SessionDescriptionInterface* current_remote_desc =
7199 remote_desc ? remote_desc : remote_description();
7200
7201 if (!current_remote_desc) {
7202 return false;
7203 }
7204
Guido Urdaneta41633172019-05-23 20:12:29 +02007205 RTCErrorOr<const cricket::ContentInfo*> result =
7206 FindContentInfo(current_remote_desc, candidate);
7207 if (!result.ok()) {
7208 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7209 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007210
7211 *valid = false;
7212 return false;
7213 }
7214
Guido Urdaneta41633172019-05-23 20:12:29 +02007215 std::string transport_name = GetTransportName(result.value()->name);
7216 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007217}
7218
7219bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007220 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007221 (dtls_enabled_ ||
7222 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007223}
7224
7225void PeerConnection::OnTransportControllerGatheringState(
7226 cricket::IceGatheringState state) {
7227 RTC_DCHECK(signaling_thread()->IsCurrent());
7228 if (state == cricket::kIceGatheringGathering) {
7229 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7230 } else if (state == cricket::kIceGatheringComplete) {
7231 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7232 }
7233}
7234
7235void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007236 std::map<std::string, std::set<cricket::MediaType>>
7237 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007238 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007239 if (transceiver->internal()->channel()) {
7240 const std::string& transport_name =
7241 transceiver->internal()->channel()->transport_name();
7242 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007243 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007244 }
Steve Anton75737c02017-11-06 10:37:17 -08007245 }
7246 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007247 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7248 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007249 }
Zhi Huange830e682018-03-30 10:48:35 -07007250
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007251 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007252 if (transport_name) {
7253 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007254 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007255 }
Zhi Huange830e682018-03-30 10:48:35 -07007256
Steve Antonc7b964c2018-02-01 14:39:45 -08007257 for (const auto& entry : media_types_by_transport_name) {
7258 const std::string& transport_name = entry.first;
7259 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007260 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007261 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007262 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007263 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007264 }
7265 }
7266}
7267// Walk through the ConnectionInfos to gather best connection usage
7268// for IPv4 and IPv6.
7269void PeerConnection::ReportBestConnectionState(
7270 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007271 for (const cricket::TransportChannelStats& channel_stats :
7272 stats.channel_stats) {
7273 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007274 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007275 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007276 continue;
7277 }
7278
Steve Antonc7b964c2018-02-01 14:39:45 -08007279 const cricket::Candidate& local = connection_info.local_candidate;
7280 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007281
7282 // Increment the counter for IceCandidatePairType.
7283 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7284 (local.type() == RELAY_PORT_TYPE &&
7285 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007286 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7287 GetIceCandidatePairCounter(local, remote),
7288 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007289 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007290 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7291 GetIceCandidatePairCounter(local, remote),
7292 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007293 } else {
7294 RTC_CHECK(0);
7295 }
Steve Anton75737c02017-11-06 10:37:17 -08007296
7297 // Increment the counter for IP type.
7298 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007299 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7300 kBestConnections_IPv4,
7301 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007302 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007303 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7304 kBestConnections_IPv6,
7305 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007306 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007307 RTC_CHECK(!local.address().hostname().empty() &&
7308 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007309 }
7310
7311 return;
7312 }
7313 }
7314}
7315
7316void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007317 const cricket::TransportStats& stats,
7318 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007319 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7320 return;
7321 }
7322
7323 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7324 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7325 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7326 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7327 return;
7328 }
7329
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007330 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7331 for (cricket::MediaType media_type : media_types) {
7332 switch (media_type) {
7333 case cricket::MEDIA_TYPE_AUDIO:
7334 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7335 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7336 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7337 break;
7338 case cricket::MEDIA_TYPE_VIDEO:
7339 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7340 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7341 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7342 break;
7343 case cricket::MEDIA_TYPE_DATA:
7344 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7345 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7346 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7347 break;
7348 default:
7349 RTC_NOTREACHED();
7350 continue;
7351 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007352 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007353 }
7354
7355 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7356 for (cricket::MediaType media_type : media_types) {
7357 switch (media_type) {
7358 case cricket::MEDIA_TYPE_AUDIO:
7359 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7360 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7361 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7362 break;
7363 case cricket::MEDIA_TYPE_VIDEO:
7364 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7365 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7366 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7367 break;
7368 case cricket::MEDIA_TYPE_DATA:
7369 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7370 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7371 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7372 break;
7373 default:
7374 RTC_NOTREACHED();
7375 continue;
7376 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007377 }
Steve Anton75737c02017-11-06 10:37:17 -08007378 }
7379}
7380
7381void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007382 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007383 RTC_DCHECK(call_);
7384 call_->OnSentPacket(sent_packet);
7385}
7386
7387const std::string PeerConnection::GetTransportName(
7388 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007389 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007390 if (channel) {
7391 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007392 }
Qingsi Wang437077d2019-09-10 17:52:26 +00007393 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007394 RTC_DCHECK(sctp_mid_);
7395 if (content_name == *sctp_mid_) {
7396 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007397 }
7398 }
7399 // Return an empty string if failed to retrieve the transport name.
7400 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007401}
7402
Steve Anton6fec8802017-12-04 10:37:29 -08007403void PeerConnection::DestroyTransceiverChannel(
7404 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7405 transceiver) {
7406 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007407
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007408 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007409 if (channel) {
7410 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007411 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007412 }
7413}
7414
7415void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007416 if (rtp_data_channel_) {
7417 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007418 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007419 rtp_data_channel_ = nullptr;
7420 }
7421
7422 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7423 // grab a reference to this PeerConnection. If this is called from the
7424 // PeerConnection destructor, the RefCountedObject vtable will have already
7425 // been destroyed (since it is a subclass of PeerConnection) and using
7426 // rtc::Bind will cause "Pure virtual function called" error to appear.
7427
Qingsi Wang437077d2019-09-10 17:52:26 +00007428 if (sctp_transport_) {
7429 OnDataChannelDestroyed();
7430 network_thread()->Invoke<void>(RTC_FROM_HERE,
7431 [this] { DestroySctpTransport_n(); });
7432 sctp_ready_to_send_data_ = false;
7433 }
7434
7435 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007436 OnDataChannelDestroyed();
7437 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7438 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007439 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007440 });
7441 }
Steve Anton6fec8802017-12-04 10:37:29 -08007442}
7443
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007444void PeerConnection::DestroyChannelInterface(
7445 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007446 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007447 switch (channel->media_type()) {
7448 case cricket::MEDIA_TYPE_AUDIO:
7449 channel_manager()->DestroyVoiceChannel(
7450 static_cast<cricket::VoiceChannel*>(channel));
7451 break;
7452 case cricket::MEDIA_TYPE_VIDEO:
7453 channel_manager()->DestroyVideoChannel(
7454 static_cast<cricket::VideoChannel*>(channel));
7455 break;
7456 case cricket::MEDIA_TYPE_DATA:
7457 channel_manager()->DestroyRtpDataChannel(
7458 static_cast<cricket::RtpDataChannel*>(channel));
7459 break;
7460 default:
7461 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7462 break;
7463 }
Zhi Huange830e682018-03-30 10:48:35 -07007464}
Steve Anton6fec8802017-12-04 10:37:29 -08007465
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007466bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007467 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007468 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007469 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007470 MediaTransportInterface* media_transport,
Qingsi Wang437077d2019-09-10 17:52:26 +00007471 DataChannelTransportInterface* data_channel_transport,
7472 JsepTransportController::NegotiationState negotiation_state) {
Karl Wibergac025892019-03-26 13:08:37 +01007473 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007474 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007475 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007476 auto base_channel = GetChannel(mid);
7477 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007478 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007479 }
Qingsi Wang437077d2019-09-10 17:52:26 +00007480 if (sctp_transport_ && mid == sctp_mid_) {
7481 sctp_transport_->SetDtlsTransport(dtls_transport);
7482 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007483
Karl Wiberg5966c502019-02-21 23:55:09 +01007484 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007485 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007486 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007487
Qingsi Wang437077d2019-09-10 17:52:26 +00007488 if (mid == sctp_mid_) {
7489 switch (negotiation_state) {
7490 case JsepTransportController::NegotiationState::kFinal:
7491 if (data_channel_transport) {
7492 if (sctp_transport_) {
7493 DestroySctpTransport_n();
7494 }
7495 } else {
7496 TeardownDataChannelTransport_n();
7497 }
7498 // We also need to mark the remaining transport as ready-to-send.
7499 RTC_FALLTHROUGH();
7500 case JsepTransportController::NegotiationState::kProvisional: {
7501 rtc::AsyncInvoker* invoker = data_channel_transport_invoker_
7502 ? data_channel_transport_invoker_.get()
7503 : sctp_invoker_.get();
7504 if (!invoker) {
7505 break; // Have neither SCTP nor DataChannelTransport, nothing to do.
7506 }
7507 invoker->AsyncInvoke<void>(
7508 RTC_FROM_HERE, signaling_thread(), [this, data_channel_transport] {
7509 RTC_DCHECK_RUN_ON(signaling_thread());
7510 if (data_channel_transport) {
7511 data_channel_transport_negotiated_ = true;
7512 if (data_channel_transport_ready_to_send_) {
7513 SignalDataChannelTransportWritable_s(
7514 data_channel_transport_ready_to_send_);
7515 }
7516 } else {
7517 sctp_negotiated_ = true;
7518 if (sctp_ready_to_send_data_) {
7519 SignalSctpReadyToSendData(sctp_ready_to_send_data_);
7520 }
7521 }
7522 });
7523 } break;
7524 case JsepTransportController::NegotiationState::kInitial:
7525 // Negotiation isn't finished. Nothing to do here.
7526 break;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007527 }
7528 }
7529
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007530 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007531}
7532
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007533void PeerConnection::OnSetStreams() {
7534 RTC_DCHECK_RUN_ON(signaling_thread());
7535 if (IsUnifiedPlan())
7536 UpdateNegotiationNeeded();
7537}
7538
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007539PeerConnectionObserver* PeerConnection::Observer() const {
7540 // In earlier production code, the pointer was not cleared on close,
7541 // which might have led to undefined behavior if the observer was not
7542 // deallocated, or strange crashes if it was.
7543 // We use CHECK in order to catch such behavior if it exists.
7544 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7545 RTC_CHECK(observer_);
7546 return observer_;
7547}
7548
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007549CryptoOptions PeerConnection::GetCryptoOptions() {
7550 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7551 // after it has been removed.
7552 return configuration_.crypto_options.has_value()
7553 ? *configuration_.crypto_options
7554 : factory_->options().crypto_options;
7555}
7556
Harald Alvestrand89061872018-01-02 14:08:34 +01007557void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007558 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007559 if (stats_collector_) {
7560 stats_collector_->ClearCachedStatsReport();
7561 }
7562}
7563
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007564void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007565 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7566 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007567}
7568
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007569void PeerConnection::UpdateNegotiationNeeded() {
7570 RTC_DCHECK_RUN_ON(signaling_thread());
7571 if (!IsUnifiedPlan()) {
7572 Observer()->OnRenegotiationNeeded();
7573 return;
7574 }
7575
7576 // If connection's [[IsClosed]] slot is true, abort these steps.
7577 if (IsClosed())
7578 return;
7579
7580 // If connection's signaling state is not "stable", abort these steps.
7581 if (signaling_state() != kStable)
7582 return;
7583
7584 // NOTE
7585 // The negotiation-needed flag will be updated once the state transitions to
7586 // "stable", as part of the steps for setting an RTCSessionDescription.
7587
7588 // If the result of checking if negotiation is needed is false, clear the
7589 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7590 // to false, and abort these steps.
7591 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7592 if (!is_negotiation_needed) {
7593 is_negotiation_needed_ = false;
7594 return;
7595 }
7596
7597 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7598 // steps.
7599 if (is_negotiation_needed_)
7600 return;
7601
7602 // Set connection's [[NegotiationNeeded]] slot to true.
7603 is_negotiation_needed_ = true;
7604
7605 // Queue a task that runs the following steps:
7606 // If connection's [[IsClosed]] slot is true, abort these steps.
7607 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7608 // Fire an event named negotiationneeded at connection.
7609 Observer()->OnRenegotiationNeeded();
7610}
7611
7612bool PeerConnection::CheckIfNegotiationIsNeeded() {
7613 RTC_DCHECK_RUN_ON(signaling_thread());
7614 // 1. If any implementation-specific negotiation is required, as described at
7615 // the start of this section, return true.
7616
Henrik Boström79b69802019-07-18 11:16:56 +02007617 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7618 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7619 return true;
7620 }
7621
7622 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007623 const SessionDescriptionInterface* description = current_local_description();
7624 if (!description)
7625 return true;
7626
Henrik Boström79b69802019-07-18 11:16:56 +02007627 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007628 // description has been negotiated yet for data, return true.
7629 if (!sctp_data_channels_.empty()) {
7630 if (!cricket::GetFirstDataContent(description->description()->contents()))
7631 return true;
7632 }
7633
Henrik Boström79b69802019-07-18 11:16:56 +02007634 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007635 // following checks:
7636 for (const auto& transceiver : transceivers_) {
7637 const ContentInfo* current_local_msection =
7638 FindTransceiverMSection(transceiver.get(), description);
7639
7640 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7641 transceiver.get(), current_remote_description());
7642
Henrik Boström79b69802019-07-18 11:16:56 +02007643 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007644 // but the associated m= section is not yet rejected in
7645 // connection.[[CurrentLocalDescription]] or
7646 // connection.[[CurrentRemoteDescription]], return true.
7647 if (transceiver->stopped()) {
7648 if (current_local_msection && !current_local_msection->rejected &&
7649 ((current_remote_msection && !current_remote_msection->rejected) ||
7650 !current_remote_msection)) {
7651 return true;
7652 }
7653 continue;
7654 }
7655
Henrik Boström79b69802019-07-18 11:16:56 +02007656 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007657 // section in description, return true.
7658 if (!current_local_msection)
7659 return true;
7660
7661 const MediaContentDescription* current_local_media_description =
7662 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007663 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007664 // in description then perform the following checks:
7665
Henrik Boström79b69802019-07-18 11:16:56 +02007666 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007667 // associated m= section in description either doesn't contain a single
7668 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7669 // m= section, or the MSID values themselves, differ from what is in
7670 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7671 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7672 if (current_local_media_description->streams().size() == 0)
7673 return true;
7674
7675 std::vector<std::string> msection_msids;
7676 for (const auto& stream : current_local_media_description->streams()) {
7677 for (const std::string& msid : stream.stream_ids())
7678 msection_msids.push_back(msid);
7679 }
7680
7681 std::vector<std::string> transceiver_msids =
7682 transceiver->sender()->stream_ids();
7683 if (msection_msids.size() != transceiver_msids.size())
7684 return true;
7685
7686 absl::c_sort(transceiver_msids);
7687 absl::c_sort(msection_msids);
7688 if (transceiver_msids != msection_msids)
7689 return true;
7690 }
7691
Henrik Boström79b69802019-07-18 11:16:56 +02007692 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007693 // associated m= section in neither connection.[[CurrentLocalDescription]]
7694 // nor connection.[[CurrentRemoteDescription]] matches
7695 // transceiver.[[Direction]], return true.
7696 if (description->GetType() == SdpType::kOffer) {
7697 if (!current_remote_description())
7698 return true;
7699
7700 if (!current_remote_msection)
7701 return true;
7702
7703 RtpTransceiverDirection current_local_direction =
7704 current_local_media_description->direction();
7705 RtpTransceiverDirection current_remote_direction =
7706 current_remote_msection->media_description()->direction();
7707 if (transceiver->direction() != current_local_direction &&
7708 transceiver->direction() !=
7709 RtpTransceiverDirectionReversed(current_remote_direction)) {
7710 return true;
7711 }
7712 }
7713
Henrik Boström79b69802019-07-18 11:16:56 +02007714 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007715 // associated m= section in the description does not match
7716 // transceiver.[[Direction]] intersected with the offered direction (as
7717 // described in [JSEP] (section 5.3.1.)), return true.
7718 if (description->GetType() == SdpType::kAnswer) {
7719 if (!remote_description())
7720 return true;
7721
7722 const ContentInfo* offered_remote_msection =
7723 FindTransceiverMSection(transceiver.get(), remote_description());
7724
7725 RtpTransceiverDirection offered_direction =
7726 offered_remote_msection
7727 ? offered_remote_msection->media_description()->direction()
7728 : RtpTransceiverDirection::kInactive;
7729
7730 if (current_local_media_description->direction() !=
7731 (RtpTransceiverDirectionIntersection(
7732 transceiver->direction(),
7733 RtpTransceiverDirectionReversed(offered_direction)))) {
7734 return true;
7735 }
7736 }
7737 }
7738
7739 // If all the preceding checks were performed and true was not returned,
7740 // nothing remains to be negotiated; return false.
7741 return false;
7742}
7743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007744} // namespace webrtc