blob: 927155928a0ea9b32286db674a772f57d31ae0bc [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>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.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
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800613cricket::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();
952 sctp_invoker_.reset();
953 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;
Karl Wibergb03ab712019-02-14 11:59:57 +01001080 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001081#if defined(ENABLE_EXTERNAL_AUTH)
1082 config.enable_external_auth = true;
1083#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001084 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001085
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001086 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001087 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001088 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001089 use_datagram_transport_for_data_channels_ =
1090 datagram_transport_data_channel_config_.enabled &&
1091 configuration.use_datagram_transport_for_data_channels.value_or(
1092 datagram_transport_data_channel_config_.default_value);
1093 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1094 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001095 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001096 if (!factory_->media_transport_factory()) {
1097 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001098 << "PeerConnecton is initialized with use_media_transport = true or "
1099 << "use_media_transport_for_data_channels = true "
1100 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001101 return false;
1102 }
1103
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001104 if (configuration.use_media_transport ||
1105 configuration.use_media_transport_for_data_channels) {
1106 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1107 // RTP media transport is introduced. But until then, we require SDES to
1108 // be enabled.
1109 if (configuration.enable_dtls_srtp.has_value() &&
1110 configuration.enable_dtls_srtp.value()) {
1111 RTC_LOG(LS_WARNING)
1112 << "When media transport is used, SDES must be enabled. Set "
1113 "configuration.enable_dtls_srtp to false. use_media_transport="
1114 << configuration.use_media_transport
1115 << ", use_media_transport_for_data_channels="
1116 << configuration.use_media_transport_for_data_channels;
1117 return false;
1118 }
1119 }
1120
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001121 config.use_media_transport_for_media = configuration.use_media_transport;
1122 config.use_media_transport_for_data_channels =
1123 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001124 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001125 config.use_datagram_transport_for_data_channels =
1126 use_datagram_transport_for_data_channels_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001127 config.media_transport_factory = factory_->media_transport_factory();
1128 }
1129
Zhi Huange830e682018-03-30 10:48:35 -07001130 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001131 signaling_thread(), network_thread(), port_allocator_.get(),
1132 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001133 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001134 this, &PeerConnection::OnTransportControllerConnectionState);
1135 transport_controller_->SignalStandardizedIceConnectionState.connect(
1136 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001137 transport_controller_->SignalConnectionState.connect(
1138 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001139 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001140 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001141 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001142 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001143 transport_controller_->SignalIceCandidateError.connect(
1144 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001145 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001146 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1147 transport_controller_->SignalDtlsHandshakeError.connect(
1148 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001149 transport_controller_->SignalIceCandidatePairChanged.connect(
1150 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001151
1152 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001153
deadbeefab9b2d12015-10-14 11:33:11 -07001154 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001155 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156
Steve Antonba818672017-11-06 10:21:57 -08001157 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001158 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001159
Steve Anton75737c02017-11-06 10:37:17 -08001160 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1161 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1162 if (!configuration.certificates.empty()) {
1163 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1164 // just picking the first one. The decision should be made based on the DTLS
1165 // handshake. The DTLS negotiations need to know about all certificates.
1166 certificate = configuration.certificates[0];
1167 }
1168
Steve Antond25da372017-11-06 14:50:29 -08001169 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001170
1171 if (options.disable_encryption) {
1172 dtls_enabled_ = false;
1173 } else {
1174 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001175 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001176 // |configuration| can override the default |dtls_enabled_| value.
1177 if (configuration.enable_dtls_srtp) {
1178 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1179 }
1180 }
1181
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001182 if (use_datagram_transport_for_data_channels_) {
1183 if (configuration.enable_rtp_data_channel) {
1184 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1185 "use_datagram_transport_for_data_channels are "
1186 "incompatible and cannot both be set to true";
1187 return false;
1188 }
1189 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1190 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1191 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1192 } else {
1193 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1194 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1195 }
1196 } else if (configuration.use_media_transport_for_data_channels) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001197 if (configuration.enable_rtp_data_channel) {
1198 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1199 "use_media_transport_for_data_channels are "
1200 "incompatible and cannot both be set to true";
1201 return false;
1202 }
1203 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1204 } else if (configuration.enable_rtp_data_channel) {
1205 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1206 // set. It takes precendence over the disable_sctp_data_channels
1207 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001208 data_channel_type_ = cricket::DCT_RTP;
1209 } else {
1210 // DTLS has to be enabled to use SCTP.
1211 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1212 data_channel_type_ = cricket::DCT_SCTP;
1213 }
1214 }
1215
1216 video_options_.screencast_min_bitrate_kbps =
1217 configuration.screencast_min_bitrate;
1218 audio_options_.combined_audio_video_bwe =
1219 configuration.combined_audio_video_bwe;
1220
1221 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001222 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001223
1224 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001225 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001226
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001227 audio_options_.audio_jitter_buffer_min_delay_ms =
1228 configuration.audio_jitter_buffer_min_delay_ms;
1229
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001230 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1231 configuration.audio_jitter_buffer_enable_rtx_handling;
1232
Steve Anton75737c02017-11-06 10:37:17 -08001233 // Whether the certificate generator/certificate is null or not determines
1234 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1235 // the right instructions by clearing the variables if needed.
1236 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001237 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001238 certificate = nullptr;
1239 } else if (certificate) {
1240 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001241 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001242 }
1243
1244 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1245 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001246 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001247 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1248 this, &PeerConnection::OnCertificateReady);
1249
1250 if (options.disable_encryption) {
1251 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1252 }
1253
1254 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001255 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001256 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001257
Steve Anton4171afb2017-11-20 10:20:22 -08001258 // Add default audio/video transceivers for Plan B SDP.
1259 if (!IsUnifiedPlan()) {
1260 transceivers_.push_back(
1261 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1262 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1263 transceivers_.push_back(
1264 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1265 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1266 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001267 int delay_ms =
1268 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001269 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1270 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001271
1272 if (dependencies.video_bitrate_allocator_factory) {
1273 video_bitrate_allocator_factory_ =
1274 std::move(dependencies.video_bitrate_allocator_factory);
1275 } else {
1276 video_bitrate_allocator_factory_ =
1277 CreateBuiltinVideoBitrateAllocatorFactory();
1278 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279 return true;
1280}
1281
Steve Anton038834f2017-07-14 15:59:59 -07001282RTCError PeerConnection::ValidateConfiguration(
1283 const RTCConfiguration& config) const {
1284 if (config.ice_regather_interval_range &&
1285 config.continual_gathering_policy == GATHER_ONCE) {
1286 return RTCError(RTCErrorType::INVALID_PARAMETER,
1287 "ice_regather_interval_range specified but continual "
1288 "gathering policy is GATHER_ONCE");
1289 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001290 auto result =
1291 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1292 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001293}
1294
Yves Gerey665174f2018-06-19 15:03:05 +02001295rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001296 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001297 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1298 "Plan SdpSemantics. Please use GetSenders "
1299 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001300 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301}
1302
Yves Gerey665174f2018-06-19 15:03:05 +02001303rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001304 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001305 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1306 "Plan SdpSemantics. Please use GetReceivers "
1307 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001308 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309}
1310
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001311bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001312 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001313 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1314 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001315 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 if (IsClosed()) {
1317 return false;
1318 }
deadbeefab9b2d12015-10-14 11:33:11 -07001319 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 return false;
1321 }
deadbeefab9b2d12015-10-14 11:33:11 -07001322
1323 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001324 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1325 observer->SignalAudioTrackAdded.connect(this,
1326 &PeerConnection::OnAudioTrackAdded);
1327 observer->SignalAudioTrackRemoved.connect(
1328 this, &PeerConnection::OnAudioTrackRemoved);
1329 observer->SignalVideoTrackAdded.connect(this,
1330 &PeerConnection::OnVideoTrackAdded);
1331 observer->SignalVideoTrackRemoved.connect(
1332 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001333 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001334
deadbeefab9b2d12015-10-14 11:33:11 -07001335 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001336 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001337 }
1338 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001339 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001340 }
1341
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001342 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001343 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 return true;
1345}
1346
1347void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001348 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001349 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1350 "Plan SdpSemantics. Please use RemoveTrack "
1351 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001352 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001353 if (!IsClosed()) {
1354 for (const auto& track : local_stream->GetAudioTracks()) {
1355 RemoveAudioTrack(track.get(), local_stream);
1356 }
1357 for (const auto& track : local_stream->GetVideoTracks()) {
1358 RemoveVideoTrack(track.get(), local_stream);
1359 }
deadbeefab9b2d12015-10-14 11:33:11 -07001360 }
deadbeefab9b2d12015-10-14 11:33:11 -07001361 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001362 stream_observers_.erase(
1363 std::remove_if(
1364 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001365 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001366 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001367 }),
1368 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 if (IsClosed()) {
1371 return;
1372 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001373 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374}
1375
Steve Anton2d6c76a2018-01-05 17:10:52 -08001376RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001377 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001378 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001379 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001380 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001381 if (!track) {
1382 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1383 }
1384 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1385 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1387 "Track has invalid kind: " + track->kind());
1388 }
Steve Antonf9381f02017-12-14 10:23:57 -08001389 if (IsClosed()) {
1390 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1391 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001392 }
Steve Anton4171afb2017-11-20 10:20:22 -08001393 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001394 LOG_AND_RETURN_ERROR(
1395 RTCErrorType::INVALID_PARAMETER,
1396 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001397 }
Steve Antonf9381f02017-12-14 10:23:57 -08001398 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001399 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1400 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001401 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001402 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001403 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001404 }
1405 return sender_or_error;
1406}
deadbeefe1f9d832016-01-14 15:35:42 -08001407
Steve Antonf9381f02017-12-14 10:23:57 -08001408RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1409PeerConnection::AddTrackPlanB(
1410 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001411 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001412 if (stream_ids.size() > 1u) {
1413 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1414 "AddTrack with more than one stream is not "
1415 "supported with Plan B semantics.");
1416 }
1417 std::vector<std::string> adjusted_stream_ids = stream_ids;
1418 if (adjusted_stream_ids.empty()) {
1419 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1420 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001421 cricket::MediaType media_type =
1422 (track->kind() == MediaStreamTrackInterface::kAudioKind
1423 ? cricket::MEDIA_TYPE_AUDIO
1424 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001425 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001426 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001427 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001428 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001429 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001430 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001431 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001432 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001433 if (sender_info) {
1434 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001435 }
Steve Antonf9381f02017-12-14 10:23:57 -08001436 } else {
1437 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001438 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001439 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001440 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001441 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001442 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001443 if (sender_info) {
1444 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001445 }
deadbeefe1f9d832016-01-14 15:35:42 -08001446 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001448}
deadbeefe1f9d832016-01-14 15:35:42 -08001449
Steve Antonf9381f02017-12-14 10:23:57 -08001450RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1451PeerConnection::AddTrackUnifiedPlan(
1452 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001453 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001454 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1455 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001456 RTC_LOG(LS_INFO) << "Reusing an existing "
1457 << cricket::MediaTypeToString(transceiver->media_type())
1458 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001459 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001460 transceiver->internal()->set_direction(
1461 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001462 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001463 transceiver->internal()->set_direction(
1464 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001465 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001466 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001467 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001468 } else {
1469 cricket::MediaType media_type =
1470 (track->kind() == MediaStreamTrackInterface::kAudioKind
1471 ? cricket::MEDIA_TYPE_AUDIO
1472 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001473 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1474 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001475 std::string sender_id = track->id();
1476 // Avoid creating a sender with an existing ID by generating a random ID.
1477 // This can happen if this is the second time AddTrack has created a sender
1478 // for this track.
1479 if (FindSenderById(sender_id)) {
1480 sender_id = rtc::CreateRandomUuid();
1481 }
Florent Castelli892acf02018-10-01 22:47:20 +02001482 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001483 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1484 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001485 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001486 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001487 }
Steve Antonf9381f02017-12-14 10:23:57 -08001488 return transceiver->sender();
1489}
1490
1491rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1492PeerConnection::FindFirstTransceiverForAddedTrack(
1493 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1494 RTC_DCHECK(track);
1495 for (auto transceiver : transceivers_) {
1496 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001497 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001498 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001499 !transceiver->internal()->has_ever_been_used_to_send() &&
1500 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001501 return transceiver;
1502 }
1503 }
1504 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001505}
1506
1507bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1508 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001509 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001510}
1511
Steve Anton24db5732018-07-23 10:27:33 -07001512RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001513 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001514 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001515 if (!sender) {
1516 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1517 }
deadbeefe1f9d832016-01-14 15:35:42 -08001518 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001519 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1520 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001521 }
Steve Antonf9381f02017-12-14 10:23:57 -08001522 if (IsUnifiedPlan()) {
1523 auto transceiver = FindTransceiverBySender(sender);
1524 if (!transceiver || !sender->track()) {
1525 return RTCError::OK();
1526 }
1527 sender->SetTrack(nullptr);
1528 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001529 transceiver->internal()->set_direction(
1530 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001531 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001532 transceiver->internal()->set_direction(
1533 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001534 }
Steve Anton4171afb2017-11-20 10:20:22 -08001535 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001536 bool removed;
1537 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1538 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1539 } else {
1540 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1541 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1542 }
1543 if (!removed) {
1544 LOG_AND_RETURN_ERROR(
1545 RTCErrorType::INVALID_PARAMETER,
1546 "Couldn't find sender " + sender->id() + " to remove.");
1547 }
Steve Anton4171afb2017-11-20 10:20:22 -08001548 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001549 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001550 return RTCError::OK();
1551}
1552
1553rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1554PeerConnection::FindTransceiverBySender(
1555 rtc::scoped_refptr<RtpSenderInterface> sender) {
1556 for (auto transceiver : transceivers_) {
1557 if (transceiver->sender() == sender) {
1558 return transceiver;
1559 }
1560 }
1561 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001562}
1563
Steve Anton9158ef62017-11-27 13:01:52 -08001564RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1565PeerConnection::AddTransceiver(
1566 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1567 return AddTransceiver(track, RtpTransceiverInit());
1568}
1569
1570RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1571PeerConnection::AddTransceiver(
1572 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1573 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001574 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001575 RTC_CHECK(IsUnifiedPlan())
1576 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001577 if (!track) {
1578 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1579 }
1580 cricket::MediaType media_type;
1581 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1582 media_type = cricket::MEDIA_TYPE_AUDIO;
1583 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1584 media_type = cricket::MEDIA_TYPE_VIDEO;
1585 } else {
1586 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1587 "Track kind is not audio or video");
1588 }
1589 return AddTransceiver(media_type, track, init);
1590}
1591
1592RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1593PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1594 return AddTransceiver(media_type, RtpTransceiverInit());
1595}
1596
1597RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1598PeerConnection::AddTransceiver(cricket::MediaType media_type,
1599 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001600 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001601 RTC_CHECK(IsUnifiedPlan())
1602 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001603 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1604 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1605 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1606 "media type is not audio or video");
1607 }
1608 return AddTransceiver(media_type, nullptr, init);
1609}
1610
1611RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1612PeerConnection::AddTransceiver(
1613 cricket::MediaType media_type,
1614 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001615 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001616 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001617 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1618 media_type == cricket::MEDIA_TYPE_VIDEO));
1619 if (track) {
1620 RTC_DCHECK_EQ(media_type,
1621 (track->kind() == MediaStreamTrackInterface::kAudioKind
1622 ? cricket::MEDIA_TYPE_AUDIO
1623 : cricket::MEDIA_TYPE_VIDEO));
1624 }
1625
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001626 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1627 init.send_encodings.size(), 0, 7, 8);
1628
Amit Hilbuchaa584152019-02-06 17:09:52 -08001629 size_t num_rids = absl::c_count_if(init.send_encodings,
1630 [](const RtpEncodingParameters& encoding) {
1631 return !encoding.rid.empty();
1632 });
1633 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001634 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001635 RTCErrorType::INVALID_PARAMETER,
1636 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001637 }
1638
Amit Hilbuchf4770402019-04-08 14:11:57 -07001639 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1640 [](const RtpEncodingParameters& encoding) {
1641 return !IsLegalRsidName(encoding.rid);
1642 })) {
1643 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1644 "Invalid RID value provided.");
1645 }
1646
Amit Hilbuchaa584152019-02-06 17:09:52 -08001647 if (absl::c_any_of(init.send_encodings,
1648 [](const RtpEncodingParameters& encoding) {
1649 return encoding.ssrc.has_value();
1650 })) {
1651 LOG_AND_RETURN_ERROR(
1652 RTCErrorType::UNSUPPORTED_PARAMETER,
1653 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001654 }
1655
1656 RtpParameters parameters;
1657 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001658
1659 // Encodings are dropped from the tail if too many are provided.
1660 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1661 parameters.encodings.erase(
1662 parameters.encodings.begin() + kMaxSimulcastStreams,
1663 parameters.encodings.end());
1664 }
1665
1666 // Single RID should be removed.
1667 if (parameters.encodings.size() == 1 &&
1668 !parameters.encodings[0].rid.empty()) {
1669 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1670 parameters.encodings[0].rid.clear();
1671 }
1672
1673 // If RIDs were not provided, they are generated for simulcast scenario.
1674 if (parameters.encodings.size() > 1 && num_rids == 0) {
1675 rtc::UniqueStringGenerator rid_generator;
1676 for (RtpEncodingParameters& encoding : parameters.encodings) {
1677 encoding.rid = rid_generator();
1678 }
1679 }
1680
Florent Castelli892acf02018-10-01 22:47:20 +02001681 if (UnimplementedRtpParameterHasValue(parameters)) {
1682 LOG_AND_RETURN_ERROR(
1683 RTCErrorType::UNSUPPORTED_PARAMETER,
1684 "Attempted to set an unimplemented parameter of RtpParameters.");
1685 }
Steve Anton9158ef62017-11-27 13:01:52 -08001686
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001687 auto result = cricket::CheckRtpParametersValues(parameters);
1688 if (!result.ok()) {
1689 LOG_AND_RETURN_ERROR(result.type(), result.message());
1690 }
1691
Steve Anton3d954a62018-04-02 11:27:23 -07001692 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1693 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001694 // Set the sender ID equal to the track ID if the track is specified unless
1695 // that sender ID is already in use.
1696 std::string sender_id =
1697 (track && !FindSenderById(track->id()) ? track->id()
1698 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001699 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001700 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001701 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1702 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1703 transceiver->internal()->set_direction(init.direction);
1704
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001705 if (update_negotiation_needed) {
1706 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001707 }
Steve Antonf9381f02017-12-14 10:23:57 -08001708
1709 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1710}
1711
Steve Anton02ee47c2018-01-10 16:26:06 -08001712rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1713PeerConnection::CreateSender(
1714 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001715 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001716 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001717 const std::vector<std::string>& stream_ids,
1718 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001719 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001720 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001721 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1722 RTC_DCHECK(!track ||
1723 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1724 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1725 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001726 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001727 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001728 } else {
1729 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1730 RTC_DCHECK(!track ||
1731 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1732 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001733 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001734 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001735 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001736 bool set_track_succeeded = sender->SetTrack(track);
1737 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001738 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001739 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001740 return sender;
1741}
1742
1743rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1744PeerConnection::CreateReceiver(cricket::MediaType media_type,
1745 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001746 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1747 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001748 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001749 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001750 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1751 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001752 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001753 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001754 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001755 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001756 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1757 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001758 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001759 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001760 return receiver;
1761}
1762
1763rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1764PeerConnection::CreateAndAddTransceiver(
1765 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1766 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1767 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001768 // Ensure that the new sender does not have an ID that is already in use by
1769 // another sender.
1770 // Allow receiver IDs to conflict since those come from remote SDP (which
1771 // could be invalid, but should not cause a crash).
1772 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001773 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001774 signaling_thread(),
1775 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001776 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001777 transceiver->internal()->SignalNegotiationNeeded.connect(
1778 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001779 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001780}
1781
Steve Anton52d86772018-02-20 15:48:12 -08001782void PeerConnection::OnNegotiationNeeded() {
1783 RTC_DCHECK_RUN_ON(signaling_thread());
1784 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001785 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001786}
1787
deadbeeffac06552015-11-25 11:26:01 -08001788rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001789 const std::string& kind,
1790 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001791 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001792 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1793 "Plan SdpSemantics. Please use AddTransceiver "
1794 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001795 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001796 if (IsClosed()) {
1797 return nullptr;
1798 }
Steve Anton4171afb2017-11-20 10:20:22 -08001799
Seth Hampson5b4f0752018-04-02 16:31:36 -07001800 // Internally we need to have one stream with Plan B semantics, so we
1801 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001802 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001803 if (stream_id.empty()) {
1804 stream_ids.push_back(rtc::CreateRandomUuid());
1805 RTC_LOG(LS_INFO)
1806 << "No stream_id specified for sender. Generated stream ID: "
1807 << stream_ids[0];
1808 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001809 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001810 }
1811
Steve Anton4171afb2017-11-20 10:20:22 -08001812 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001813 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001814 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001815 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001816 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001817 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001818 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001819 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001820 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001821 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001822 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001823 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001824 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001825 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001826 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001827 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001828 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001829 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001830 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001831 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001832 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001833
deadbeefe1f9d832016-01-14 15:35:42 -08001834 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001835}
1836
deadbeef70ab1a12015-09-28 16:53:55 -07001837std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1838 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001839 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001840 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001841 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001842 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001843 }
1844 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001845}
1846
Steve Anton4171afb2017-11-20 10:20:22 -08001847std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1848PeerConnection::GetSendersInternal() const {
1849 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1850 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001851 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001852 auto senders = transceiver->internal()->senders();
1853 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1854 }
1855 return all_senders;
1856}
1857
deadbeef70ab1a12015-09-28 16:53:55 -07001858std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1859PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001860 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001861 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001862 for (const auto& receiver : GetReceiversInternal()) {
1863 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001864 }
1865 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001866}
1867
Steve Anton4171afb2017-11-20 10:20:22 -08001868std::vector<
1869 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1870PeerConnection::GetReceiversInternal() const {
1871 std::vector<
1872 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1873 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001874 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001875 auto receivers = transceiver->internal()->receivers();
1876 all_receivers.insert(all_receivers.end(), receivers.begin(),
1877 receivers.end());
1878 }
1879 return all_receivers;
1880}
1881
Steve Anton9158ef62017-11-27 13:01:52 -08001882std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1883PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001884 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001885 RTC_CHECK(IsUnifiedPlan())
1886 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001887 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001888 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001889 all_transceivers.push_back(transceiver);
1890 }
1891 return all_transceivers;
1892}
1893
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001895 MediaStreamTrackInterface* track,
1896 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001897 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001898 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001899 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001900 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001901 return false;
1902 }
1903
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001904 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001905 // The StatsCollector is used to tell if a track is valid because it may
1906 // remember tracks that the PeerConnection previously removed.
1907 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001908 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1909 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001910 return false;
1911 }
Steve Antonad182762018-09-05 20:22:40 +00001912 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1913 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914 return true;
1915}
1916
hbos74e1a4f2016-09-15 23:33:01 -07001917void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001918 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001919 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001920 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001921 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001922 stats_collector_->GetStatsReport(callback);
1923}
1924
Henrik Boström1df1bf82018-03-20 13:24:20 +01001925void PeerConnection::GetStats(
1926 rtc::scoped_refptr<RtpSenderInterface> selector,
1927 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1928 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001929 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001930 RTC_DCHECK(callback);
1931 RTC_DCHECK(stats_collector_);
1932 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1933 if (selector) {
1934 for (const auto& proxy_transceiver : transceivers_) {
1935 for (const auto& proxy_sender :
1936 proxy_transceiver->internal()->senders()) {
1937 if (proxy_sender == selector) {
1938 internal_sender = proxy_sender->internal();
1939 break;
1940 }
1941 }
1942 if (internal_sender)
1943 break;
1944 }
1945 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001946 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001947 // belong to the PeerConnection (in Plan B, senders can be removed from the
1948 // PeerConnection). This means that "all the stats objects representing the
1949 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1950 // produces an empty stats report.
1951 stats_collector_->GetStatsReport(internal_sender, callback);
1952}
1953
1954void PeerConnection::GetStats(
1955 rtc::scoped_refptr<RtpReceiverInterface> selector,
1956 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1957 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001958 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001959 RTC_DCHECK(callback);
1960 RTC_DCHECK(stats_collector_);
1961 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1962 if (selector) {
1963 for (const auto& proxy_transceiver : transceivers_) {
1964 for (const auto& proxy_receiver :
1965 proxy_transceiver->internal()->receivers()) {
1966 if (proxy_receiver == selector) {
1967 internal_receiver = proxy_receiver->internal();
1968 break;
1969 }
1970 }
1971 if (internal_receiver)
1972 break;
1973 }
1974 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001975 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001976 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1977 // the PeerConnection). This means that "all the stats objects representing
1978 // the selector" is an empty set. Invoking GetStatsReport() with a null
1979 // selector produces an empty stats report.
1980 stats_collector_->GetStatsReport(internal_receiver, callback);
1981}
1982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001984 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 return signaling_state_;
1986}
1987
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001988PeerConnectionInterface::IceConnectionState
1989PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001990 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 return ice_connection_state_;
1992}
1993
Alex Loiko9289eda2018-11-23 16:18:59 +00001994PeerConnectionInterface::IceConnectionState
1995PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001996 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001997 return standardized_ice_connection_state_;
1998}
1999
Jonas Olsson635474e2018-10-18 15:58:17 +02002000PeerConnectionInterface::PeerConnectionState
2001PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002002 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002003 return connection_state_;
2004}
2005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006PeerConnectionInterface::IceGatheringState
2007PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002008 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 return ice_gathering_state_;
2010}
2011
Yves Gerey665174f2018-06-19 15:03:05 +02002012rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 const std::string& label,
2014 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002015 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002016 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002017
deadbeefab9b2d12015-10-14 11:33:11 -07002018 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002019
kwibergd1fe2812016-04-27 06:47:29 -07002020 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002021 if (config) {
2022 internal_config.reset(new InternalDataChannelInit(*config));
2023 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002024 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002025 InternalCreateDataChannel(label, internal_config.get()));
2026 if (!channel.get()) {
2027 return nullptr;
2028 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002030 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2031 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002032 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002033 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002034 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002035 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036 return DataChannelProxy::Create(signaling_thread(), channel.get());
2037}
2038
Henrik Boström79b69802019-07-18 11:16:56 +02002039void PeerConnection::RestartIce() {
2040 RTC_DCHECK_RUN_ON(signaling_thread());
2041 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2042 current_local_description_.get(), pending_local_description_.get());
2043 UpdateNegotiationNeeded();
2044}
2045
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002046void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002047 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002048 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002049 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002050
nisse7ce109a2017-01-31 00:57:56 -08002051 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002052 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002053 return;
2054 }
deadbeefab9b2d12015-10-14 11:33:11 -07002055
Steve Anton8d3444d2017-10-20 15:30:51 -07002056 if (IsClosed()) {
2057 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002058 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002059 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002060 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002061 return;
2062 }
2063
Steve Anton25ca0ac2019-06-25 10:40:48 -07002064 // If a session error has occurred the PeerConnection is in a possibly
2065 // inconsistent state so fail right away.
2066 if (session_error() != SessionError::kNone) {
2067 std::string error_message = GetSessionErrorMsg();
2068 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2069 PostCreateSessionDescriptionFailure(
2070 observer,
2071 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2072 return;
2073 }
2074
zhihuang1c378ed2017-08-17 14:10:50 -07002075 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002076 std::string error = "CreateOffer called with invalid options.";
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_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002080 return;
2081 }
2082
Steve Anton22da89f2018-01-25 13:58:07 -08002083 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2084 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2085 if (IsUnifiedPlan()) {
2086 RTCError error = HandleLegacyOfferOptions(options);
2087 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002088 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002089 return;
2090 }
2091 }
2092
zhihuang1c378ed2017-08-17 14:10:50 -07002093 cricket::MediaSessionOptions session_options;
2094 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002095 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002096}
2097
Steve Anton22da89f2018-01-25 13:58:07 -08002098RTCError PeerConnection::HandleLegacyOfferOptions(
2099 const RTCOfferAnswerOptions& options) {
2100 RTC_DCHECK(IsUnifiedPlan());
2101
2102 if (options.offer_to_receive_audio == 0) {
2103 RemoveRecvDirectionFromReceivingTransceiversOfType(
2104 cricket::MEDIA_TYPE_AUDIO);
2105 } else if (options.offer_to_receive_audio == 1) {
2106 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2107 } else if (options.offer_to_receive_audio > 1) {
2108 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2109 "offer_to_receive_audio > 1 is not supported.");
2110 }
2111
2112 if (options.offer_to_receive_video == 0) {
2113 RemoveRecvDirectionFromReceivingTransceiversOfType(
2114 cricket::MEDIA_TYPE_VIDEO);
2115 } else if (options.offer_to_receive_video == 1) {
2116 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2117 } else if (options.offer_to_receive_video > 1) {
2118 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2119 "offer_to_receive_video > 1 is not supported.");
2120 }
2121
2122 return RTCError::OK();
2123}
2124
2125void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2126 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002127 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002128 RtpTransceiverDirection new_direction =
2129 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2130 if (new_direction != transceiver->direction()) {
2131 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2132 << " transceiver (MID="
2133 << transceiver->mid().value_or("<not set>") << ") from "
2134 << RtpTransceiverDirectionToString(
2135 transceiver->direction())
2136 << " to "
2137 << RtpTransceiverDirectionToString(new_direction)
2138 << " since CreateOffer specified offer_to_receive=0";
2139 transceiver->internal()->set_direction(new_direction);
2140 }
Steve Anton22da89f2018-01-25 13:58:07 -08002141 }
2142}
2143
2144void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2145 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002146 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002147 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002148 RTC_LOG(LS_INFO)
2149 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2150 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002151 RtpTransceiverInit init;
2152 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002153 AddTransceiver(media_type, nullptr, init,
2154 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002155 }
2156}
2157
2158std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2159PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2160 std::vector<
2161 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2162 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002163 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002164 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002165 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2166 receiving_transceivers.push_back(transceiver);
2167 }
2168 }
2169 return receiving_transceivers;
2170}
2171
htaa2a49d92016-03-04 02:51:39 -08002172void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2173 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002174 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002175 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002176 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002177 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002178 return;
2179 }
2180
Steve Anton25ca0ac2019-06-25 10:40:48 -07002181 // If a session error has occurred the PeerConnection is in a possibly
2182 // inconsistent state so fail right away.
2183 if (session_error() != SessionError::kNone) {
2184 std::string error_message = GetSessionErrorMsg();
2185 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2186 PostCreateSessionDescriptionFailure(
2187 observer,
2188 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2189 return;
2190 }
2191
Steve Antondffead82018-02-06 10:31:29 -08002192 if (!(signaling_state_ == kHaveRemoteOffer ||
2193 signaling_state_ == kHaveLocalPrAnswer)) {
2194 std::string error =
2195 "PeerConnection cannot create an answer in a state other than "
2196 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002197 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002198 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002199 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002200 return;
2201 }
2202
Steve Antondffead82018-02-06 10:31:29 -08002203 // The remote description should be set if we're in the right state.
2204 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002205
Steve Anton22da89f2018-01-25 13:58:07 -08002206 if (IsUnifiedPlan()) {
2207 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2208 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2209 "supported with Unified Plan semantics. Use the "
2210 "RtpTransceiver API instead.";
2211 }
2212 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2213 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2214 "supported with Unified Plan semantics. Use the "
2215 "RtpTransceiver API instead.";
2216 }
2217 }
2218
htaa2a49d92016-03-04 02:51:39 -08002219 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002220 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002221
Steve Antond25da372017-11-06 14:50:29 -08002222 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223}
2224
2225void PeerConnection::SetLocalDescription(
2226 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002227 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002228 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002229 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002230
Steve Anton80dd7b52018-02-16 17:08:42 -08002231 // The SetLocalDescription contract is that we take ownership of the session
2232 // description regardless of the outcome, so wrap it in a unique_ptr right
2233 // away. Ideally, SetLocalDescription's signature will be changed to take the
2234 // description as a unique_ptr argument to formalize this agreement.
2235 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2236
nisse7ce109a2017-01-31 00:57:56 -08002237 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002238 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 return;
2240 }
Steve Anton8a006912017-12-04 15:25:56 -08002241
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002243 PostSetSessionDescriptionFailure(
2244 observer,
2245 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246 return;
2247 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002248
Steve Anton80dd7b52018-02-16 17:08:42 -08002249 // If a session error has occurred the PeerConnection is in a possibly
2250 // inconsistent state so fail right away.
2251 if (session_error() != SessionError::kNone) {
2252 std::string error_message = GetSessionErrorMsg();
2253 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002254 PostSetSessionDescriptionFailure(
2255 observer,
2256 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002257 return;
2258 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002259
Steve Anton80dd7b52018-02-16 17:08:42 -08002260 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2261 if (!error.ok()) {
2262 std::string error_message = GetSetDescriptionErrorMessage(
2263 cricket::CS_LOCAL, desc->GetType(), error);
2264 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002265 PostSetSessionDescriptionFailure(
2266 observer,
2267 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002268 return;
2269 }
2270
2271 // Grab the description type before moving ownership to ApplyLocalDescription,
2272 // which may destroy it before returning.
2273 const SdpType type = desc->GetType();
2274
2275 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002276 // |desc| may be destroyed at this point.
2277
2278 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002279 // If ApplyLocalDescription fails, the PeerConnection could be in an
2280 // inconsistent state, so act conservatively here and set the session error
2281 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2282 SetSessionError(SessionError::kContent, error.message());
2283 std::string error_message =
2284 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2285 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002286 PostSetSessionDescriptionFailure(
2287 observer,
2288 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002289 return;
2290 }
Steve Anton8a006912017-12-04 15:25:56 -08002291 RTC_DCHECK(local_description());
2292
2293 PostSetSessionDescriptionSuccess(observer);
2294
Steve Antonad182762018-09-05 20:22:40 +00002295 // MaybeStartGathering needs to be called after posting
2296 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2297 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002298 transport_controller_->MaybeStartGathering();
2299
Steve Antona3a92c22017-12-07 10:27:41 -08002300 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002301 // TODO(deadbeef): We already had to hop to the network thread for
2302 // MaybeStartGathering...
2303 network_thread()->Invoke<void>(
2304 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2305 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002306 // Make UMA notes about what was agreed to.
2307 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002308 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002309
2310 if (IsUnifiedPlan()) {
2311 bool was_negotiation_needed = is_negotiation_needed_;
2312 UpdateNegotiationNeeded();
2313 if (signaling_state() == kStable && was_negotiation_needed &&
2314 is_negotiation_needed_) {
2315 Observer()->OnRenegotiationNeeded();
2316 }
2317 }
2318
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002319 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002320}
2321
2322RTCError PeerConnection::ApplyLocalDescription(
2323 std::unique_ptr<SessionDescriptionInterface> desc) {
2324 RTC_DCHECK_RUN_ON(signaling_thread());
2325 RTC_DCHECK(desc);
2326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327 // Update stats here so that we have the most recent stats for tracks and
2328 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002329 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002330
Steve Antondcc3c022017-12-22 16:02:54 -08002331 // Take a reference to the old local description since it's used below to
2332 // compare against the new local description. When setting the new local
2333 // description, grab ownership of the replaced session description in case it
2334 // is the same as |old_local_description|, to keep it alive for the duration
2335 // of the method.
2336 const SessionDescriptionInterface* old_local_description =
2337 local_description();
2338 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002339 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002340 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002341 replaced_local_description = pending_local_description_
2342 ? std::move(pending_local_description_)
2343 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002344 current_local_description_ = std::move(desc);
2345 pending_local_description_ = nullptr;
2346 current_remote_description_ = std::move(pending_remote_description_);
2347 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002348 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002349 pending_local_description_ = std::move(desc);
2350 }
2351 // The session description to apply now must be accessed by
2352 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002353 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002354
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002355 // Report statistics about any use of simulcast.
2356 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2357 *local_description()->description());
2358
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002359 if (!is_caller_) {
2360 if (remote_description()) {
2361 // Remote description was applied first, so this PC is the callee.
2362 is_caller_ = false;
2363 } else {
2364 // Local description is applied first, so this PC is the caller.
2365 is_caller_ = true;
2366 }
2367 }
2368
Zhi Huange830e682018-03-30 10:48:35 -07002369 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2370 if (!error.ok()) {
2371 return error;
2372 }
2373
Steve Antondcc3c022017-12-22 16:02:54 -08002374 if (IsUnifiedPlan()) {
2375 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002376 cricket::CS_LOCAL, *local_description(), old_local_description,
2377 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002378 if (!error.ok()) {
2379 return error;
2380 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002381 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2382 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002383 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002384 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2385 // Note that code paths that don't set MID won't be able to use
2386 // information about DTLS transports.
2387 if (transceiver->mid()) {
2388 auto dtls_transport =
2389 LookupDtlsTransportByMidInternal(*transceiver->mid());
2390 transceiver->internal()->sender_internal()->set_transport(
2391 dtls_transport);
2392 transceiver->internal()->receiver_internal()->set_transport(
2393 dtls_transport);
2394 }
2395
Steve Antondcc3c022017-12-22 16:02:54 -08002396 const ContentInfo* content =
2397 FindMediaSectionForTransceiver(transceiver, local_description());
2398 if (!content) {
2399 continue;
2400 }
2401 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002402 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2403 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002404 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002405 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2406 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2407 // "recvonly", process the removal of a remote track for the media
2408 // description, given transceiver, removeList, and muteTracks.
2409 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2410 (transceiver->internal()->fired_direction() &&
2411 RtpTransceiverDirectionHasRecv(
2412 *transceiver->internal()->fired_direction()))) {
2413 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2414 &removed_streams);
2415 }
2416 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2417 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002418 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002419 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002420 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002421 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002422 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002423 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002424 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002425 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002426 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002427 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002428 }
2429 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002430 // Media channels will be created only when offer is set. These may use new
2431 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002432 if (type == SdpType::kOffer) {
2433 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2434 // description is applied. Restore back to old description.
2435 RTCError error = CreateChannels(*local_description()->description());
2436 if (!error.ok()) {
2437 return error;
2438 }
2439 }
Steve Antondcc3c022017-12-22 16:02:54 -08002440 // Remove unused channels if MediaContentDescription is rejected.
2441 RemoveUnusedChannels(local_description()->description());
2442 }
Steve Anton8a006912017-12-04 15:25:56 -08002443
Zhi Huange830e682018-03-30 10:48:35 -07002444 error = UpdateSessionState(type, cricket::CS_LOCAL,
2445 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002446 if (!error.ok()) {
2447 return error;
2448 }
Steve Antondcc3c022017-12-22 16:02:54 -08002449
Steve Anton8a006912017-12-04 15:25:56 -08002450 if (remote_description()) {
2451 // Now that we have a local description, we can push down remote candidates.
2452 UseCandidatesInSessionDescription(remote_description());
2453 }
2454
2455 pending_ice_restarts_.clear();
2456 if (session_error() != SessionError::kNone) {
2457 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2458 }
2459
deadbeefab9b2d12015-10-14 11:33:11 -07002460 // If setting the description decided our SSL role, allocate any necessary
2461 // SCTP sids.
2462 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002463 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002464 AllocateSctpSids(role);
2465 }
2466
Steve Antond3679212018-01-17 17:41:02 -08002467 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002468 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002469 const ContentInfo* content =
2470 FindMediaSectionForTransceiver(transceiver, local_description());
2471 if (!content) {
2472 continue;
2473 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002474 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2475 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002476 // 0 is a special value meaning "this sender has no associated send
2477 // stream". Need to call this so the sender won't attempt to configure
2478 // a no longer existing stream and run into DCHECKs in the lower
2479 // layers.
2480 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002481 } else {
2482 // Get the StreamParams from the channel which could generate SSRCs.
2483 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002484 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002485 streams[0].stream_ids());
2486 transceiver->internal()->sender_internal()->SetSsrc(
2487 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002488 }
2489 }
2490 } else {
2491 // Plan B semantics.
2492
Steve Antondcc3c022017-12-22 16:02:54 -08002493 // Update state and SSRC of local MediaStreams and DataChannels based on the
2494 // local session description.
2495 const cricket::ContentInfo* audio_content =
2496 GetFirstAudioContent(local_description()->description());
2497 if (audio_content) {
2498 if (audio_content->rejected) {
2499 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2500 } else {
2501 const cricket::AudioContentDescription* audio_desc =
2502 audio_content->media_description()->as_audio();
2503 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2504 }
deadbeeffaac4972015-11-12 15:33:07 -08002505 }
deadbeefab9b2d12015-10-14 11:33:11 -07002506
Steve Antondcc3c022017-12-22 16:02:54 -08002507 const cricket::ContentInfo* video_content =
2508 GetFirstVideoContent(local_description()->description());
2509 if (video_content) {
2510 if (video_content->rejected) {
2511 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2512 } else {
2513 const cricket::VideoContentDescription* video_desc =
2514 video_content->media_description()->as_video();
2515 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2516 }
deadbeeffaac4972015-11-12 15:33:07 -08002517 }
deadbeefab9b2d12015-10-14 11:33:11 -07002518 }
2519
2520 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002521 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002522 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002523 const cricket::RtpDataContentDescription* rtp_data_desc =
2524 data_content->media_description()->as_rtp_data();
2525 // rtp_data_desc will be null if this is an SCTP description.
2526 if (rtp_data_desc) {
2527 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002528 }
2529 }
2530
Henrik Boström79b69802019-07-18 11:16:56 +02002531 if (type == SdpType::kAnswer &&
2532 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2533 *current_local_description_)) {
2534 local_ice_credentials_to_replace_->ClearIceCredentials();
2535 }
2536
Steve Anton8a006912017-12-04 15:25:56 -08002537 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002538}
2539
Steve Anton06817cd2018-12-18 15:55:30 -08002540// The SDP parser used to populate these values by default for the 'content
2541// name' if an a=mid line was absent.
2542static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2543 switch (media_type) {
2544 case cricket::MEDIA_TYPE_AUDIO:
2545 return cricket::CN_AUDIO;
2546 case cricket::MEDIA_TYPE_VIDEO:
2547 return cricket::CN_VIDEO;
2548 case cricket::MEDIA_TYPE_DATA:
2549 return cricket::CN_DATA;
2550 }
2551 RTC_NOTREACHED();
2552 return "";
2553}
2554
2555void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002556 cricket::SessionDescription* new_remote_description) {
2557 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002558 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002559 const cricket::ContentInfos& local_contents =
2560 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002561 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002562 const cricket::ContentInfos& remote_contents =
2563 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002564 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002565 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2566 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002567 if (!content.name.empty()) {
2568 continue;
2569 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002570 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002571 absl::string_view source_explanation;
2572 if (IsUnifiedPlan()) {
2573 if (i < local_contents.size()) {
2574 new_mid = local_contents[i].name;
2575 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002576 } else if (i < remote_contents.size()) {
2577 new_mid = remote_contents[i].name;
2578 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002579 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002580 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002581 source_explanation = "generated just now";
2582 }
2583 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002584 new_mid = std::string(
2585 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002586 source_explanation = "to match pre-existing behavior";
2587 }
Steve Antond7180cc2019-02-07 10:44:53 -08002588 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002589 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002590 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002591 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2592 << " is missing an a=mid line. Filling in the value '"
2593 << new_mid << "' " << source_explanation << ".";
2594 }
2595}
2596
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002597void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002598 SetSessionDescriptionObserver* observer,
2599 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002600 SetRemoteDescription(
2601 std::unique_ptr<SessionDescriptionInterface>(desc),
2602 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2603 new SetRemoteDescriptionObserverAdapter(this, observer)));
2604}
2605
2606void PeerConnection::SetRemoteDescription(
2607 std::unique_ptr<SessionDescriptionInterface> desc,
2608 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002609 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002610 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002611
nisse7ce109a2017-01-31 00:57:56 -08002612 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002613 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002614 return;
2615 }
Steve Anton8a006912017-12-04 15:25:56 -08002616
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002617 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002618 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002619 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620 return;
2621 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002622
Steve Anton80dd7b52018-02-16 17:08:42 -08002623 // If a session error has occurred the PeerConnection is in a possibly
2624 // inconsistent state so fail right away.
2625 if (session_error() != SessionError::kNone) {
2626 std::string error_message = GetSessionErrorMsg();
2627 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2628 observer->OnSetRemoteDescriptionComplete(
2629 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2630 return;
2631 }
Steve Anton71439a62018-02-15 11:53:06 -08002632
Steve Antonba42e992018-04-09 14:10:01 -07002633 if (desc->GetType() == SdpType::kOffer) {
2634 // Report to UMA the format of the received offer.
2635 ReportSdpFormatReceived(*desc);
2636 }
2637
Steve Anton06817cd2018-12-18 15:55:30 -08002638 // Handle remote descriptions missing a=mid lines for interop with legacy end
2639 // points.
2640 FillInMissingRemoteMids(desc->description());
2641
Steve Anton80dd7b52018-02-16 17:08:42 -08002642 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002643 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002644 std::string error_message = GetSetDescriptionErrorMessage(
2645 cricket::CS_REMOTE, desc->GetType(), error);
2646 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002647 observer->OnSetRemoteDescriptionComplete(
2648 RTCError(error.type(), std::move(error_message)));
2649 return;
2650 }
Steve Anton71439a62018-02-15 11:53:06 -08002651
Steve Anton80dd7b52018-02-16 17:08:42 -08002652 // Grab the description type before moving ownership to
2653 // ApplyRemoteDescription, which may destroy it before returning.
2654 const SdpType type = desc->GetType();
2655
2656 error = ApplyRemoteDescription(std::move(desc));
2657 // |desc| may be destroyed at this point.
2658
2659 if (!error.ok()) {
2660 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2661 // inconsistent state, so act conservatively here and set the session error
2662 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2663 SetSessionError(SessionError::kContent, error.message());
2664 std::string error_message =
2665 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2666 RTC_LOG(LS_ERROR) << error_message;
2667 observer->OnSetRemoteDescriptionComplete(
2668 RTCError(error.type(), std::move(error_message)));
2669 return;
2670 }
2671 RTC_DCHECK(remote_description());
2672
2673 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002674 // TODO(deadbeef): We already had to hop to the network thread for
2675 // MaybeStartGathering...
2676 network_thread()->Invoke<void>(
2677 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2678 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002679 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002680 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002681 }
2682
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002683 if (IsUnifiedPlan()) {
2684 bool was_negotiation_needed = is_negotiation_needed_;
2685 UpdateNegotiationNeeded();
2686 if (signaling_state() == kStable && was_negotiation_needed &&
2687 is_negotiation_needed_) {
2688 Observer()->OnRenegotiationNeeded();
2689 }
2690 }
2691
Steve Anton8a006912017-12-04 15:25:56 -08002692 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002693 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002694}
2695
2696RTCError PeerConnection::ApplyRemoteDescription(
2697 std::unique_ptr<SessionDescriptionInterface> desc) {
2698 RTC_DCHECK_RUN_ON(signaling_thread());
2699 RTC_DCHECK(desc);
2700
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 // Update stats here so that we have the most recent stats for tracks and
2702 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002703 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002704
Steve Antondcc3c022017-12-22 16:02:54 -08002705 // Take a reference to the old remote description since it's used below to
2706 // compare against the new remote description. When setting the new remote
2707 // description, grab ownership of the replaced session description in case it
2708 // is the same as |old_remote_description|, to keep it alive for the duration
2709 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002710 const SessionDescriptionInterface* old_remote_description =
2711 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002712 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002713 SdpType type = desc->GetType();
2714 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002715 replaced_remote_description = pending_remote_description_
2716 ? std::move(pending_remote_description_)
2717 : std::move(current_remote_description_);
2718 current_remote_description_ = std::move(desc);
2719 pending_remote_description_ = nullptr;
2720 current_local_description_ = std::move(pending_local_description_);
2721 } else {
2722 replaced_remote_description = std::move(pending_remote_description_);
2723 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002724 }
Steve Anton8a006912017-12-04 15:25:56 -08002725 // The session description to apply now must be accessed by
2726 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002727 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002728
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002729 // Report statistics about any use of simulcast.
2730 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2731 *remote_description()->description());
2732
Zhi Huange830e682018-03-30 10:48:35 -07002733 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2734 if (!error.ok()) {
2735 return error;
2736 }
Steve Anton8a006912017-12-04 15:25:56 -08002737 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002738 if (IsUnifiedPlan()) {
2739 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002740 cricket::CS_REMOTE, *remote_description(), local_description(),
2741 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002742 if (!error.ok()) {
2743 return error;
2744 }
Steve Antondcc3c022017-12-22 16:02:54 -08002745 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002746 // Media channels will be created only when offer is set. These may use new
2747 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002748 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002749 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002750 // description is applied. Restore back to old description.
2751 RTCError error = CreateChannels(*remote_description()->description());
2752 if (!error.ok()) {
2753 return error;
2754 }
2755 }
Steve Antondcc3c022017-12-22 16:02:54 -08002756 // Remove unused channels if MediaContentDescription is rejected.
2757 RemoveUnusedChannels(remote_description()->description());
2758 }
Steve Anton8a006912017-12-04 15:25:56 -08002759
Zhi Huange830e682018-03-30 10:48:35 -07002760 // NOTE: Candidates allocation will be initiated only when
2761 // SetLocalDescription is called.
2762 error = UpdateSessionState(type, cricket::CS_REMOTE,
2763 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002764 if (!error.ok()) {
2765 return error;
2766 }
2767
2768 if (local_description() &&
2769 !UseCandidatesInSessionDescription(remote_description())) {
2770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2771 }
2772
2773 if (old_remote_description) {
2774 for (const cricket::ContentInfo& content :
2775 old_remote_description->description()->contents()) {
2776 // Check if this new SessionDescription contains new ICE ufrag and
2777 // password that indicates the remote peer requests an ICE restart.
2778 // TODO(deadbeef): When we start storing both the current and pending
2779 // remote description, this should reset pending_ice_restarts and compare
2780 // against the current description.
2781 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2782 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002783 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002784 pending_ice_restarts_.insert(content.name);
2785 }
2786 } else {
2787 // We retain all received candidates only if ICE is not restarted.
2788 // When ICE is restarted, all previous candidates belong to an old
2789 // generation and should not be kept.
2790 // TODO(deadbeef): This goes against the W3C spec which says the remote
2791 // description should only contain candidates from the last set remote
2792 // description plus any candidates added since then. We should remove
2793 // this once we're sure it won't break anything.
2794 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2795 old_remote_description, content.name, mutable_remote_description());
2796 }
2797 }
2798 }
2799
2800 if (session_error() != SessionError::kNone) {
2801 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2802 }
2803
2804 // Set the the ICE connection state to connecting since the connection may
2805 // become writable with peer reflexive candidates before any remote candidate
2806 // is signaled.
2807 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2808 // is to have a new signal the indicates a change in checking state from the
2809 // transport and expose a new checking() member from transport that can be
2810 // read to determine the current checking state. The existing SignalConnecting
2811 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002812 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002813 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002814 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2815 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2816 }
2817
deadbeefab9b2d12015-10-14 11:33:11 -07002818 // If setting the description decided our SSL role, allocate any necessary
2819 // SCTP sids.
2820 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002821 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002822 AllocateSctpSids(role);
2823 }
2824
Steve Antondcc3c022017-12-22 16:02:54 -08002825 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002826 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002827 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002828 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002829 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002830 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002831 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002832 const ContentInfo* content =
2833 FindMediaSectionForTransceiver(transceiver, remote_description());
2834 if (!content) {
2835 continue;
2836 }
2837 const MediaContentDescription* media_desc = content->media_description();
2838 RtpTransceiverDirection local_direction =
2839 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002840 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2841 // RTCSessionDescription: Set the associated remote streams given
2842 // transceiver.[[Receiver]], msids, addList, and removeList".
2843 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2844 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2845 std::vector<std::string> stream_ids;
2846 if (!media_desc->streams().empty()) {
2847 // The remote description has signaled the stream IDs.
2848 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002849 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002850 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2851 << " (" << GetStreamIdsString(stream_ids) << ").";
2852 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2853 stream_ids, &added_streams,
2854 &removed_streams);
2855 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2856 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2857 // and transceiver's current direction is neither sendrecv nor recvonly,
2858 // process the addition of a remote track for the media description.
2859 if (!transceiver->fired_direction() ||
2860 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2861 RTC_LOG(LS_INFO)
2862 << "Processing the addition of a remote track for MID="
2863 << content->name << ".";
2864 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002865 }
Steve Antondcc3c022017-12-22 16:02:54 -08002866 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002867 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002868 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2869 // removal of a remote track for the media description, given transceiver,
2870 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002871 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002872 (transceiver->fired_direction() &&
2873 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2874 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2875 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002876 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002877 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002878 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002879 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002880 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002881 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002882 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002883 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002884 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002885 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2886 if (transceiver->mid()) {
2887 auto dtls_transport =
2888 LookupDtlsTransportByMidInternal(*transceiver->mid());
2889 transceiver->internal()->sender_internal()->set_transport(
2890 dtls_transport);
2891 transceiver->internal()->receiver_internal()->set_transport(
2892 dtls_transport);
2893 }
Steve Antondcc3c022017-12-22 16:02:54 -08002894 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002895 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002896 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002897 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002898 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2899 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002900 transceiver->Stop();
2901 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002902 if (!content->rejected &&
2903 RtpTransceiverDirectionHasRecv(local_direction)) {
2904 // Set ssrc to 0 in the case of an unsignalled ssrc.
2905 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002906 if (!media_desc->streams().empty() &&
2907 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002908 ssrc = media_desc->streams()[0].first_ssrc();
2909 }
2910 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002911 }
Steve Antondcc3c022017-12-22 16:02:54 -08002912 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002913 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002914 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002915 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002916 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002917 observer->OnTrack(transceiver);
2918 observer->OnAddTrack(transceiver->receiver(),
2919 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002920 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002921 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002922 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002923 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002924 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002925 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002926 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002927 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002928 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002929 }
Steve Antondcc3c022017-12-22 16:02:54 -08002930 }
2931
Henrik Boströmfdb92012017-11-09 19:55:44 +01002932 const cricket::ContentInfo* audio_content =
2933 GetFirstAudioContent(remote_description()->description());
2934 const cricket::ContentInfo* video_content =
2935 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002936 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002937 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002938 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002939 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002940 const cricket::RtpDataContentDescription* rtp_data_desc =
2941 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002942
2943 // Check if the descriptions include streams, just in case the peer supports
2944 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002945 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002946 (audio_desc && !audio_desc->streams().empty()) ||
2947 (video_desc && !video_desc->streams().empty())) {
2948 remote_peer_supports_msid_ = true;
2949 }
deadbeefab9b2d12015-10-14 11:33:11 -07002950
2951 // We wait to signal new streams until we finish processing the description,
2952 // since only at that point will new streams have all their tracks.
2953 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2954
Steve Antondcc3c022017-12-22 16:02:54 -08002955 if (!IsUnifiedPlan()) {
2956 // TODO(steveanton): When removing RTP senders/receivers in response to a
2957 // rejected media section, there is some cleanup logic that expects the
2958 // voice/ video channel to still be set. But in this method the voice/video
2959 // channel would have been destroyed by the SetRemoteDescription caller
2960 // above so the cleanup that relies on them fails to run. The RemoveSenders
2961 // calls should be moved to right before the DestroyChannel calls to fix
2962 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002963
Steve Antondcc3c022017-12-22 16:02:54 -08002964 // Find all audio rtp streams and create corresponding remote AudioTracks
2965 // and MediaStreams.
2966 if (audio_content) {
2967 if (audio_content->rejected) {
2968 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2969 } else {
2970 bool default_audio_track_needed =
2971 !remote_peer_supports_msid_ &&
2972 RtpTransceiverDirectionHasSend(audio_desc->direction());
2973 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2974 default_audio_track_needed, audio_desc->type(),
2975 new_streams);
2976 }
deadbeeffaac4972015-11-12 15:33:07 -08002977 }
deadbeefab9b2d12015-10-14 11:33:11 -07002978
Steve Antondcc3c022017-12-22 16:02:54 -08002979 // Find all video rtp streams and create corresponding remote VideoTracks
2980 // and MediaStreams.
2981 if (video_content) {
2982 if (video_content->rejected) {
2983 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2984 } else {
2985 bool default_video_track_needed =
2986 !remote_peer_supports_msid_ &&
2987 RtpTransceiverDirectionHasSend(video_desc->direction());
2988 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2989 default_video_track_needed, video_desc->type(),
2990 new_streams);
2991 }
deadbeeffaac4972015-11-12 15:33:07 -08002992 }
deadbeefab9b2d12015-10-14 11:33:11 -07002993
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002994 // If this is an RTP data transport, update the DataChannels with the
2995 // information from the remote peer.
2996 if (rtp_data_desc) {
2997 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002998 }
deadbeefab9b2d12015-10-14 11:33:11 -07002999
Steve Antondcc3c022017-12-22 16:02:54 -08003000 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003001 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003002 for (size_t i = 0; i < new_streams->count(); ++i) {
3003 MediaStreamInterface* new_stream = new_streams->at(i);
3004 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003005 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003006 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3007 }
deadbeefab9b2d12015-10-14 11:33:11 -07003008
Steve Antondcc3c022017-12-22 16:02:54 -08003009 UpdateEndedRemoteMediaStreams();
3010 }
deadbeefab9b2d12015-10-14 11:33:11 -07003011
Henrik Boström79b69802019-07-18 11:16:56 +02003012 if (type == SdpType::kAnswer &&
3013 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3014 *current_local_description_)) {
3015 local_ice_credentials_to_replace_->ClearIceCredentials();
3016 }
3017
Steve Anton8a006912017-12-04 15:25:56 -08003018 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003019}
3020
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003021void PeerConnection::SetAssociatedRemoteStreams(
3022 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3023 const std::vector<std::string>& stream_ids,
3024 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3025 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3026 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3027 for (const std::string& stream_id : stream_ids) {
3028 rtc::scoped_refptr<MediaStreamInterface> stream =
3029 remote_streams_->find(stream_id);
3030 if (!stream) {
3031 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3032 MediaStream::Create(stream_id));
3033 remote_streams_->AddStream(stream);
3034 added_streams->push_back(stream);
3035 }
3036 media_streams.push_back(stream);
3037 }
3038 // Special case: "a=msid" missing, use random stream ID.
3039 if (media_streams.empty() &&
3040 !(remote_description()->description()->msid_signaling() &
3041 cricket::kMsidSignalingMediaSection)) {
3042 if (!missing_msid_default_stream_) {
3043 missing_msid_default_stream_ = MediaStreamProxy::Create(
3044 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3045 added_streams->push_back(missing_msid_default_stream_);
3046 }
3047 media_streams.push_back(missing_msid_default_stream_);
3048 }
3049 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3050 receiver->streams();
3051 // SetStreams() will add/remove the receiver's track to/from the streams. This
3052 // differs from the spec - the spec uses an "addList" and "removeList" to
3053 // update the stream-track relationships in a later step. We do this earlier,
3054 // changing the order of things, but the end-result is the same.
3055 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3056 // instead. https://crbug.com/webrtc/9480
3057 receiver->SetStreams(media_streams);
3058 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3059}
3060
Steve Anton0f5400a2018-07-17 14:25:36 -07003061void PeerConnection::ProcessRemovalOfRemoteTrack(
3062 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3063 transceiver,
3064 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3065 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3066 RTC_DCHECK(transceiver->mid());
3067 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3068 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003069 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003070 transceiver->internal()->receiver_internal()->streams();
3071 // This will remove the remote track from the streams.
3072 transceiver->internal()->receiver_internal()->set_stream_ids({});
3073 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003074 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3075}
3076
3077void PeerConnection::RemoveRemoteStreamsIfEmpty(
3078 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3079 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3080 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3081 // streams, see if the stream was removed by checking if this was the last
3082 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003083 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003084 if (remote_stream->GetAudioTracks().empty() &&
3085 remote_stream->GetVideoTracks().empty()) {
3086 remote_streams_->RemoveStream(remote_stream);
3087 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003088 }
3089 }
3090}
3091
Steve Antondcc3c022017-12-22 16:02:54 -08003092RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3093 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003094 const SessionDescriptionInterface& new_session,
3095 const SessionDescriptionInterface* old_local_description,
3096 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003097 RTC_DCHECK(IsUnifiedPlan());
3098
Steve Anton7464fca2018-01-19 11:10:37 -08003099 const cricket::ContentGroup* bundle_group = nullptr;
3100 if (new_session.GetType() == SdpType::kOffer) {
3101 auto bundle_group_or_error =
3102 GetEarlyBundleGroup(*new_session.description());
3103 if (!bundle_group_or_error.ok()) {
3104 return bundle_group_or_error.MoveError();
3105 }
3106 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003107 }
Steve Antondcc3c022017-12-22 16:02:54 -08003108
Steve Antondcc3c022017-12-22 16:02:54 -08003109 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003110 for (size_t i = 0; i < new_contents.size(); ++i) {
3111 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003112 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003113 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003114 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3115 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003116 const cricket::ContentInfo* old_local_content = nullptr;
3117 if (old_local_description &&
3118 i < old_local_description->description()->contents().size()) {
3119 old_local_content =
3120 &old_local_description->description()->contents()[i];
3121 }
3122 const cricket::ContentInfo* old_remote_content = nullptr;
3123 if (old_remote_description &&
3124 i < old_remote_description->description()->contents().size()) {
3125 old_remote_content =
3126 &old_remote_description->description()->contents()[i];
3127 }
Steve Antondcc3c022017-12-22 16:02:54 -08003128 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003129 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3130 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003131 if (!transceiver_or_error.ok()) {
3132 return transceiver_or_error.MoveError();
3133 }
3134 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003135 RTCError error =
3136 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3137 if (!error.ok()) {
3138 return error;
3139 }
3140 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003141 if (GetDataMid() && new_content.name != *GetDataMid()) {
3142 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003143 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3144 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003145 continue;
3146 }
3147 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3148 if (!error.ok()) {
3149 return error;
3150 }
Steve Antondcc3c022017-12-22 16:02:54 -08003151 } else {
3152 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3153 "Unknown section type.");
3154 }
3155 }
3156
3157 return RTCError::OK();
3158}
3159
3160RTCError PeerConnection::UpdateTransceiverChannel(
3161 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3162 transceiver,
3163 const cricket::ContentInfo& content,
3164 const cricket::ContentGroup* bundle_group) {
3165 RTC_DCHECK(IsUnifiedPlan());
3166 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003167 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003168 if (content.rejected) {
3169 if (channel) {
3170 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003171 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003172 }
3173 } else {
3174 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003175 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003176 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003177 } else {
Steve Anton69470252018-02-09 11:43:08 -08003178 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003179 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003180 }
3181 if (!channel) {
3182 LOG_AND_RETURN_ERROR(
3183 RTCErrorType::INTERNAL_ERROR,
3184 "Failed to create channel for mid=" + content.name);
3185 }
3186 transceiver->internal()->SetChannel(channel);
3187 }
3188 }
3189 return RTCError::OK();
3190}
3191
Steve Antonfa2260d2017-12-28 16:38:23 -08003192RTCError PeerConnection::UpdateDataChannel(
3193 cricket::ContentSource source,
3194 const cricket::ContentInfo& content,
3195 const cricket::ContentGroup* bundle_group) {
3196 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003197 // If data channels are disabled, ignore this media section. CreateAnswer
3198 // will take care of rejecting it.
3199 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003200 }
3201 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003202 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003203 DestroyDataChannel();
3204 } else {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003205 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
3206 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003207 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003208 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3209 "Failed to create data channel.");
3210 }
3211 }
3212 if (source == cricket::CS_REMOTE) {
3213 const MediaContentDescription* data_desc = content.media_description();
3214 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3215 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3216 }
3217 }
3218 }
3219 return RTCError::OK();
3220}
3221
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003222// This method will extract any send encodings that were sent by the remote
3223// connection. This is currently only relevant for Simulcast scenario (where
3224// the number of layers may be communicated by the server).
3225static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3226 const MediaContentDescription& desc) {
3227 if (!desc.HasSimulcast()) {
3228 return {};
3229 }
3230 std::vector<RtpEncodingParameters> result;
3231 const SimulcastDescription& simulcast = desc.simulcast_description();
3232
3233 // This is a remote description, the parameters we are after should appear
3234 // as receive streams.
3235 for (const auto& alternatives : simulcast.receive_layers()) {
3236 RTC_DCHECK(!alternatives.empty());
3237 // There is currently no way to specify or choose from alternatives.
3238 // We will always use the first alternative, which is the most preferred.
3239 const SimulcastLayer& layer = alternatives[0];
3240 RtpEncodingParameters parameters;
3241 parameters.rid = layer.rid;
3242 parameters.active = !layer.is_paused;
3243 result.push_back(parameters);
3244 }
3245
3246 return result;
3247}
3248
3249static RTCError UpdateSimulcastLayerStatusInSender(
3250 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003251 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003252 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003253 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003254 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003255
3256 // The simulcast envelope cannot be changed, only the status of the streams.
3257 // So we will iterate over the send encodings rather than the layers.
3258 for (RtpEncodingParameters& encoding : parameters.encodings) {
3259 auto iter = std::find_if(layers.begin(), layers.end(),
3260 [&encoding](const SimulcastLayer& layer) {
3261 return layer.rid == encoding.rid;
3262 });
3263 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003264 if (iter == layers.end()) {
3265 disabled_layers.push_back(encoding.rid);
3266 continue;
3267 }
3268
3269 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003270 }
3271
Amit Hilbuch619b2942019-02-26 15:55:19 -08003272 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003273 if (result.ok()) {
3274 result = sender->DisableEncodingLayers(disabled_layers);
3275 }
3276
3277 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003278}
3279
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003280static bool SimulcastIsRejected(
3281 const ContentInfo* local_content,
3282 const MediaContentDescription& answer_media_desc) {
3283 bool simulcast_offered = local_content &&
3284 local_content->media_description() &&
3285 local_content->media_description()->HasSimulcast();
3286 bool simulcast_answered = answer_media_desc.HasSimulcast();
3287 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3288 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3289 return simulcast_offered && (!simulcast_answered || !rids_supported);
3290}
3291
Amit Hilbuch2297d332019-02-19 12:49:22 -08003292static RTCError DisableSimulcastInSender(
3293 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003294 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003295 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003296 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003297 return RTCError::OK();
3298 }
3299
Amit Hilbuch2297d332019-02-19 12:49:22 -08003300 std::vector<std::string> disabled_layers;
3301 std::transform(
3302 parameters.encodings.begin() + 1, parameters.encodings.end(),
3303 std::back_inserter(disabled_layers),
3304 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3305 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003306}
3307
Steve Antondcc3c022017-12-22 16:02:54 -08003308RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3309PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003310 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003311 size_t mline_index,
3312 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003313 const ContentInfo* old_local_content,
3314 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003315 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003316 // If this is an offer then the m= section might be recycled. If the m=
3317 // section is being recycled (defined as: rejected in the current local or
3318 // remote description and not rejected in new description), dissociate the
3319 // currently associated RtpTransceiver by setting its mid property to null,
3320 // and discard the mapping between the transceiver and its m= section index.
3321 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3322 old_remote_content)) {
3323 // We want to dissociate the transceiver that has the rejected mid.
3324 const std::string& old_mid =
3325 (old_local_content && old_local_content->rejected)
3326 ? old_local_content->name
3327 : old_remote_content->name;
3328 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003329 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003330 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3331 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003332 old_transceiver->internal()->set_mid(absl::nullopt);
3333 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003334 }
3335 }
3336 const MediaContentDescription* media_desc = content.media_description();
3337 auto transceiver = GetAssociatedTransceiver(content.name);
3338 if (source == cricket::CS_LOCAL) {
3339 // Find the RtpTransceiver that corresponds to this m= section, using the
3340 // mapping between transceivers and m= section indices established when
3341 // creating the offer.
3342 if (!transceiver) {
3343 transceiver = GetTransceiverByMLineIndex(mline_index);
3344 }
3345 if (!transceiver) {
3346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3347 "Unknown transceiver");
3348 }
3349 } else {
3350 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3351 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3352 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003353 // When simulcast is requested, a transceiver cannot be associated because
3354 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003355 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003356 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3357 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003358 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3359 }
3360 // If no RtpTransceiver was found in the previous step, create one with a
3361 // recvonly direction.
3362 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003363 RTC_LOG(LS_INFO) << "Adding "
3364 << cricket::MediaTypeToString(media_desc->type())
3365 << " transceiver for MID=" << content.name
3366 << " at i=" << mline_index
3367 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003368 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003369 std::vector<RtpEncodingParameters> send_encodings =
3370 GetSendEncodingsFromRemoteDescription(*media_desc);
3371 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3372 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003373 std::string receiver_id;
3374 if (!media_desc->streams().empty()) {
3375 receiver_id = media_desc->streams()[0].id;
3376 } else {
3377 receiver_id = rtc::CreateRandomUuid();
3378 }
3379 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003380 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003381 transceiver->internal()->set_direction(
3382 RtpTransceiverDirection::kRecvOnly);
3383 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003384
3385 // Check if the offer indicated simulcast but the answer rejected it.
3386 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003387 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003388 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003389 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003390 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003391 if (!error.ok()) {
3392 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3393 return std::move(error);
3394 }
3395 }
Steve Antondcc3c022017-12-22 16:02:54 -08003396 }
3397 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003398 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003399 LOG_AND_RETURN_ERROR(
3400 RTCErrorType::INVALID_PARAMETER,
3401 "Transceiver type does not match media description type.");
3402 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003403 if (media_desc->HasSimulcast()) {
3404 std::vector<SimulcastLayer> layers =
3405 source == cricket::CS_LOCAL
3406 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3407 : media_desc->simulcast_description()
3408 .receive_layers()
3409 .GetAllLayers();
3410 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003411 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003412 if (!error.ok()) {
3413 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3414 return std::move(error);
3415 }
3416 }
Steve Antondcc3c022017-12-22 16:02:54 -08003417 // Associate the found or created RtpTransceiver with the m= section by
3418 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3419 // section, and establish a mapping between the transceiver and the index of
3420 // the m= section.
3421 transceiver->internal()->set_mid(content.name);
3422 transceiver->internal()->set_mline_index(mline_index);
3423 return std::move(transceiver);
3424}
3425
3426rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3427PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3428 RTC_DCHECK(IsUnifiedPlan());
3429 for (auto transceiver : transceivers_) {
3430 if (transceiver->mid() == mid) {
3431 return transceiver;
3432 }
3433 }
3434 return nullptr;
3435}
3436
3437rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3438PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3439 RTC_DCHECK(IsUnifiedPlan());
3440 for (auto transceiver : transceivers_) {
3441 if (transceiver->internal()->mline_index() == mline_index) {
3442 return transceiver;
3443 }
3444 }
3445 return nullptr;
3446}
3447
3448rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3449PeerConnection::FindAvailableTransceiverToReceive(
3450 cricket::MediaType media_type) const {
3451 RTC_DCHECK(IsUnifiedPlan());
3452 // From JSEP section 5.10 (Applying a Remote Description):
3453 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3454 // the same type that were added to the PeerConnection by addTrack and are not
3455 // associated with any m= section and are not stopped, find the first such
3456 // RtpTransceiver.
3457 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003458 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003459 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3460 !transceiver->stopped()) {
3461 return transceiver;
3462 }
3463 }
3464 return nullptr;
3465}
3466
Steve Antoned10bd92017-12-05 10:52:59 -08003467const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3468 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3469 transceiver,
3470 const SessionDescriptionInterface* sdesc) const {
3471 RTC_DCHECK(transceiver);
3472 RTC_DCHECK(sdesc);
3473 if (IsUnifiedPlan()) {
3474 if (!transceiver->internal()->mid()) {
3475 // This transceiver is not associated with a media section yet.
3476 return nullptr;
3477 }
3478 return sdesc->description()->GetContentByName(
3479 *transceiver->internal()->mid());
3480 } else {
3481 // Plan B only allows at most one audio and one video section, so use the
3482 // first media section of that type.
3483 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003484 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003485 }
3486}
3487
deadbeef46c73892016-11-16 19:42:04 -08003488PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003489 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003490 return configuration_;
3491}
3492
deadbeef293e9262017-01-11 12:28:30 -08003493bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3494 RTCError* error) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003495 RTCError result = SetConfiguration(configuration);
3496 bool success = result.ok();
3497 if (error) {
3498 *error = std::move(result);
3499 }
3500 return success;
3501}
3502
3503RTCError PeerConnection::SetConfiguration(
3504 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003505 RTC_DCHECK_RUN_ON(signaling_thread());
3506 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003507 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003508 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003509 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3510 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003511 }
3512
Qingsi Wanga2d60672018-04-11 16:57:45 -07003513 // According to JSEP, after setLocalDescription, changing the candidate pool
3514 // size is not allowed, and changing the set of ICE servers will not result
3515 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003516 if (local_description() && configuration.ice_candidate_pool_size !=
3517 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3519 "Can't change candidate pool size after calling "
3520 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003521 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003522
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003523 if (local_description() &&
3524 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003525 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3526 "Can't change media_transport after calling "
3527 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003528 }
3529
3530 if (remote_description() &&
3531 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3533 "Can't change media_transport after calling "
3534 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003535 }
3536
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003537 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003538 configuration.use_media_transport_for_data_channels !=
3539 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003540 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3541 "Can't change media_transport_for_data_channels "
3542 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003543 }
3544
3545 if (remote_description() &&
3546 configuration.use_media_transport_for_data_channels !=
3547 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003548 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3549 "Can't change media_transport_for_data_channels "
3550 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003551 }
3552
3553 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003554 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003555 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3556 "Can't change crypto_options after calling "
3557 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003558 }
3559
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003560 if (local_description() && configuration.use_datagram_transport !=
3561 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003562 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3563 "Can't change use_datagram_transport "
3564 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003565 }
3566
3567 if (remote_description() && configuration.use_datagram_transport !=
3568 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003569 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3570 "Can't change use_datagram_transport "
3571 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003572 }
3573
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003574 if (local_description() &&
3575 configuration.use_datagram_transport_for_data_channels !=
3576 configuration_.use_datagram_transport_for_data_channels) {
3577 LOG_AND_RETURN_ERROR(
3578 RTCErrorType::INVALID_MODIFICATION,
3579 "Can't change use_datagram_transport_for_data_channels "
3580 "after calling SetLocalDescription.");
3581 }
3582
3583 if (remote_description() &&
3584 configuration.use_datagram_transport_for_data_channels !=
3585 configuration_.use_datagram_transport_for_data_channels) {
3586 LOG_AND_RETURN_ERROR(
3587 RTCErrorType::INVALID_MODIFICATION,
3588 "Can't change use_datagram_transport_for_data_channels "
3589 "after calling SetRemoteDescription.");
3590 }
3591
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003592 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003593 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003594 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003595 *configuration.use_datagram_transport) ||
3596 (configuration.use_datagram_transport_for_data_channels &&
3597 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003598 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3599 << "Media transport requires MaxBundle policy.";
3600 }
3601
deadbeef293e9262017-01-11 12:28:30 -08003602 // The simplest (and most future-compatible) way to tell if the config was
3603 // modified in an invalid way is to copy each property we do support
3604 // modifying, then use operator==. There are far more properties we don't
3605 // support modifying than those we do, and more could be added.
3606 RTCConfiguration modified_config = configuration_;
3607 modified_config.servers = configuration.servers;
3608 modified_config.type = configuration.type;
3609 modified_config.ice_candidate_pool_size =
3610 configuration.ice_candidate_pool_size;
3611 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003612 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3613 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003614 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003615 modified_config.ice_check_interval_strong_connectivity =
3616 configuration.ice_check_interval_strong_connectivity;
3617 modified_config.ice_check_interval_weak_connectivity =
3618 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003619 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3620 modified_config.ice_unwritable_min_checks =
3621 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003622 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003623 modified_config.stun_candidate_keepalive_interval =
3624 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003625 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003626 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003627 modified_config.active_reset_srtp_params =
3628 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003629 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003630 modified_config.use_media_transport_for_data_channels =
3631 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003632 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003633 modified_config.use_datagram_transport_for_data_channels =
3634 configuration.use_datagram_transport_for_data_channels;
Jonas Oreland3c028422019-08-22 16:16:35 +02003635 modified_config.turn_logging_id = configuration.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -08003636 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003637 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3638 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003639 }
3640
Steve Anton038834f2017-07-14 15:59:59 -07003641 // Validate the modified configuration.
3642 RTCError validate_error = ValidateConfiguration(modified_config);
3643 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003644 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003645 }
3646
deadbeef293e9262017-01-11 12:28:30 -08003647 // Note that this isn't possible through chromium, since it's an unsigned
3648 // short in WebIDL.
3649 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003650 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003651 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003652 }
3653
3654 // Parse ICE servers before hopping to network thread.
3655 cricket::ServerAddresses stun_servers;
3656 std::vector<cricket::RelayServerConfig> turn_servers;
3657 RTCErrorType parse_error =
3658 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3659 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003660 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003661 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003662 // Add the turn logging id to all turn servers
3663 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3664 turn_server.turn_logging_id = configuration.turn_logging_id;
3665 }
3666
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003667 // Note if STUN or TURN servers were supplied.
3668 if (!stun_servers.empty()) {
3669 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3670 }
3671 if (!turn_servers.empty()) {
3672 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3673 }
deadbeef293e9262017-01-11 12:28:30 -08003674
3675 // In theory this shouldn't fail.
3676 if (!network_thread()->Invoke<bool>(
3677 RTC_FROM_HERE,
3678 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3679 stun_servers, turn_servers, modified_config.type,
3680 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003681 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003682 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003683 modified_config.stun_candidate_keepalive_interval,
3684 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003685 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3686 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003687 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003688
deadbeefd1a38b52016-12-10 13:15:33 -08003689 // As described in JSEP, calling setConfiguration with new ICE servers or
3690 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3691 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003692 if (modified_config.servers != configuration_.servers ||
3693 modified_config.type != configuration_.type ||
3694 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003695 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003696 }
skvladd1f5fda2017-02-03 16:54:05 -08003697
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003698 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003699
3700 use_datagram_transport_ = datagram_transport_config_.enabled &&
3701 modified_config.use_datagram_transport.value_or(
3702 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003703 use_datagram_transport_for_data_channels_ =
3704 datagram_transport_data_channel_config_.enabled &&
3705 modified_config.use_datagram_transport_for_data_channels.value_or(
3706 datagram_transport_data_channel_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003707 transport_controller_->SetMediaTransportSettings(
3708 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003709 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003710 use_datagram_transport_, use_datagram_transport_for_data_channels_);
skvladd1f5fda2017-02-03 16:54:05 -08003711
Zhi Huangb57e1692018-06-12 11:41:11 -07003712 if (configuration_.active_reset_srtp_params !=
3713 modified_config.active_reset_srtp_params) {
3714 transport_controller_->SetActiveResetSrtpParams(
3715 modified_config.active_reset_srtp_params);
3716 }
3717
deadbeef293e9262017-01-11 12:28:30 -08003718 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003719 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003720 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003721}
3722
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003723bool PeerConnection::AddIceCandidate(
3724 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003725 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003726 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003727 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003728 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003729 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003730 return false;
3731 }
Steve Antond25da372017-11-06 14:50:29 -08003732
3733 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003734 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003735 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003736 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003737 return false;
3738 }
3739
3740 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003741 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003742 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003743 return false;
3744 }
3745
3746 bool valid = false;
3747 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3748 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003749 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003750 return false;
3751 }
3752
3753 // Add this candidate to the remote session description.
3754 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003755 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003756 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003757 return false;
3758 }
3759
3760 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003761 bool result = UseCandidate(ice_candidate);
3762 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003763 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003764 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3765 } else {
3766 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3767 }
3768 return result;
Steve Antond25da372017-11-06 14:50:29 -08003769 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003770 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003771 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003772 return true;
3773 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003774}
3775
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003776bool PeerConnection::RemoveIceCandidates(
3777 const std::vector<cricket::Candidate>& candidates) {
3778 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003779 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003780 if (IsClosed()) {
3781 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3782 return false;
3783 }
3784
Steve Antond25da372017-11-06 14:50:29 -08003785 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003786 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3787 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003788 return false;
3789 }
3790
3791 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003792 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003793 return false;
3794 }
3795
3796 size_t number_removed =
3797 mutable_remote_description()->RemoveCandidates(candidates);
3798 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003799 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003800 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003801 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003802 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003803 }
3804
3805 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003806 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3807 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003808 RTC_LOG(LS_ERROR)
3809 << "RemoveIceCandidates: Error when removing remote candidates: "
3810 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003811 }
3812 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003813}
3814
Niels Möller0c4f7be2018-05-07 14:01:37 +02003815RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003816 if (!worker_thread()->IsCurrent()) {
3817 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003818 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003819 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003820 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003821
Niels Möller0c4f7be2018-05-07 14:01:37 +02003822 const bool has_min = bitrate.min_bitrate_bps.has_value();
3823 const bool has_start = bitrate.start_bitrate_bps.has_value();
3824 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003825 if (has_min && *bitrate.min_bitrate_bps < 0) {
3826 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3827 "min_bitrate_bps <= 0");
3828 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003829 if (has_start) {
3830 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003831 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003832 "start_bitrate_bps < min_bitrate_bps");
3833 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003834 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3835 "curent_bitrate_bps < 0");
3836 }
3837 }
3838 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003839 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003840 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003841 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003842 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3843 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3844 "max_bitrate_bps < min_bitrate_bps");
3845 } else if (*bitrate.max_bitrate_bps < 0) {
3846 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3847 "max_bitrate_bps < 0");
3848 }
3849 }
3850
zstein4b979802017-06-02 14:37:37 -07003851 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003852 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003853
3854 return RTCError::OK();
3855}
3856
henrika5f6bf242017-11-01 11:06:56 +01003857void PeerConnection::SetAudioPlayout(bool playout) {
3858 if (!worker_thread()->IsCurrent()) {
3859 worker_thread()->Invoke<void>(
3860 RTC_FROM_HERE,
3861 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3862 return;
3863 }
3864 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003865 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003866 audio_state->SetPlayout(playout);
3867}
3868
3869void PeerConnection::SetAudioRecording(bool recording) {
3870 if (!worker_thread()->IsCurrent()) {
3871 worker_thread()->Invoke<void>(
3872 RTC_FROM_HERE,
3873 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3874 return;
3875 }
3876 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003877 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003878 audio_state->SetRecording(recording);
3879}
3880
Steve Anton8c0f7a72017-10-03 10:03:10 -07003881std::unique_ptr<rtc::SSLCertificate>
3882PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003883 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3884 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003885 return nullptr;
3886 }
Steve Antonf25303e2018-10-16 15:23:31 -07003887 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003888}
3889
Zhi Huang70b820f2018-01-27 14:16:15 -08003890std::unique_ptr<rtc::SSLCertChain>
3891PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003892 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003893 auto audio_transceiver = GetFirstAudioTransceiver();
3894 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003895 return nullptr;
3896 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003897 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003898 audio_transceiver->internal()->channel()->transport_name());
3899}
3900
3901rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3902PeerConnection::GetFirstAudioTransceiver() const {
3903 for (auto transceiver : transceivers_) {
3904 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3905 return transceiver;
3906 }
3907 }
3908 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003909}
3910
Bjorn Tereliusde939432017-11-20 17:38:14 +01003911bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3912 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003913 // TODO(eladalon): In C++14, this can be done with a lambda.
3914 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003915 bool operator()() {
3916 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3917 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003918 PeerConnection* const pc;
3919 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003920 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003921 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003922 return worker_thread()->Invoke<bool>(
3923 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003924}
3925
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003926bool PeerConnection::StartRtcEventLog(
3927 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003928 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3929 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3930 output_period_ms = 5000;
3931 }
3932 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003933}
3934
ivoc14d5dbe2016-07-04 07:06:55 -07003935void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003936 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003937 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3938}
3939
Harald Alvestrandad88c882018-11-28 16:47:46 +01003940rtc::scoped_refptr<DtlsTransportInterface>
3941PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003942 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003943 return transport_controller_->LookupDtlsTransportByMid(mid);
3944}
3945
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003946rtc::scoped_refptr<DtlsTransport>
3947PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003948 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003949 return transport_controller_->LookupDtlsTransportByMid(mid);
3950}
3951
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003952rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3953 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003954 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003955 return sctp_transport_;
3956}
3957
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003958const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003959 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003960 return pending_local_description_ ? pending_local_description_.get()
3961 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003962}
3963
3964const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003965 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003966 return pending_remote_description_ ? pending_remote_description_.get()
3967 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003968}
3969
deadbeeffe4a8a42016-12-20 17:56:17 -08003970const SessionDescriptionInterface* PeerConnection::current_local_description()
3971 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003972 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003973 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003974}
3975
3976const SessionDescriptionInterface* PeerConnection::current_remote_description()
3977 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003978 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003979 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003980}
3981
3982const SessionDescriptionInterface* PeerConnection::pending_local_description()
3983 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003984 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003985 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003986}
3987
3988const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3989 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003990 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003991 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003992}
3993
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003994void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003995 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003996 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003997 // Update stats here so that we have the most recent stats for tracks and
3998 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003999 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004000
Steve Anton75737c02017-11-06 10:37:17 -08004001 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004002 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004003
Mirko Bonadei739baf02019-01-27 17:29:42 +01004004 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004005 transceiver->Stop();
4006 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004007
4008 // Ensure that all asynchronous stats requests are completed before destroying
4009 // the transport controller below.
4010 if (stats_collector_) {
4011 stats_collector_->WaitForPendingRequest();
4012 }
4013
4014 // Don't destroy BaseChannels until after stats has been cleaned up so that
4015 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004016 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004017
Qingsi Wang93a84392018-01-30 17:13:09 -08004018 // The event log is used in the transport controller, which must be outlived
4019 // by the former. CreateOffer by the peer connection is implemented
4020 // asynchronously and if the peer connection is closed without resetting the
4021 // WebRTC session description factory, the session description factory would
4022 // call the transport controller.
4023 webrtc_session_desc_factory_.reset();
4024 transport_controller_.reset();
4025
deadbeef42a42632017-03-10 15:18:00 -08004026 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004027 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4028 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004029
Steve Anton978b8762017-09-29 12:15:02 -07004030 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004031 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004032 call_.reset();
4033 // The event log must outlive call (and any other object that uses it).
4034 event_log_.reset();
4035 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004036 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004037 // The .h file says that observer can be discarded after close() returns.
4038 // Make sure this is true.
4039 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004040}
4041
Steve Antonad182762018-09-05 20:22:40 +00004042void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004043 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004044 switch (msg->message_id) {
4045 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4046 SetSessionDescriptionMsg* param =
4047 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4048 param->observer->OnSuccess();
4049 delete param;
4050 break;
4051 }
4052 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4053 SetSessionDescriptionMsg* param =
4054 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4055 param->observer->OnFailure(std::move(param->error));
4056 delete param;
4057 break;
4058 }
4059 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4060 CreateSessionDescriptionMsg* param =
4061 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4062 param->observer->OnFailure(std::move(param->error));
4063 delete param;
4064 break;
4065 }
4066 case MSG_GETSTATS: {
4067 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4068 StatsReports reports;
4069 stats_->GetStats(param->track, &reports);
4070 param->observer->OnComplete(reports);
4071 delete param;
4072 break;
4073 }
4074 case MSG_FREE_DATACHANNELS: {
4075 sctp_data_channels_to_free_.clear();
4076 break;
4077 }
4078 case MSG_REPORT_USAGE_PATTERN: {
4079 ReportUsagePattern();
4080 break;
4081 }
4082 default:
4083 RTC_NOTREACHED() << "Not implemented";
4084 break;
4085 }
4086}
4087
Steve Antonafb0bb72018-02-20 11:35:37 -08004088cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4089 RTC_DCHECK(!IsUnifiedPlan());
4090 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4091 GetAudioTransceiver()->internal()->channel());
4092 if (voice_channel) {
4093 return voice_channel->media_channel();
4094 } else {
4095 return nullptr;
4096 }
4097}
4098
4099cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4100 RTC_DCHECK(!IsUnifiedPlan());
4101 auto* video_channel = static_cast<cricket::VideoChannel*>(
4102 GetVideoTransceiver()->internal()->channel());
4103 if (video_channel) {
4104 return video_channel->media_channel();
4105 } else {
4106 return nullptr;
4107 }
4108}
4109
Steve Anton4171afb2017-11-20 10:20:22 -08004110void PeerConnection::CreateAudioReceiver(
4111 MediaStreamInterface* stream,
4112 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004113 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4114 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004115 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4116 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004117 auto* audio_receiver = new AudioRtpReceiver(
4118 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004119 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004120 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4121 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4122 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004123 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004124 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004125 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004126}
4127
Steve Anton4171afb2017-11-20 10:20:22 -08004128void PeerConnection::CreateVideoReceiver(
4129 MediaStreamInterface* stream,
4130 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004131 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4132 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004133 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4134 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004135 auto* video_receiver = new VideoRtpReceiver(
4136 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004137 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004138 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4139 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4140 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004141 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004142 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004143 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004144}
4145
deadbeef70ab1a12015-09-28 16:53:55 -07004146// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4147// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004148rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004149 const RtpSenderInfo& remote_sender_info) {
4150 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4151 if (!receiver) {
4152 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4153 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004154 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004155 }
Steve Anton4171afb2017-11-20 10:20:22 -08004156 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4157 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4158 } else {
4159 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4160 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004161 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004162}
4163
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004164void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4165 MediaStreamInterface* stream) {
4166 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004167 RTC_DCHECK(track);
4168 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004169 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004170 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004171 // We already have a sender for this track, so just change the stream_id
4172 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004173 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004174 return;
4175 }
4176
4177 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004178 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004179 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004180 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004181 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004182 // If the sender has already been configured in SDP, we call SetSsrc,
4183 // which will connect the sender to the underlying transport. This can
4184 // occur if a local session description that contains the ID of the sender
4185 // is set before AddStream is called. It can also occur if the local
4186 // session description is not changed and RemoveStream is called, and
4187 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004188 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004189 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004190 if (sender_info) {
4191 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004192 }
4193}
4194
4195// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4196// indefinitely, when we have unified plan SDP.
4197void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4198 MediaStreamInterface* stream) {
4199 RTC_DCHECK(!IsClosed());
4200 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004201 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004202 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4203 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004204 return;
4205 }
Steve Anton4171afb2017-11-20 10:20:22 -08004206 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004207}
4208
4209void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4210 MediaStreamInterface* stream) {
4211 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004212 RTC_DCHECK(track);
4213 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004214 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004215 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004216 // We already have a sender for this track, so just change the stream_id
4217 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004218 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004219 return;
4220 }
4221
4222 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004223 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004224 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004225 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004226 GetVideoTransceiver()->internal()->AddSender(new_sender);
4227 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004228 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004229 if (sender_info) {
4230 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004231 }
4232}
4233
4234void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4235 MediaStreamInterface* stream) {
4236 RTC_DCHECK(!IsClosed());
4237 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004238 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004239 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4240 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004241 return;
4242 }
Steve Anton4171afb2017-11-20 10:20:22 -08004243 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004244}
4245
Steve Antonba818672017-11-06 10:21:57 -08004246void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004247 if (ice_connection_state_ == new_state) {
4248 return;
4249 }
4250
deadbeefcbecd352015-09-23 11:50:27 -07004251 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004252 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004253 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004254 return;
4255 }
Steve Antonba818672017-11-06 10:21:57 -08004256
Mirko Bonadei675513b2017-11-09 11:09:25 +01004257 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4258 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004259 RTC_DCHECK(ice_connection_state_ !=
4260 PeerConnectionInterface::kIceConnectionClosed);
4261
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004262 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004263 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004264}
4265
Alex Loiko9289eda2018-11-23 16:18:59 +00004266void PeerConnection::SetStandardizedIceConnectionState(
4267 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004268 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004269 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004270 }
4271
4272 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004273 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004274 }
4275
4276 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4277 << standardized_ice_connection_state_ << " => " << new_state;
4278
Alex Loiko9289eda2018-11-23 16:18:59 +00004279 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004280 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004281}
4282
Jonas Olsson635474e2018-10-18 15:58:17 +02004283void PeerConnection::SetConnectionState(
4284 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004285 if (connection_state_ == new_state)
4286 return;
4287 if (IsClosed())
4288 return;
4289 connection_state_ = new_state;
4290 Observer()->OnConnectionChange(new_state);
4291}
4292
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004293void PeerConnection::OnIceGatheringChange(
4294 PeerConnectionInterface::IceGatheringState new_state) {
4295 if (IsClosed()) {
4296 return;
4297 }
4298 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004299 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004300}
4301
jbauch81bf7b02017-03-25 08:31:12 -07004302void PeerConnection::OnIceCandidate(
4303 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004304 if (IsClosed()) {
4305 return;
4306 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004307 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004308 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004309}
4310
Eldar Relloda13ea22019-06-01 12:23:43 +03004311void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4312 const std::string& url,
4313 int error_code,
4314 const std::string& error_text) {
4315 if (IsClosed()) {
4316 return;
4317 }
4318 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4319}
4320
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004321void PeerConnection::OnIceCandidatesRemoved(
4322 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004323 if (IsClosed()) {
4324 return;
4325 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004326 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004327}
4328
Alex Drake00c7ecf2019-08-06 10:54:47 -07004329void PeerConnection::OnSelectedCandidatePairChanged(
4330 const cricket::CandidatePairChangeEvent& event) {
4331 if (IsClosed()) {
4332 return;
4333 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004334
Alex Drake00c7ecf2019-08-06 10:54:47 -07004335 Observer()->OnIceSelectedCandidatePairChanged(event);
4336}
4337
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004338void PeerConnection::ChangeSignalingState(
4339 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004340 if (signaling_state_ == signaling_state) {
4341 return;
4342 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004343 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4344 << GetSignalingStateString(signaling_state_)
4345 << " New state: "
4346 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004347 signaling_state_ = signaling_state;
4348 if (signaling_state == kClosed) {
4349 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004350 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004351 standardized_ice_connection_state_ =
4352 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004353 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4354 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004355 if (ice_gathering_state_ != kIceGatheringComplete) {
4356 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004357 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004358 }
4359 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004360 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004361}
4362
deadbeefeb459812015-12-15 19:24:43 -08004363void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4364 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004365 if (IsClosed()) {
4366 return;
4367 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004368 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004369 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004370}
4371
deadbeefeb459812015-12-15 19:24:43 -08004372void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4373 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004374 if (IsClosed()) {
4375 return;
4376 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004377 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004378 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004379}
4380
4381void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4382 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004383 if (IsClosed()) {
4384 return;
4385 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004386 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004387 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004388}
4389
4390void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4391 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004392 if (IsClosed()) {
4393 return;
4394 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004395 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004396 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004397}
4398
Henrik Boström31638672017-11-23 17:48:32 +01004399void PeerConnection::PostSetSessionDescriptionSuccess(
4400 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004401 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4402 signaling_thread()->Post(RTC_FROM_HERE, this,
4403 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004404}
4405
deadbeefab9b2d12015-10-14 11:33:11 -07004406void PeerConnection::PostSetSessionDescriptionFailure(
4407 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004408 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004409 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004410 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4411 msg->error = std::move(error);
4412 signaling_thread()->Post(RTC_FROM_HERE, this,
4413 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004414}
4415
4416void PeerConnection::PostCreateSessionDescriptionFailure(
4417 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004418 RTCError error) {
4419 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004420 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4421 msg->error = std::move(error);
4422 signaling_thread()->Post(RTC_FROM_HERE, this,
4423 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004424}
4425
zhihuang1c378ed2017-08-17 14:10:50 -07004426void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004427 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004428 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004429 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004430
Steve Antondcc3c022017-12-22 16:02:54 -08004431 if (IsUnifiedPlan()) {
4432 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4433 } else {
4434 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4435 }
4436
Steve Antonfa2260d2017-12-28 16:38:23 -08004437 // Intentionally unset the data channel type for RTP data channel with the
4438 // second condition. Otherwise the RTP data channels would be successfully
4439 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4440 // when building with chromium. We want to leave RTP data channels broken, so
4441 // people won't try to use them.
4442 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4443 session_options->data_channel_type = data_channel_type();
4444 }
4445
Steve Antondcc3c022017-12-22 16:02:54 -08004446 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004447 bool ice_restart = offer_answer_options.ice_restart ||
4448 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004449 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004450 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004451 options.transport_options.enable_ice_renomination =
4452 configuration_.enable_ice_renomination;
4453 }
4454
4455 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004456 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004457 session_options->pooled_ice_credentials =
4458 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4459 RTC_FROM_HERE,
4460 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4461 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004462 session_options->offer_extmap_allow_mixed =
4463 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004464
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004465 if (configuration_.use_media_transport ||
4466 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004467 session_options->media_transport_settings =
4468 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4469 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004470
4471 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004472 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004473 for (auto& options : session_options->media_description_options) {
4474 options.transport_options.opaque_parameters =
4475 transport_controller_->GetTransportParameters(options.mid);
4476 }
4477 }
4478
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004479 // Allow fallback for using obsolete SCTP syntax.
4480 // Note that the default in |session_options| is true, while
4481 // the default in |options| is false.
4482 session_options->use_obsolete_sctp_sdp =
4483 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004484}
4485
4486void PeerConnection::GetOptionsForPlanBOffer(
4487 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4488 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004489 // Figure out transceiver directional preferences.
4490 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4491 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4492
4493 // By default, generate sendrecv/recvonly m= sections.
4494 bool recv_audio = true;
4495 bool recv_video = true;
4496
4497 // By default, only offer a new m= section if we have media to send with it.
4498 bool offer_new_audio_description = send_audio;
4499 bool offer_new_video_description = send_video;
4500 bool offer_new_data_description = HasDataChannels();
4501
4502 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004503 if (offer_answer_options.offer_to_receive_audio !=
4504 RTCOfferAnswerOptions::kUndefined) {
4505 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004506 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004507 offer_new_audio_description ||
4508 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004509 }
Steve Antondcc3c022017-12-22 16:02:54 -08004510 if (offer_answer_options.offer_to_receive_video !=
4511 RTCOfferAnswerOptions::kUndefined) {
4512 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004513 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004514 offer_new_video_description ||
4515 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004516 }
4517
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004518 absl::optional<size_t> audio_index;
4519 absl::optional<size_t> video_index;
4520 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004521 // If a current description exists, generate m= sections in the same order,
4522 // using the first audio/video/data section that appears and rejecting
4523 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004524 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004525 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004526 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004527 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4528 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4529 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004530 }
4531
zhihuang1c378ed2017-08-17 14:10:50 -07004532 // Add audio/video/data m= sections to the end if needed.
4533 if (!audio_index && offer_new_audio_description) {
4534 session_options->media_description_options.push_back(
4535 cricket::MediaDescriptionOptions(
4536 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004537 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4538 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004539 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004540 }
zhihuang1c378ed2017-08-17 14:10:50 -07004541 if (!video_index && offer_new_video_description) {
4542 session_options->media_description_options.push_back(
4543 cricket::MediaDescriptionOptions(
4544 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004545 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4546 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004547 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004548 }
zhihuang1c378ed2017-08-17 14:10:50 -07004549 if (!data_index && offer_new_data_description) {
4550 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004551 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004552 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004553 }
4554
4555 cricket::MediaDescriptionOptions* audio_media_description_options =
4556 !audio_index ? nullptr
4557 : &session_options->media_description_options[*audio_index];
4558 cricket::MediaDescriptionOptions* video_media_description_options =
4559 !video_index ? nullptr
4560 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004561
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004562 AddPlanBRtpSenderOptions(GetSendersInternal(),
4563 audio_media_description_options,
4564 video_media_description_options,
4565 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004566}
4567
Steve Antondcc3c022017-12-22 16:02:54 -08004568static cricket::MediaDescriptionOptions
4569GetMediaDescriptionOptionsForTransceiver(
4570 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4571 transceiver,
4572 const std::string& mid) {
4573 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004574 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004575 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004576 media_description_options.codec_preferences =
4577 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004578 // This behavior is specified in JSEP. The gist is that:
4579 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4580 // sendrecv.
4581 // 2. If the MSID is included, then it must be included in any subsequent
4582 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004583 if (transceiver->stopped() ||
4584 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4585 !transceiver->internal()->has_ever_been_used_to_send())) {
4586 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004587 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004588
4589 cricket::SenderOptions sender_options;
4590 sender_options.track_id = transceiver->sender()->id();
4591 sender_options.stream_ids = transceiver->sender()->stream_ids();
4592
4593 // The following sets up RIDs and Simulcast.
4594 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004595 RtpParameters send_parameters =
4596 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004597 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4598 send_parameters.encodings.end(),
4599 [](const RtpEncodingParameters& encoding) {
4600 return !encoding.rid.empty();
4601 });
4602
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004603 std::vector<RidDescription> send_rids;
4604 SimulcastLayerList send_layers;
4605 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4606 if (encoding.rid.empty()) {
4607 continue;
4608 }
4609 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4610 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4611 }
4612
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004613 if (has_rids) {
4614 sender_options.rids = send_rids;
4615 }
4616
4617 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004618 // When RIDs are configured, we must set num_sim_layers to 0 to.
4619 // Otherwise, num_sim_layers must be 1 because either there is no
4620 // simulcast, or simulcast is acheived by munging the SDP.
4621 sender_options.num_sim_layers = has_rids ? 0 : 1;
4622 media_description_options.sender_options.push_back(sender_options);
4623
Steve Antondcc3c022017-12-22 16:02:54 -08004624 return media_description_options;
4625}
4626
Steve Anton5c72e712018-12-10 14:25:30 -08004627// Returns the ContentInfo at mline index |i|, or null if none exists.
4628static const ContentInfo* GetContentByIndex(
4629 const SessionDescriptionInterface* sdesc,
4630 size_t i) {
4631 if (!sdesc) {
4632 return nullptr;
4633 }
4634 const ContentInfos& contents = sdesc->description()->contents();
4635 return (i < contents.size() ? &contents[i] : nullptr);
4636}
4637
Steve Antondcc3c022017-12-22 16:02:54 -08004638void PeerConnection::GetOptionsForUnifiedPlanOffer(
4639 const RTCOfferAnswerOptions& offer_answer_options,
4640 cricket::MediaSessionOptions* session_options) {
4641 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4642 // Offers) and 5.2.2 (Subsequent Offers).
4643 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004644 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004645 const ContentInfos& local_contents =
4646 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004647 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004648 const ContentInfos& remote_contents =
4649 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004650 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004651 // The mline indices that can be recycled. New transceivers should reuse these
4652 // slots first.
4653 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004654 // First, go through each media section that exists in either the local or
4655 // remote description and generate a media section in this offer for the
4656 // associated transceiver. If a media section can be recycled, generate a
4657 // default, rejected media section here that can be later overwritten.
4658 for (size_t i = 0;
4659 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4660 // Either |local_content| or |remote_content| is non-null.
4661 const ContentInfo* local_content =
4662 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004663 const ContentInfo* current_local_content =
4664 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004665 const ContentInfo* remote_content =
4666 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004667 const ContentInfo* current_remote_content =
4668 GetContentByIndex(current_remote_description(), i);
4669 bool had_been_rejected =
4670 (current_local_content && current_local_content->rejected) ||
4671 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004672 const std::string& mid =
4673 (local_content ? local_content->name : remote_content->name);
4674 cricket::MediaType media_type =
4675 (local_content ? local_content->media_description()->type()
4676 : remote_content->media_description()->type());
4677 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4678 media_type == cricket::MEDIA_TYPE_VIDEO) {
4679 auto transceiver = GetAssociatedTransceiver(mid);
4680 RTC_CHECK(transceiver);
4681 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004682 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004683 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004684 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004685 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4686 RtpTransceiverDirection::kInactive,
4687 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004688 recycleable_mline_indices.push(i);
4689 } else {
4690 session_options->media_description_options.push_back(
4691 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4692 // CreateOffer shouldn't really cause any state changes in
4693 // PeerConnection, but we need a way to match new transceivers to new
4694 // media sections in SetLocalDescription and JSEP specifies this is done
4695 // by recording the index of the media section generated for the
4696 // transceiver in the offer.
4697 transceiver->internal()->set_mline_index(i);
4698 }
4699 } else {
4700 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004701 RTC_CHECK(GetDataMid());
4702 if (had_been_rejected || mid != *GetDataMid()) {
4703 session_options->media_description_options.push_back(
4704 GetMediaDescriptionOptionsForRejectedData(mid));
4705 } else {
4706 session_options->media_description_options.push_back(
4707 GetMediaDescriptionOptionsForActiveData(mid));
4708 }
Steve Antondcc3c022017-12-22 16:02:54 -08004709 }
4710 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004711
Steve Antondcc3c022017-12-22 16:02:54 -08004712 // Next, look for transceivers that are newly added (that is, are not stopped
4713 // and not associated). Reuse media sections marked as recyclable first,
4714 // otherwise append to the end of the offer. New media sections should be
4715 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004716 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004717 if (transceiver->mid() || transceiver->stopped()) {
4718 continue;
4719 }
4720 size_t mline_index;
4721 if (!recycleable_mline_indices.empty()) {
4722 mline_index = recycleable_mline_indices.front();
4723 recycleable_mline_indices.pop();
4724 session_options->media_description_options[mline_index] =
4725 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004726 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004727 } else {
4728 mline_index = session_options->media_description_options.size();
4729 session_options->media_description_options.push_back(
4730 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004731 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004732 }
4733 // See comment above for why CreateOffer changes the transceiver's state.
4734 transceiver->internal()->set_mline_index(mline_index);
4735 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004736 // Lastly, add a m-section if we have local data channels and an m section
4737 // does not already exist.
4738 if (!GetDataMid() && HasDataChannels()) {
4739 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004740 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004741 }
Steve Antondcc3c022017-12-22 16:02:54 -08004742}
4743
4744void PeerConnection::GetOptionsForAnswer(
4745 const RTCOfferAnswerOptions& offer_answer_options,
4746 cricket::MediaSessionOptions* session_options) {
4747 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4748
4749 if (IsUnifiedPlan()) {
4750 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4751 } else {
4752 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4753 }
4754
Steve Antonfa2260d2017-12-28 16:38:23 -08004755 // Intentionally unset the data channel type for RTP data channel. Otherwise
4756 // the RTP data channels would be successfully negotiated by default and the
4757 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4758 // We want to leave RTP data channels broken, so people won't try to use them.
4759 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4760 session_options->data_channel_type = data_channel_type();
4761 }
4762
Steve Antondcc3c022017-12-22 16:02:54 -08004763 // Apply ICE renomination flag.
4764 for (auto& options : session_options->media_description_options) {
4765 options.transport_options.enable_ice_renomination =
4766 configuration_.enable_ice_renomination;
4767 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004768
4769 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004770 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004771 session_options->pooled_ice_credentials =
4772 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4773 RTC_FROM_HERE,
4774 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4775 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004776
4777 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004778 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004779 for (auto& options : session_options->media_description_options) {
4780 options.transport_options.opaque_parameters =
4781 transport_controller_->GetTransportParameters(options.mid);
4782 }
4783 }
deadbeefab9b2d12015-10-14 11:33:11 -07004784}
4785
Steve Antondcc3c022017-12-22 16:02:54 -08004786void PeerConnection::GetOptionsForPlanBAnswer(
4787 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004788 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004789 // Figure out transceiver directional preferences.
4790 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4791 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4792
4793 // By default, generate sendrecv/recvonly m= sections. The direction is also
4794 // restricted by the direction in the offer.
4795 bool recv_audio = true;
4796 bool recv_video = true;
4797
4798 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004799 if (offer_answer_options.offer_to_receive_audio !=
4800 RTCOfferAnswerOptions::kUndefined) {
4801 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004802 }
Steve Antondcc3c022017-12-22 16:02:54 -08004803 if (offer_answer_options.offer_to_receive_video !=
4804 RTCOfferAnswerOptions::kUndefined) {
4805 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004806 }
4807
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004808 absl::optional<size_t> audio_index;
4809 absl::optional<size_t> video_index;
4810 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004811
4812 // Generate m= sections that match those in the offer.
4813 // Note that mediasession.cc will handle intersection our preferred
4814 // direction with the offered direction.
4815 GenerateMediaDescriptionOptions(
4816 remote_description(),
4817 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4818 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4819 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004820
4821 cricket::MediaDescriptionOptions* audio_media_description_options =
4822 !audio_index ? nullptr
4823 : &session_options->media_description_options[*audio_index];
4824 cricket::MediaDescriptionOptions* video_media_description_options =
4825 !video_index ? nullptr
4826 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004827
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004828 AddPlanBRtpSenderOptions(GetSendersInternal(),
4829 audio_media_description_options,
4830 video_media_description_options,
4831 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004832}
zhihuangaf388472016-11-02 16:49:48 -07004833
Steve Antondcc3c022017-12-22 16:02:54 -08004834void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4835 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4836 cricket::MediaSessionOptions* session_options) {
4837 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4838 // Answers) and 5.3.2 (Subsequent Answers).
4839 RTC_DCHECK(remote_description());
4840 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4841 for (const ContentInfo& content :
4842 remote_description()->description()->contents()) {
4843 cricket::MediaType media_type = content.media_description()->type();
4844 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4845 media_type == cricket::MEDIA_TYPE_VIDEO) {
4846 auto transceiver = GetAssociatedTransceiver(content.name);
4847 RTC_CHECK(transceiver);
4848 session_options->media_description_options.push_back(
4849 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4850 } else {
4851 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004852 // Reject all data sections if data channels are disabled.
4853 // Reject a data section if it has already been rejected.
4854 // Reject all data sections except for the first one.
4855 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4856 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004857 session_options->media_description_options.push_back(
4858 GetMediaDescriptionOptionsForRejectedData(content.name));
4859 } else {
4860 session_options->media_description_options.push_back(
4861 GetMediaDescriptionOptionsForActiveData(content.name));
4862 }
Steve Antondcc3c022017-12-22 16:02:54 -08004863 }
4864 }
htaa2a49d92016-03-04 02:51:39 -08004865}
4866
zhihuang1c378ed2017-08-17 14:10:50 -07004867void PeerConnection::GenerateMediaDescriptionOptions(
4868 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004869 RtpTransceiverDirection audio_direction,
4870 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004871 absl::optional<size_t>* audio_index,
4872 absl::optional<size_t>* video_index,
4873 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004874 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004875 for (const cricket::ContentInfo& content :
4876 session_desc->description()->contents()) {
4877 if (IsAudioContent(&content)) {
4878 // If we already have an audio m= section, reject this extra one.
4879 if (*audio_index) {
4880 session_options->media_description_options.push_back(
4881 cricket::MediaDescriptionOptions(
4882 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004883 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004884 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004885 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004886 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004887 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4888 content.name, audio_direction,
4889 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004890 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004891 }
4892 } else if (IsVideoContent(&content)) {
4893 // If we already have an video m= section, reject this extra one.
4894 if (*video_index) {
4895 session_options->media_description_options.push_back(
4896 cricket::MediaDescriptionOptions(
4897 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004898 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004899 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004900 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004901 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004902 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4903 content.name, video_direction,
4904 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004905 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004906 }
4907 } else {
4908 RTC_DCHECK(IsDataContent(&content));
4909 // If we already have an data m= section, reject this extra one.
4910 if (*data_index) {
4911 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004912 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004913 } else {
4914 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004915 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004916 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004917 }
4918 }
htaa2a49d92016-03-04 02:51:39 -08004919 }
deadbeefab9b2d12015-10-14 11:33:11 -07004920}
4921
Steve Antonfa2260d2017-12-28 16:38:23 -08004922cricket::MediaDescriptionOptions
4923PeerConnection::GetMediaDescriptionOptionsForActiveData(
4924 const std::string& mid) const {
4925 // Direction for data sections is meaningless, but legacy endpoints might
4926 // expect sendrecv.
4927 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4928 RtpTransceiverDirection::kSendRecv,
4929 /*stopped=*/false);
4930 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4931 return options;
4932}
4933
4934cricket::MediaDescriptionOptions
4935PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4936 const std::string& mid) const {
4937 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4938 RtpTransceiverDirection::kInactive,
4939 /*stopped=*/true);
4940 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4941 return options;
4942}
4943
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004944absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004945 switch (data_channel_type_) {
4946 case cricket::DCT_RTP:
4947 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004948 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004949 }
4950 return rtp_data_channel_->content_name();
4951 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004952 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004953 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
4954 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
4955 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004956 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004957 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004958 }
4959}
4960
Steve Anton4171afb2017-11-20 10:20:22 -08004961void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4962 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4963 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004964 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004965}
4966
Steve Anton4171afb2017-11-20 10:20:22 -08004967void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004968 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004969 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004970 cricket::MediaType media_type,
4971 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004972 RTC_DCHECK(!IsUnifiedPlan());
4973
Steve Anton4171afb2017-11-20 10:20:22 -08004974 std::vector<RtpSenderInfo>* current_senders =
4975 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004976
Steve Anton4171afb2017-11-20 10:20:22 -08004977 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004978 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004979 for (auto sender_it = current_senders->begin();
4980 sender_it != current_senders->end();
4981 /* incremented manually */) {
4982 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004983 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004984 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004985 std::string params_stream_id;
4986 if (params) {
4987 params_stream_id =
4988 (!params->first_stream_id().empty() ? params->first_stream_id()
4989 : kDefaultStreamId);
4990 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004991 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004992 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004993 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004994 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004995 sender_exists) {
4996 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004997 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004998 OnRemoteSenderRemoved(info, media_type);
4999 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005000 }
5001 }
5002
Steve Anton4171afb2017-11-20 10:20:22 -08005003 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005004 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005005 if (!params.has_ssrcs()) {
5006 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5007 // sender, this means it is coming from a Unified Plan endpoint,so we just
5008 // create a default.
5009 default_sender_needed = true;
5010 break;
5011 }
5012
Seth Hampson845e8782018-03-02 11:34:10 -08005013 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005014 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005015 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5016 // not supported in Plan B, we just take the first here and create the
5017 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005018 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005019 (!params.first_stream_id().empty() ? params.first_stream_id()
5020 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005021 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005022 uint32_t ssrc = params.first_ssrc();
5023
5024 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005025 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005026 if (!stream) {
5027 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005028 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005029 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005030 remote_streams_->AddStream(stream);
5031 new_streams->AddStream(stream);
5032 }
5033
Steve Anton4171afb2017-11-20 10:20:22 -08005034 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005035 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005036 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005037 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005038 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005039 }
5040 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005041
Steve Anton4171afb2017-11-20 10:20:22 -08005042 // Add default sender if necessary.
5043 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005044 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005045 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005046 if (!default_stream) {
5047 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005048 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005049 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005050 remote_streams_->AddStream(default_stream);
5051 new_streams->AddStream(default_stream);
5052 }
Steve Anton4171afb2017-11-20 10:20:22 -08005053 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5054 ? kDefaultAudioSenderId
5055 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005056 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005057 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005058 if (!default_sender_info) {
5059 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005060 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005061 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005062 }
5063 }
deadbeefab9b2d12015-10-14 11:33:11 -07005064}
5065
Steve Anton4171afb2017-11-20 10:20:22 -08005066void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5067 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005068 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5069 << " receiver for track_id=" << sender_info.sender_id
5070 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005071
Steve Anton3d954a62018-04-02 11:27:23 -07005072 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005073 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005074 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005075 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005076 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005077 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005078 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005079 }
5080}
5081
Steve Anton4171afb2017-11-20 10:20:22 -08005082void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5083 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005084 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5085 << " receiver for track_id=" << sender_info.sender_id
5086 << " and stream_id=" << sender_info.stream_id;
5087
Seth Hampson845e8782018-03-02 11:34:10 -08005088 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005089
Henrik Boström933d8b02017-10-10 10:05:16 -07005090 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005091 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005092 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5093 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005094 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005095 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005096 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005097 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005098 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005099 }
5100 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005101 // Stopping or destroying a VideoRtpReceiver will end the
5102 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005103 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005104 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005105 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005106 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005107 // There's no guarantee the track is still available, e.g. the track may
5108 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005109 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005110 }
5111 } else {
nisseede5da42017-01-12 05:15:36 -08005112 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005113 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005114 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005115 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005116 }
deadbeefab9b2d12015-10-14 11:33:11 -07005117}
5118
5119void PeerConnection::UpdateEndedRemoteMediaStreams() {
5120 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5121 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5122 MediaStreamInterface* stream = remote_streams_->at(i);
5123 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5124 streams_to_remove.push_back(stream);
5125 }
5126 }
5127
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005128 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005129 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005130 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005131 }
5132}
5133
Steve Anton4171afb2017-11-20 10:20:22 -08005134void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005135 const std::vector<cricket::StreamParams>& streams,
5136 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005137 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005138
Seth Hampson845e8782018-03-02 11:34:10 -08005139 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005140 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005141 for (auto sender_it = current_senders->begin();
5142 sender_it != current_senders->end();
5143 /* incremented manually */) {
5144 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005145 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005146 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5147 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005148 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005149 OnLocalSenderRemoved(info, media_type);
5150 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005151 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005152 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005153 }
5154 }
5155
Steve Anton4171afb2017-11-20 10:20:22 -08005156 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005157 for (const cricket::StreamParams& params : streams) {
5158 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005159 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005160 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005161 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005162 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005163 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005164 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005165 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005166 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005167 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005168 }
5169 }
5170}
5171
Steve Anton4171afb2017-11-20 10:20:22 -08005172void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5173 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005174 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005175 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005176 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005177 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5178 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005179 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005180 return;
5181 }
5182
deadbeeffac06552015-11-25 11:26:01 -08005183 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005184 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005185 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005186 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005187 }
deadbeeffac06552015-11-25 11:26:01 -08005188
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005189 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005190 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005191}
5192
Steve Anton4171afb2017-11-20 10:20:22 -08005193void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5194 cricket::MediaType media_type) {
5195 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005196 if (!sender) {
5197 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005198 // SessionDescriptions has been renegotiated.
5199 return;
5200 }
deadbeeffac06552015-11-25 11:26:01 -08005201
5202 // A sender has been removed from the SessionDescription but it's still
5203 // associated with the PeerConnection. This only occurs if the SDP doesn't
5204 // match with the calls to CreateSender, AddStream and RemoveStream.
5205 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005206 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005207 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005208 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005209 }
deadbeeffac06552015-11-25 11:26:01 -08005210
Steve Anton4171afb2017-11-20 10:20:22 -08005211 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005212}
5213
5214void PeerConnection::UpdateLocalRtpDataChannels(
5215 const cricket::StreamParamsVec& streams) {
5216 std::vector<std::string> existing_channels;
5217
5218 // Find new and active data channels.
5219 for (const cricket::StreamParams& params : streams) {
5220 // |it->sync_label| is actually the data channel label. The reason is that
5221 // we use the same naming of data channels as we do for
5222 // MediaStreams and Tracks.
5223 // For MediaStreams, the sync_label is the MediaStream label and the
5224 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005225 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005226 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005227 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005228 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005229 continue;
5230 }
5231 // Set the SSRC the data channel should use for sending.
5232 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5233 existing_channels.push_back(data_channel_it->first);
5234 }
5235
5236 UpdateClosingRtpDataChannels(existing_channels, true);
5237}
5238
5239void PeerConnection::UpdateRemoteRtpDataChannels(
5240 const cricket::StreamParamsVec& streams) {
5241 std::vector<std::string> existing_channels;
5242
5243 // Find new and active data channels.
5244 for (const cricket::StreamParams& params : streams) {
5245 // The data channel label is either the mslabel or the SSRC if the mslabel
5246 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005247 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005248 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005249 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005250 auto data_channel_it = rtp_data_channels_.find(label);
5251 if (data_channel_it == rtp_data_channels_.end()) {
5252 // This is a new data channel.
5253 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5254 } else {
5255 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5256 }
5257 existing_channels.push_back(label);
5258 }
5259
5260 UpdateClosingRtpDataChannels(existing_channels, false);
5261}
5262
5263void PeerConnection::UpdateClosingRtpDataChannels(
5264 const std::vector<std::string>& active_channels,
5265 bool is_local_update) {
5266 auto it = rtp_data_channels_.begin();
5267 while (it != rtp_data_channels_.end()) {
5268 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005269 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005270 ++it;
5271 continue;
5272 }
5273
5274 if (is_local_update) {
5275 data_channel->SetSendSsrc(0);
5276 } else {
5277 data_channel->RemotePeerRequestClose();
5278 }
5279
5280 if (data_channel->state() == DataChannel::kClosed) {
5281 rtp_data_channels_.erase(it);
5282 it = rtp_data_channels_.begin();
5283 } else {
5284 ++it;
5285 }
5286 }
5287}
5288
5289void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5290 uint32_t remote_ssrc) {
5291 rtc::scoped_refptr<DataChannel> channel(
5292 InternalCreateDataChannel(label, nullptr));
5293 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005294 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005295 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005296 return;
5297 }
5298 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005299 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5300 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005301 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005302}
5303
5304rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5305 const std::string& label,
5306 const InternalDataChannelInit* config) {
5307 if (IsClosed()) {
5308 return nullptr;
5309 }
Steve Anton75737c02017-11-06 10:37:17 -08005310 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005311 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005312 << "InternalCreateDataChannel: Data is not supported in this call.";
5313 return nullptr;
5314 }
5315 InternalDataChannelInit new_config =
5316 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005317 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005318 if (new_config.id < 0) {
5319 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005320 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005321 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005322 RTC_LOG(LS_ERROR)
5323 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005324 return nullptr;
5325 }
5326 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005327 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005328 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005329 return nullptr;
5330 }
5331 }
5332
Steve Anton75737c02017-11-06 10:37:17 -08005333 rtc::scoped_refptr<DataChannel> channel(
5334 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005335 if (!channel) {
5336 sid_allocator_.ReleaseSid(new_config.id);
5337 return nullptr;
5338 }
5339
5340 if (channel->data_channel_type() == cricket::DCT_RTP) {
5341 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005342 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5343 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005344 return nullptr;
5345 }
5346 rtp_data_channels_[channel->label()] = channel;
5347 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005348 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005349 sctp_data_channels_.push_back(channel);
5350 channel->SignalClosed.connect(this,
5351 &PeerConnection::OnSctpDataChannelClosed);
5352 }
5353
Steve Anton2d8609c2018-01-23 16:38:46 -08005354 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005355 return channel;
5356}
5357
5358bool PeerConnection::HasDataChannels() const {
5359 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5360}
5361
5362void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005363 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005364 for (const auto& channel : sctp_data_channels_) {
5365 if (channel->id() < 0) {
5366 int sid;
5367 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005368 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5369 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005370 continue;
5371 }
5372 channel->SetSctpSid(sid);
5373 }
5374 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005375 // Since closing modifies the list of channels, we have to do the actual
5376 // closing outside the loop.
5377 for (const auto& channel : channels_to_close) {
5378 channel->CloseAbruptly();
5379 }
deadbeefab9b2d12015-10-14 11:33:11 -07005380}
5381
5382void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005383 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005384 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5385 ++it) {
5386 if (it->get() == channel) {
5387 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005388 // After the closing procedure is done, it's safe to use this ID for
5389 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005390 sid_allocator_.ReleaseSid(channel->id());
5391 }
deadbeefbd292462015-12-14 18:15:29 -08005392 // Since this method is triggered by a signal from the DataChannel,
5393 // we can't free it directly here; we need to free it asynchronously.
5394 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005395 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005396 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5397 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005398 return;
5399 }
5400 }
5401}
5402
deadbeefab9b2d12015-10-14 11:33:11 -07005403void PeerConnection::OnDataChannelDestroyed() {
5404 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5405 // DataChannel may callback to us and try to modify the list.
5406 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5407 temp_rtp_dcs.swap(rtp_data_channels_);
5408 for (const auto& kv : temp_rtp_dcs) {
5409 kv.second->OnTransportChannelDestroyed();
5410 }
5411
5412 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5413 temp_sctp_dcs.swap(sctp_data_channels_);
5414 for (const auto& channel : temp_sctp_dcs) {
5415 channel->OnTransportChannelDestroyed();
5416 }
5417}
5418
5419void PeerConnection::OnDataChannelOpenMessage(
5420 const std::string& label,
5421 const InternalDataChannelInit& config) {
5422 rtc::scoped_refptr<DataChannel> channel(
5423 InternalCreateDataChannel(label, &config));
5424 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005425 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005426 return;
5427 }
5428
deadbeefa601f5c2016-06-06 14:27:39 -07005429 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5430 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005431 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005432 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005433}
5434
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005435bool PeerConnection::HandleOpenMessage_s(
5436 const cricket::ReceiveDataParams& params,
5437 const rtc::CopyOnWriteBuffer& buffer) {
5438 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5439 // Received OPEN message; parse and signal that a new data channel should
5440 // be created.
5441 std::string label;
5442 InternalDataChannelInit config;
5443 config.id = params.ssrc;
5444 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5445 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5446 << params.ssrc;
5447 return true;
5448 }
5449 config.open_handshake_role = InternalDataChannelInit::kAcker;
5450 OnDataChannelOpenMessage(label, config);
5451 return true;
5452 }
5453 return false;
5454}
5455
Steve Anton4171afb2017-11-20 10:20:22 -08005456rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5457PeerConnection::GetAudioTransceiver() const {
5458 // This method only works with Plan B SDP, where there is a single
5459 // audio/video transceiver.
5460 RTC_DCHECK(!IsUnifiedPlan());
5461 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005462 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005463 return transceiver;
5464 }
5465 }
5466 RTC_NOTREACHED();
5467 return nullptr;
5468}
5469
5470rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5471PeerConnection::GetVideoTransceiver() const {
5472 // This method only works with Plan B SDP, where there is a single
5473 // audio/video transceiver.
5474 RTC_DCHECK(!IsUnifiedPlan());
5475 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005476 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005477 return transceiver;
5478 }
5479 }
5480 RTC_NOTREACHED();
5481 return nullptr;
5482}
5483
5484// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5485// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005486bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005487 switch (type) {
5488 case cricket::MEDIA_TYPE_AUDIO:
5489 return !GetAudioTransceiver()->internal()->senders().empty();
5490 case cricket::MEDIA_TYPE_VIDEO:
5491 return !GetVideoTransceiver()->internal()->senders().empty();
5492 case cricket::MEDIA_TYPE_DATA:
5493 return false;
5494 }
5495 RTC_NOTREACHED();
5496 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005497}
5498
Steve Anton4171afb2017-11-20 10:20:22 -08005499rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5500PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005501 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005502 for (auto sender : transceiver->internal()->senders()) {
5503 if (sender->track() == track) {
5504 return sender;
5505 }
5506 }
5507 }
5508 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005509}
5510
Steve Anton4171afb2017-11-20 10:20:22 -08005511rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5512PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005513 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005514 for (auto sender : transceiver->internal()->senders()) {
5515 if (sender->id() == sender_id) {
5516 return sender;
5517 }
5518 }
5519 }
5520 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005521}
5522
Steve Anton4171afb2017-11-20 10:20:22 -08005523rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5524PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005525 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005526 for (auto receiver : transceiver->internal()->receivers()) {
5527 if (receiver->id() == receiver_id) {
5528 return receiver;
5529 }
5530 }
5531 }
5532 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005533}
5534
Steve Anton4171afb2017-11-20 10:20:22 -08005535std::vector<PeerConnection::RtpSenderInfo>*
5536PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5537 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5538 media_type == cricket::MEDIA_TYPE_VIDEO);
5539 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5540 ? &remote_audio_sender_infos_
5541 : &remote_video_sender_infos_;
5542}
5543
5544std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005545 cricket::MediaType media_type) {
5546 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5547 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005548 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5549 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005550}
5551
Steve Anton4171afb2017-11-20 10:20:22 -08005552const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5553 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005554 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005555 const std::string sender_id) const {
5556 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005557 if (sender_info.stream_id == stream_id &&
5558 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005559 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005560 }
5561 }
5562 return nullptr;
5563}
5564
5565DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5566 for (const auto& channel : sctp_data_channels_) {
5567 if (channel->id() == sid) {
5568 return channel;
5569 }
5570 }
5571 return nullptr;
5572}
5573
Karl Wibergfb3be392019-03-22 14:13:22 +01005574PeerConnection::InitializePortAllocatorResult
5575PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005576 const cricket::ServerAddresses& stun_servers,
5577 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005578 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005579 RTC_DCHECK_RUN_ON(network_thread());
5580
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005581 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005582 // To handle both internal and externally created port allocator, we will
5583 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005584 int port_allocator_flags = port_allocator_->flags();
5585 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5586 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5587 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005588 // If the disable-IPv6 flag was specified, we'll not override it
5589 // by experiment.
5590 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005591 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005592 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5593 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005594 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005595 }
5596
zhihuangb09b3f92017-03-07 14:40:51 -08005597 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005598 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005599 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005600 }
5601
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005602 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005603 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005604 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005605 }
5606
honghaiz60347052016-05-31 18:29:12 -07005607 if (configuration.candidate_network_policy ==
5608 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005609 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005610 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005611 }
5612
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005613 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005614 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005615 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5616 }
5617
Karl Wibergfb3be392019-03-22 14:13:22 +01005618 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005619 // No step delay is used while allocating ports.
5620 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005621 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005622 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005623 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005624
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005625 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005626 for (auto& turn_server : turn_servers_copy) {
5627 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005628 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005629 // Call this last since it may create pooled allocator sessions using the
5630 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005631 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005632 stun_servers, std::move(turn_servers_copy),
5633 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5634 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005635 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005636
5637 InitializePortAllocatorResult res;
5638 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5639 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005640}
5641
deadbeef91dd5672016-05-18 16:55:30 -07005642bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005643 const cricket::ServerAddresses& stun_servers,
5644 const std::vector<cricket::RelayServerConfig>& turn_servers,
5645 IceTransportsType type,
5646 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005647 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005648 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005649 absl::optional<int> stun_candidate_keepalive_interval,
5650 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005651 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005652 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005653 // According to JSEP, after setLocalDescription, changing the candidate pool
5654 // size is not allowed, and changing the set of ICE servers will not result
5655 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005656 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005657 port_allocator_->FreezeCandidatePool();
5658 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005659 // Add the custom tls turn servers if they exist.
5660 auto turn_servers_copy = turn_servers;
5661 for (auto& turn_server : turn_servers_copy) {
5662 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5663 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005664 // Call this last since it may create pooled allocator sessions using the
5665 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005666 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005667 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5668 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005669}
5670
Steve Antonba818672017-11-06 10:21:57 -08005671cricket::ChannelManager* PeerConnection::channel_manager() const {
5672 return factory_->channel_manager();
5673}
5674
Elad Alon99c3fe52017-10-13 16:29:40 +02005675bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005676 std::unique_ptr<RtcEventLogOutput> output,
5677 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005678 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005679 if (!event_log_) {
5680 return false;
5681 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005682 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005683}
5684
5685void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005686 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005687 if (event_log_) {
5688 event_log_->StopLogging();
5689 }
ivoc14d5dbe2016-07-04 07:06:55 -07005690}
nisseeaabdf62017-05-05 02:23:02 -07005691
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005692cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005693 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005694 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005695 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005696 if (channel && channel->content_name() == content_name) {
5697 return channel;
5698 }
Steve Anton75737c02017-11-06 10:37:17 -08005699 }
5700 if (rtp_data_channel() &&
5701 rtp_data_channel()->content_name() == content_name) {
5702 return rtp_data_channel();
5703 }
5704 return nullptr;
5705}
5706
5707bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005708 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005709 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005710 RTC_LOG(LS_INFO)
5711 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005712 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005713 return false;
5714 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005715 if (!sctp_transport_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005716 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005717 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005718 return false;
5719 }
5720
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005721 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005722 if (sctp_mid_ && sctp_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005723 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5724 } else if (is_caller_) {
5725 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5726 }
Zhi Huange830e682018-03-30 10:48:35 -07005727 if (dtls_role) {
5728 *role = *dtls_role;
5729 return true;
5730 }
5731 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005732}
5733
5734bool PeerConnection::GetSslRole(const std::string& content_name,
5735 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005736 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005737 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005738 RTC_LOG(LS_INFO)
5739 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005740 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005741 return false;
5742 }
5743
Zhi Huange830e682018-03-30 10:48:35 -07005744 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5745 if (dtls_role) {
5746 *role = *dtls_role;
5747 return true;
5748 }
5749 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005750}
5751
Steve Antonf8470812017-12-04 10:46:21 -08005752void PeerConnection::SetSessionError(SessionError error,
5753 const std::string& error_desc) {
5754 RTC_DCHECK_RUN_ON(signaling_thread());
5755 if (error != session_error_) {
5756 session_error_ = error;
5757 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005758 }
5759}
5760
Zhi Huange830e682018-03-30 10:48:35 -07005761RTCError PeerConnection::UpdateSessionState(
5762 SdpType type,
5763 cricket::ContentSource source,
5764 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005765 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005766
5767 // If there's already a pending error then no state transition should happen.
5768 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005769 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005770
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005771 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005772 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005773 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005774 }
5775
5776 // Update the signaling state according to the specified state machine (see
5777 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005778 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005779 ChangeSignalingState(source == cricket::CS_LOCAL
5780 ? PeerConnectionInterface::kHaveLocalOffer
5781 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005782 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005783 ChangeSignalingState(source == cricket::CS_LOCAL
5784 ? PeerConnectionInterface::kHaveLocalPrAnswer
5785 : PeerConnectionInterface::kHaveRemotePrAnswer);
5786 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005787 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005788 ChangeSignalingState(PeerConnectionInterface::kStable);
5789 }
5790
5791 // Update internal objects according to the session description's media
5792 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005793 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005794 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005795 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005796 }
5797
Steve Anton8a006912017-12-04 15:25:56 -08005798 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005799}
5800
Steve Anton8a006912017-12-04 15:25:56 -08005801RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005802 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005803 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005804 const SessionDescriptionInterface* sdesc =
5805 (source == cricket::CS_LOCAL ? local_description()
5806 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005807 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005808
5809 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005810 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005811 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005812 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005813 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005814 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005815 continue;
5816 }
5817 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005818 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005819 if (!content_desc) {
5820 continue;
5821 }
5822 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005823 bool success = (source == cricket::CS_LOCAL)
5824 ? channel->SetLocalContent(content_desc, type, &error)
5825 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005826 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005827 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005828 }
5829 }
5830
5831 // If using the RtpDataChannel, push down the new SDP section for it too.
5832 if (rtp_data_channel_) {
5833 const ContentInfo* data_content =
5834 cricket::GetFirstDataContent(sdesc->description());
5835 if (data_content && !data_content->rejected) {
5836 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005837 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005838 if (data_desc) {
5839 std::string error;
5840 bool success =
5841 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005842 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005843 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005844 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005845 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005846 }
Steve Anton75737c02017-11-06 10:37:17 -08005847 }
5848 }
5849 }
Steve Antoned10bd92017-12-05 10:52:59 -08005850
Steve Anton75737c02017-11-06 10:37:17 -08005851 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5852 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005853 if (sctp_transport_ && local_description() && remote_description()) {
5854 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5855 local_description()->description());
5856 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5857 remote_description()->description());
5858 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005859 int max_message_size;
5860 // A remote max message size of zero means "any size supported".
5861 // We configure the connection with our own max message size.
5862 if (remote_sctp_description->max_message_size() == 0) {
5863 max_message_size = local_sctp_description->max_message_size();
5864 } else {
5865 max_message_size =
5866 std::min(local_sctp_description->max_message_size(),
5867 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005868 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005869 sctp_transport_->Start(local_sctp_description->port(),
5870 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005871 }
Steve Anton75737c02017-11-06 10:37:17 -08005872 }
Steve Antoned10bd92017-12-05 10:52:59 -08005873
Steve Anton8a006912017-12-04 15:25:56 -08005874 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005875}
5876
Steve Anton8a006912017-12-04 15:25:56 -08005877RTCError PeerConnection::PushdownTransportDescription(
5878 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005879 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005880 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005881
Zhi Huange830e682018-03-30 10:48:35 -07005882 if (source == cricket::CS_LOCAL) {
5883 const SessionDescriptionInterface* sdesc = local_description();
5884 RTC_DCHECK(sdesc);
5885 return transport_controller_->SetLocalDescription(type,
5886 sdesc->description());
5887 } else {
5888 const SessionDescriptionInterface* sdesc = remote_description();
5889 RTC_DCHECK(sdesc);
5890 return transport_controller_->SetRemoteDescription(type,
5891 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005892 }
Steve Anton75737c02017-11-06 10:37:17 -08005893}
5894
5895bool PeerConnection::GetTransportDescription(
5896 const SessionDescription* description,
5897 const std::string& content_name,
5898 cricket::TransportDescription* tdesc) {
5899 if (!description || !tdesc) {
5900 return false;
5901 }
5902 const TransportInfo* transport_info =
5903 description->GetTransportInfoByName(content_name);
5904 if (!transport_info) {
5905 return false;
5906 }
5907 *tdesc = transport_info->description;
5908 return true;
5909}
5910
Steve Anton75737c02017-11-06 10:37:17 -08005911cricket::IceConfig PeerConnection::ParseIceConfig(
5912 const PeerConnectionInterface::RTCConfiguration& config) const {
5913 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005914 switch (config.continual_gathering_policy) {
5915 case PeerConnectionInterface::GATHER_ONCE:
5916 gathering_policy = cricket::GATHER_ONCE;
5917 break;
5918 case PeerConnectionInterface::GATHER_CONTINUALLY:
5919 gathering_policy = cricket::GATHER_CONTINUALLY;
5920 break;
5921 default:
5922 RTC_NOTREACHED();
5923 gathering_policy = cricket::GATHER_ONCE;
5924 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005925
Steve Anton75737c02017-11-06 10:37:17 -08005926 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005927 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5928 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005929 ice_config.prioritize_most_likely_candidate_pairs =
5930 config.prioritize_most_likely_ice_candidate_pairs;
5931 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005932 RTCConfigurationToIceConfigOptionalInt(
5933 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005934 ice_config.continual_gathering_policy = gathering_policy;
5935 ice_config.presume_writable_when_fully_relayed =
5936 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005937 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5938 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005939 ice_config.ice_check_interval_strong_connectivity =
5940 config.ice_check_interval_strong_connectivity;
5941 ice_config.ice_check_interval_weak_connectivity =
5942 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005943 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005944 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5945 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005946 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005947 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005948 ice_config.regather_all_networks_interval_range =
5949 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005950 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005951 return ice_config;
5952}
5953
Steve Anton75737c02017-11-06 10:37:17 -08005954bool PeerConnection::SendData(const cricket::SendDataParams& params,
5955 const rtc::CopyOnWriteBuffer& payload,
5956 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005957 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005958 if (data_channel_transport_ && data_channel_transport_negotiated_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005959 SendDataParams send_params;
5960 send_params.type = ToWebrtcDataMessageType(params.type);
5961 send_params.ordered = params.ordered;
5962 if (params.max_rtx_count >= 0) {
5963 send_params.max_rtx_count = params.max_rtx_count;
5964 } else if (params.max_rtx_ms >= 0) {
5965 send_params.max_rtx_ms = params.max_rtx_ms;
5966 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005967 return data_channel_transport_->SendData(params.sid, send_params, payload)
5968 .ok();
5969 } else if (sctp_transport_ && sctp_negotiated_) {
5970 return network_thread()->Invoke<bool>(
5971 RTC_FROM_HERE, Bind(&cricket::SctpTransportInternal::SendData,
5972 cricket_sctp_transport(), params, payload, result));
5973 } else if (rtp_data_channel_) {
5974 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005975 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005976 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
5977 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005978}
5979
5980bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005981 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005982 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005983 // Don't log an error here, because DataChannels are expected to call
5984 // ConnectDataChannel in this state. It's the only way to initially tell
5985 // whether or not the underlying transport is ready.
5986 return false;
5987 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005988 if (data_channel_transport_) {
5989 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
5990 &DataChannel::OnChannelReady);
5991 SignalDataChannelTransportReceivedData_s.connect(
5992 webrtc_data_channel, &DataChannel::OnDataReceived);
5993 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005994 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005995 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005996 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005997 }
5998 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005999 rtp_data_channel_->SignalReadyToSendData.connect(
6000 webrtc_data_channel, &DataChannel::OnChannelReady);
6001 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6002 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006003 }
6004 if (sctp_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006005 SignalSctpReadyToSendData.connect(webrtc_data_channel,
6006 &DataChannel::OnChannelReady);
6007 SignalSctpDataReceived.connect(webrtc_data_channel,
6008 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006009 SignalSctpClosingProcedureStartedRemotely.connect(
6010 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
6011 SignalSctpClosingProcedureComplete.connect(
6012 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08006013 }
6014 return true;
6015}
6016
6017void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006018 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006019 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006020 RTC_LOG(LS_ERROR)
6021 << "DisconnectDataChannel called when rtp_data_channel_ and "
6022 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006023 return;
6024 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006025 if (data_channel_transport_) {
6026 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6027 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6028 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6029 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6030 }
6031 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006032 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6033 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006034 }
6035 if (sctp_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006036 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
6037 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006038 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
6039 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006040 }
6041}
6042
6043void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006044 if (data_channel_transport_) {
6045 data_channel_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006046 }
Steve Anton75737c02017-11-06 10:37:17 -08006047 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006048 RTC_LOG(LS_ERROR)
6049 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006050 return;
6051 }
6052 network_thread()->Invoke<void>(
6053 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006054 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006055}
6056
6057void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006058 if (data_channel_transport_) {
6059 data_channel_transport_->CloseChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006060 }
Steve Anton75737c02017-11-06 10:37:17 -08006061 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006062 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006063 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006064 return;
6065 }
6066 network_thread()->Invoke<void>(
6067 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006068 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006069}
6070
6071bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006072 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006073 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006074 (data_channel_transport_ && data_channel_transport_ready_to_send_ &&
6075 data_channel_transport_negotiated_) ||
6076 (sctp_ready_to_send_data_ && sctp_negotiated_);
Steve Anton75737c02017-11-06 10:37:17 -08006077}
6078
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006079void PeerConnection::OnDataReceived(int channel_id,
6080 DataMessageType type,
6081 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006082 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006083 cricket::ReceiveDataParams params;
6084 params.sid = channel_id;
6085 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006086 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006087 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6088 RTC_DCHECK_RUN_ON(signaling_thread());
6089 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006090 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006091 }
6092 });
6093}
6094
6095void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006096 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006097 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006098 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6099 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006100 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006101 });
6102}
6103
6104void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006105 RTC_DCHECK_RUN_ON(network_thread());
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, channel_id] {
6108 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006109 SignalDataChannelTransportChannelClosed_s(channel_id);
6110 });
6111}
6112
6113void PeerConnection::OnReadyToSend() {
6114 RTC_DCHECK_RUN_ON(network_thread());
6115 data_channel_transport_invoker_->AsyncInvoke<void>(
6116 RTC_FROM_HERE, signaling_thread(), [this] {
6117 RTC_DCHECK_RUN_ON(signaling_thread());
6118 data_channel_transport_ready_to_send_ = true;
6119 if (data_channel_transport_negotiated_) {
6120 SignalDataChannelTransportWritable_s(
6121 data_channel_transport_ready_to_send_);
6122 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006123 });
6124}
6125
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006126absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006127 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006128 if (sctp_mid_ && transport_controller_) {
6129 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6130 if (dtls_transport) {
6131 return dtls_transport->transport_name();
6132 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006133 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006134 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006135 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006136}
6137
Qingsi Wang72a43a12018-02-20 16:03:18 -08006138cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6139 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006140 network_thread()->Invoke<void>(
6141 RTC_FROM_HERE,
6142 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6143 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006144 return candidate_states_list;
6145}
6146
Steve Anton5dfde182018-02-06 10:34:40 -08006147std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6148 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006149 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006150 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006151 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006152 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006153 if (channel) {
6154 transport_names_by_mid[channel->content_name()] =
6155 channel->transport_name();
6156 }
Steve Anton75737c02017-11-06 10:37:17 -08006157 }
Steve Anton5dfde182018-02-06 10:34:40 -08006158 if (rtp_data_channel_) {
6159 transport_names_by_mid[rtp_data_channel_->content_name()] =
6160 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006161 }
6162 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006163 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006164 RTC_DCHECK(transport_name);
6165 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006166 }
Steve Anton5dfde182018-02-06 10:34:40 -08006167 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006168}
6169
Steve Anton5dfde182018-02-06 10:34:40 -08006170std::map<std::string, cricket::TransportStats>
6171PeerConnection::GetTransportStatsByNames(
6172 const std::set<std::string>& transport_names) {
6173 if (!network_thread()->IsCurrent()) {
6174 return network_thread()
6175 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6176 RTC_FROM_HERE,
6177 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006178 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006179 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006180 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6181 for (const std::string& transport_name : transport_names) {
6182 cricket::TransportStats transport_stats;
6183 bool success =
6184 transport_controller_->GetStats(transport_name, &transport_stats);
6185 if (success) {
6186 transport_stats_by_name[transport_name] = std::move(transport_stats);
6187 } else {
6188 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6189 << transport_name;
6190 }
6191 }
6192 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006193}
6194
6195bool PeerConnection::GetLocalCertificate(
6196 const std::string& transport_name,
6197 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006198 if (!certificate) {
6199 return false;
6200 }
6201 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6202 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006203}
6204
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006205std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006206 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006207 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006208}
6209
6210cricket::DataChannelType PeerConnection::data_channel_type() const {
6211 return data_channel_type_;
6212}
6213
6214bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006215 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006216 return pending_ice_restarts_.find(content_name) !=
6217 pending_ice_restarts_.end();
6218}
6219
Steve Anton75737c02017-11-06 10:37:17 -08006220bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6221 return transport_controller_->NeedsIceRestart(content_name);
6222}
6223
6224void PeerConnection::OnCertificateReady(
6225 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6226 transport_controller_->SetLocalCertificate(certificate);
6227}
6228
6229void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006230 SetSessionError(SessionError::kTransport,
6231 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006232}
6233
Alex Loiko9289eda2018-11-23 16:18:59 +00006234void PeerConnection::OnTransportControllerConnectionState(
6235 cricket::IceConnectionState state) {
6236 switch (state) {
6237 case cricket::kIceConnectionConnecting:
6238 // If the current state is Connected or Completed, then there were
6239 // writable channels but now there are not, so the next state must
6240 // be Disconnected.
6241 // kIceConnectionConnecting is currently used as the default,
6242 // un-connected state by the TransportController, so its only use is
6243 // detecting disconnections.
6244 if (ice_connection_state_ ==
6245 PeerConnectionInterface::kIceConnectionConnected ||
6246 ice_connection_state_ ==
6247 PeerConnectionInterface::kIceConnectionCompleted) {
6248 SetIceConnectionState(
6249 PeerConnectionInterface::kIceConnectionDisconnected);
6250 }
6251 break;
6252 case cricket::kIceConnectionFailed:
6253 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6254 break;
6255 case cricket::kIceConnectionConnected:
6256 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6257 "all transports are writable.";
6258 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6259 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6260 break;
6261 case cricket::kIceConnectionCompleted:
6262 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6263 "all transports are complete.";
6264 if (ice_connection_state_ !=
6265 PeerConnectionInterface::kIceConnectionConnected) {
6266 // If jumping directly from "checking" to "connected",
6267 // signal "connected" first.
6268 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6269 }
6270 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6271 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6272 ReportTransportStats();
6273 break;
6274 default:
6275 RTC_NOTREACHED();
6276 }
6277}
6278
Steve Anton75737c02017-11-06 10:37:17 -08006279void PeerConnection::OnTransportControllerCandidatesGathered(
6280 const std::string& transport_name,
6281 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006282 int sdp_mline_index;
6283 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006284 RTC_LOG(LS_ERROR)
6285 << "OnTransportControllerCandidatesGathered: content name "
6286 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006287 return;
6288 }
6289
6290 for (cricket::Candidates::const_iterator citer = candidates.begin();
6291 citer != candidates.end(); ++citer) {
6292 // Use transport_name as the candidate media id.
6293 std::unique_ptr<JsepIceCandidate> candidate(
6294 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6295 if (local_description()) {
6296 mutable_local_description()->AddCandidate(candidate.get());
6297 }
6298 OnIceCandidate(std::move(candidate));
6299 }
6300}
6301
Eldar Relloda13ea22019-06-01 12:23:43 +03006302void PeerConnection::OnTransportControllerCandidateError(
6303 const cricket::IceCandidateErrorEvent& event) {
6304 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6305 event.error_text);
6306}
6307
Steve Anton75737c02017-11-06 10:37:17 -08006308void PeerConnection::OnTransportControllerCandidatesRemoved(
6309 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006310 // Sanity check.
6311 for (const cricket::Candidate& candidate : candidates) {
6312 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006313 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006314 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006315 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006316 return;
6317 }
6318 }
6319
6320 if (local_description()) {
6321 mutable_local_description()->RemoveCandidates(candidates);
6322 }
6323 OnIceCandidatesRemoved(candidates);
6324}
6325
Alex Drake00c7ecf2019-08-06 10:54:47 -07006326void PeerConnection::OnTransportControllerCandidateChanged(
6327 const cricket::CandidatePairChangeEvent& event) {
6328 OnSelectedCandidatePairChanged(event);
6329}
6330
Steve Anton75737c02017-11-06 10:37:17 -08006331void PeerConnection::OnTransportControllerDtlsHandshakeError(
6332 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006333 RTC_HISTOGRAM_ENUMERATION(
6334 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6335 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006336}
6337
Steve Antoned10bd92017-12-05 10:52:59 -08006338void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006339 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006340 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006341 if (channel && !channel->enabled()) {
6342 channel->Enable(true);
6343 }
Steve Anton75737c02017-11-06 10:37:17 -08006344 }
6345
Steve Anton4171afb2017-11-20 10:20:22 -08006346 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006347 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006348 }
Steve Anton75737c02017-11-06 10:37:17 -08006349}
6350
6351// Returns the media index for a local ice candidate given the content name.
6352bool PeerConnection::GetLocalCandidateMediaIndex(
6353 const std::string& content_name,
6354 int* sdp_mline_index) {
6355 if (!local_description() || !sdp_mline_index) {
6356 return false;
6357 }
6358
6359 bool content_found = false;
6360 const ContentInfos& contents = local_description()->description()->contents();
6361 for (size_t index = 0; index < contents.size(); ++index) {
6362 if (contents[index].name == content_name) {
6363 *sdp_mline_index = static_cast<int>(index);
6364 content_found = true;
6365 break;
6366 }
6367 }
6368 return content_found;
6369}
6370
6371bool PeerConnection::UseCandidatesInSessionDescription(
6372 const SessionDescriptionInterface* remote_desc) {
6373 if (!remote_desc) {
6374 return true;
6375 }
6376 bool ret = true;
6377
6378 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6379 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6380 for (size_t n = 0; n < candidates->count(); ++n) {
6381 const IceCandidateInterface* candidate = candidates->at(n);
6382 bool valid = false;
6383 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6384 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006385 RTC_LOG(LS_INFO)
6386 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006387 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006388 }
6389 continue;
6390 }
6391 ret = UseCandidate(candidate);
6392 if (!ret) {
6393 break;
6394 }
6395 }
6396 }
6397 return ret;
6398}
6399
6400bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006401 RTCErrorOr<const cricket::ContentInfo*> result =
6402 FindContentInfo(remote_description(), candidate);
6403 if (!result.ok()) {
6404 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6405 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006406 return false;
6407 }
Steve Anton75737c02017-11-06 10:37:17 -08006408 std::vector<cricket::Candidate> candidates;
6409 candidates.push_back(candidate->candidate());
6410 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006411 RTCError error = transport_controller_->AddRemoteCandidates(
6412 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006413 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006414 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006415 // Candidates successfully submitted for checking.
6416 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6417 ice_connection_state_ ==
6418 PeerConnectionInterface::kIceConnectionDisconnected) {
6419 // If state is New, then the session has just gotten its first remote ICE
6420 // candidates, so go to Checking.
6421 // If state is Disconnected, the session is re-using old candidates or
6422 // receiving additional ones, so go to Checking.
6423 // If state is Connected, stay Connected.
6424 // TODO(bemasc): If state is Connected, and the new candidates are for a
6425 // newly added transport, then the state actually _should_ move to
6426 // checking. Add a way to distinguish that case.
6427 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6428 }
6429 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006430 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006431 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006432 }
6433 return true;
6434}
6435
Guido Urdaneta41633172019-05-23 20:12:29 +02006436RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6437 const SessionDescriptionInterface* description,
6438 const IceCandidateInterface* candidate) {
6439 if (candidate->sdp_mline_index() >= 0) {
6440 size_t mediacontent_index =
6441 static_cast<size_t>(candidate->sdp_mline_index());
6442 size_t content_size = description->description()->contents().size();
6443 if (mediacontent_index < content_size) {
6444 return &description->description()->contents()[mediacontent_index];
6445 } else {
6446 return RTCError(RTCErrorType::INVALID_RANGE,
6447 "Media line index (" +
6448 rtc::ToString(candidate->sdp_mline_index()) +
6449 ") out of range (number of mlines: " +
6450 rtc::ToString(content_size) + ").");
6451 }
6452 } else if (!candidate->sdp_mid().empty()) {
6453 auto& contents = description->description()->contents();
6454 auto it = absl::c_find_if(
6455 contents, [candidate](const cricket::ContentInfo& content_info) {
6456 return content_info.mid() == candidate->sdp_mid();
6457 });
6458 if (it == contents.end()) {
6459 return RTCError(
6460 RTCErrorType::INVALID_PARAMETER,
6461 "Mid " + candidate->sdp_mid() +
6462 " specified but no media section with that mid found.");
6463 } else {
6464 return &*it;
6465 }
6466 }
6467
6468 return RTCError(RTCErrorType::INVALID_PARAMETER,
6469 "Neither sdp_mline_index nor sdp_mid specified.");
6470}
6471
Steve Anton75737c02017-11-06 10:37:17 -08006472void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006473 // Destroy video channel first since it may have a pointer to the
6474 // voice channel.
6475 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006476 if (!video_info || video_info->rejected) {
6477 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006478 }
6479
Steve Anton6fec8802017-12-04 10:37:29 -08006480 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6481 if (!audio_info || audio_info->rejected) {
6482 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006483 }
6484
6485 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6486 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006487 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006488 }
6489}
6490
Steve Antondcc3c022017-12-22 16:02:54 -08006491RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6492 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006493 const cricket::ContentGroup* bundle_group = nullptr;
6494 if (configuration_.bundle_policy ==
6495 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006496 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006497 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6499 "max-bundle configured but session description "
6500 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006501 }
6502 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006503 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006504}
6505
6506RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006507 // Creating the media channels. Transports should already have been created
6508 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006509 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006510 if (voice && !voice->rejected &&
6511 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006512 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006513 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006514 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6515 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006516 }
6517 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6518 }
6519
Steve Antondcc3c022017-12-22 16:02:54 -08006520 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006521 if (video && !video->rejected &&
6522 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006523 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006524 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006525 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6526 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006527 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006528 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006529 }
6530
Steve Antondcc3c022017-12-22 16:02:54 -08006531 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006532 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006533 !rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006534 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006535 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6536 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006537 }
6538 }
6539
Steve Anton8a006912017-12-04 15:25:56 -08006540 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006541}
6542
Steve Anton4171afb2017-11-20 10:20:22 -08006543// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006544cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006545 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006546 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006547 MediaTransportConfig media_transport_config =
6548 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006549
Steve Anton75737c02017-11-06 10:37:17 -08006550 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006551 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006552 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6553 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006554 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006555 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006556 }
Steve Anton75737c02017-11-06 10:37:17 -08006557 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6558 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006559 voice_channel->SignalSentPacket.connect(this,
6560 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006561 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006562
Steve Antoneda6ccd2017-12-04 10:21:55 -08006563 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006564}
6565
Steve Anton4171afb2017-11-20 10:20:22 -08006566// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006567cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006568 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006569 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006570 MediaTransportConfig media_transport_config =
6571 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006572
Steve Anton75737c02017-11-06 10:37:17 -08006573 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006574 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006575 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6576 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006577 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006578 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006579 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006580 }
Steve Anton75737c02017-11-06 10:37:17 -08006581 video_channel->SignalDtlsSrtpSetupFailure.connect(
6582 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006583 video_channel->SignalSentPacket.connect(this,
6584 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006585 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006586
Steve Antoneda6ccd2017-12-04 10:21:55 -08006587 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006588}
6589
Zhi Huange830e682018-03-30 10:48:35 -07006590bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006591 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006592 case cricket::DCT_SCTP:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006593 // Only using SCTP transport. No more setup required. Since SCTP is
6594 // the only option, it doesn't need to wait for negotiation.
6595 sctp_negotiated_ = true;
6596 if (!CreateSctpDataChannel(mid)) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006597 return false;
6598 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006599 break;
6600 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
6601 // Setup a data channel transport with SCTP as a fallback. Which one is
6602 // used will be determined later in negotiation.
6603 if (!CreateSctpDataChannel(mid)) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006604 return false;
6605 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006606 if (!SetupDataChannelTransport(mid)) {
6607 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006608 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006609 break;
6610 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6611 case cricket::DCT_MEDIA_TRANSPORT:
6612 // Using data channel transport without a fallback. It is the only
6613 // option. Data channel transport doesn't need to be negotiated.
6614 data_channel_transport_negotiated_ = true;
6615 if (!SetupDataChannelTransport(mid)) {
6616 return false;
6617 }
6618 break;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006619 case cricket::DCT_RTP:
6620 default:
6621 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6622 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6623 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006624 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006625 if (!rtp_data_channel_) {
6626 return false;
6627 }
6628 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6629 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6630 rtp_data_channel_->SignalSentPacket.connect(
6631 this, &PeerConnection::OnSentPacket_w);
6632 rtp_data_channel_->SetRtpTransport(rtp_transport);
6633 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006634 }
6635
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006636 // All non-RTP data channels must initialize |sctp_data_channels_|.
6637 for (const auto& channel : sctp_data_channels_) {
6638 channel->OnTransportChannelCreated();
6639 }
6640 return true;
6641}
6642
6643bool PeerConnection::CreateSctpDataChannel(const std::string& mid) {
6644 if (!sctp_factory_) {
6645 RTC_LOG(LS_ERROR)
6646 << "Trying to create SCTP transport, but didn't compile with "
6647 "SCTP support (HAVE_SCTP)";
6648 return false;
6649 }
6650 if (!network_thread()->Invoke<bool>(
6651 RTC_FROM_HERE,
6652 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6653 return false;
6654 }
6655 return true;
6656}
6657
6658bool PeerConnection::SetupDataChannelTransport(const std::string& mid) {
6659 if (!network_thread()->Invoke<bool>(
6660 RTC_FROM_HERE,
6661 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this, mid))) {
6662 return false;
6663 }
Steve Anton75737c02017-11-06 10:37:17 -08006664 return true;
6665}
6666
6667Call::Stats PeerConnection::GetCallStats() {
6668 if (!worker_thread()->IsCurrent()) {
6669 return worker_thread()->Invoke<Call::Stats>(
6670 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6671 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006672 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006673 if (call_) {
6674 return call_->GetStats();
6675 } else {
6676 return Call::Stats();
6677 }
6678}
6679
Zhi Huange830e682018-03-30 10:48:35 -07006680bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006681 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006682 RTC_DCHECK(sctp_factory_);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006683 RTC_LOG(LS_INFO) << "Creating SCTP transport for mid=" << mid;
6684
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006685 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6686 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006687 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006688 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006689 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006690 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6691 sctp_factory_->CreateSctpTransport(dtls_transport);
6692 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006693 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006694 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006695 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006696 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006697 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006698 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6699 // another thread. Would be nice if there was a helper class similar to
6700 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6701 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006702 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006703 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006704 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006705 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006706 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006707 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6708 std::move(cricket_sctp_transport));
6709 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006710 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006711}
6712
6713void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006714 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006715 RTC_LOG(LS_INFO) << "Destroying SCTP transport for mid=" << *sctp_mid_;
6716
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006717 sctp_transport_->Clear();
6718 sctp_transport_ = nullptr;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006719 // |sctp_mid_| may still be active through a data channel transport. If not,
6720 // unset it.
6721 if (!data_channel_transport_) {
6722 sctp_mid_.reset();
6723 }
Steve Anton75737c02017-11-06 10:37:17 -08006724 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006725}
6726
6727void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006728 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006729 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6730 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006731 // Note: Cannot use rtc::Bind here because it will grab a reference to
6732 // PeerConnection and potentially cause PeerConnection to live longer than
6733 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6734 // be destroyed before PeerConnection is destroyed, and at that point all
6735 // pending tasks will be cleared.
6736 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6737 OnSctpTransportReadyToSendData_s(true);
6738 });
6739}
6740
6741void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006742 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006743 sctp_ready_to_send_data_ = ready;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006744 if (sctp_negotiated_) {
6745 SignalSctpReadyToSendData(ready);
6746 }
Steve Anton75737c02017-11-06 10:37:17 -08006747}
6748
6749void PeerConnection::OnSctpTransportDataReceived_n(
6750 const cricket::ReceiveDataParams& params,
6751 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006752 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006753 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6754 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006755 // Note: Cannot use rtc::Bind here because it will grab a reference to
6756 // PeerConnection and potentially cause PeerConnection to live longer than
6757 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6758 // be destroyed before PeerConnection is destroyed, and at that point all
6759 // pending tasks will be cleared.
6760 sctp_invoker_->AsyncInvoke<void>(
6761 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6762 OnSctpTransportDataReceived_s(params, payload);
6763 });
6764}
6765
6766void PeerConnection::OnSctpTransportDataReceived_s(
6767 const cricket::ReceiveDataParams& params,
6768 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006769 RTC_DCHECK_RUN_ON(signaling_thread());
6770 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006771 SignalSctpDataReceived(params, payload);
6772 }
6773}
6774
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006775void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006776 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006777 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6778 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006779 sctp_invoker_->AsyncInvoke<void>(
6780 RTC_FROM_HERE, signaling_thread(),
6781 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006782 &SignalSctpClosingProcedureStartedRemotely, sid));
6783}
6784
6785void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006786 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006787 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6788 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006789 sctp_invoker_->AsyncInvoke<void>(
6790 RTC_FROM_HERE, signaling_thread(),
6791 rtc::Bind(&sigslot::signal1<int>::operator(),
6792 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006793}
6794
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006795bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
6796 data_channel_transport_ = transport_controller_->GetDataChannelTransport(mid);
6797 if (!data_channel_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006798 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006799 << "Data channel transport is not available for data channels, mid="
6800 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006801 return false;
6802 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006803 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006804
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006805 data_channel_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6806 data_channel_transport_->SetDataSink(this);
6807 sctp_mid_ = mid;
6808 // TODO(mellem): Handling data channel state through media transport is
6809 // deprecated. Delete these lines when downstream implementations call
6810 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006811 transport_controller_->SignalMediaTransportStateChanged.connect(
6812 this, &PeerConnection::OnMediaTransportStateChanged_n);
6813 // Check the initial state right away, in case transport is already writable.
6814 OnMediaTransportStateChanged_n();
6815 return true;
6816}
6817
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006818void PeerConnection::TeardownDataChannelTransport_n() {
6819 if (!data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006820 return;
6821 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006822 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6823 << *sctp_mid_;
6824
6825 // TODO(mellem): Delete this line when downstream implementations call
6826 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006827 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006828 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6829 // it.
6830 if (!sctp_transport_) {
6831 sctp_mid_.reset();
6832 }
6833 data_channel_transport_->SetDataSink(nullptr);
6834 data_channel_transport_invoker_ = nullptr;
6835 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006836}
6837
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006838// TODO(mellem): Handling of data channel state through the media transport
6839// callback is deprecated. This function should be deleted once downstream
6840// implementations call DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006841void PeerConnection::OnMediaTransportStateChanged_n() {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006842 if (!sctp_mid_ || transport_controller_->GetMediaTransportState(*sctp_mid_) !=
6843 MediaTransportState::kWritable) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006844 return;
6845 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006846 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006847 RTC_FROM_HERE, signaling_thread(), [this] {
6848 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006849 data_channel_transport_ready_to_send_ = true;
6850 if (data_channel_transport_negotiated_) {
6851 SignalDataChannelTransportWritable_s(
6852 data_channel_transport_ready_to_send_);
6853 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006854 });
6855}
6856
Steve Anton75737c02017-11-06 10:37:17 -08006857// Returns false if bundle is enabled and rtcp_mux is disabled.
6858bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6859 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6860 if (!bundle_enabled)
6861 return true;
6862
6863 const cricket::ContentGroup* bundle_group =
6864 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6865 RTC_DCHECK(bundle_group != NULL);
6866
6867 const cricket::ContentInfos& contents = desc->contents();
6868 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6869 citer != contents.end(); ++citer) {
6870 const cricket::ContentInfo* content = (&*citer);
6871 RTC_DCHECK(content != NULL);
6872 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006873 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006874 if (!HasRtcpMuxEnabled(content))
6875 return false;
6876 }
6877 }
6878 // RTCP-MUX is enabled in all the contents.
6879 return true;
6880}
6881
6882bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006883 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006884}
6885
Steve Anton06817cd2018-12-18 15:55:30 -08006886static RTCError ValidateMids(const cricket::SessionDescription& description) {
6887 std::set<std::string> mids;
6888 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006889 if (content.name.empty()) {
6890 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6891 "A media section is missing a MID attribute.");
6892 }
Steve Anton06817cd2018-12-18 15:55:30 -08006893 if (!mids.insert(content.name).second) {
6894 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6895 "Duplicate a=mid value '" + content.name + "'.");
6896 }
6897 }
6898 return RTCError::OK();
6899}
6900
Steve Anton8a006912017-12-04 15:25:56 -08006901RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006902 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006903 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006904 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006905 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006906 }
6907
6908 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006909 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006910 }
6911
Steve Anton3828c062017-12-06 10:34:51 -08006912 SdpType type = sdesc->GetType();
6913 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6914 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006915 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006916 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006917 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006918 }
6919
Steve Anton06817cd2018-12-18 15:55:30 -08006920 RTCError error = ValidateMids(*sdesc->description());
6921 if (!error.ok()) {
6922 return error;
6923 }
6924
Steve Anton75737c02017-11-06 10:37:17 -08006925 // Verify crypto settings.
6926 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006927 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6928 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006929 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006930 if (!crypto_error.ok()) {
6931 return crypto_error;
6932 }
Steve Anton75737c02017-11-06 10:37:17 -08006933 }
6934
6935 // Verify ice-ufrag and ice-pwd.
6936 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006937 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6938 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006939 }
6940
6941 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006942 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6943 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006944 }
6945
6946 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6947 // m-lines that do not rtcp-mux enabled.
6948
6949 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006950 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006951 // With an answer we want to compare the new answer session description with
6952 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006953 const cricket::SessionDescription* offer_desc =
6954 (source == cricket::CS_LOCAL) ? remote_description()->description()
6955 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006956 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6957 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6958 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006959 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6960 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006961 }
6962 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006963 // The re-offers should respect the order of m= sections in current
6964 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006965 // With a re-offer, either the current local or current remote descriptions
6966 // could be the most up to date, so we would like to check against both of
6967 // them if they exist. It could be the case that one of them has a 0 port
6968 // for a media section, but the other does not. This is important to check
6969 // against in the case that we are recycling an m= section.
6970 const cricket::SessionDescription* current_desc = nullptr;
6971 const cricket::SessionDescription* secondary_current_desc = nullptr;
6972 if (local_description()) {
6973 current_desc = local_description()->description();
6974 if (remote_description()) {
6975 secondary_current_desc = remote_description()->description();
6976 }
6977 } else if (remote_description()) {
6978 current_desc = remote_description()->description();
6979 }
Steve Anton75737c02017-11-06 10:37:17 -08006980 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006981 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6982 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006983 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6984 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006985 }
6986 }
6987
Steve Antonba42e992018-04-09 14:10:01 -07006988 if (IsUnifiedPlan()) {
6989 // Ensure that each audio and video media section has at most one
6990 // "StreamParams". This will return an error if receiving a session
6991 // description from a "Plan B" endpoint which adds multiple tracks of the
6992 // same type. With Unified Plan, there can only be at most one track per
6993 // media section.
6994 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006995 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006996 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6997 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6998 desc.streams().size() > 1u) {
6999 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7000 "Media section has more than one track specified "
7001 "with a=ssrc lines which is not supported with "
7002 "Unified Plan.");
7003 }
7004 }
7005 }
7006
Steve Anton8a006912017-12-04 15:25:56 -08007007 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007008}
7009
Steve Anton3828c062017-12-06 10:34:51 -08007010bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007011 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007012 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007013 return (state == PeerConnectionInterface::kStable) ||
7014 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08007015 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007016 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007017 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7018 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7019 }
7020}
7021
Steve Anton3828c062017-12-06 10:34:51 -08007022bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007023 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007024 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007025 return (state == PeerConnectionInterface::kStable) ||
7026 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08007027 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007028 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007029 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7030 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7031 }
7032}
7033
Steve Antonf8470812017-12-04 10:46:21 -08007034const char* PeerConnection::SessionErrorToString(SessionError error) const {
7035 switch (error) {
7036 case SessionError::kNone:
7037 return "ERROR_NONE";
7038 case SessionError::kContent:
7039 return "ERROR_CONTENT";
7040 case SessionError::kTransport:
7041 return "ERROR_TRANSPORT";
7042 }
7043 RTC_NOTREACHED();
7044 return "";
7045}
7046
Steve Anton75737c02017-11-06 10:37:17 -08007047std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02007048 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08007049 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7050 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02007051 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08007052}
7053
Steve Anton8e20f172018-03-06 10:55:04 -08007054void PeerConnection::ReportSdpFormatReceived(
7055 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08007056 int num_audio_mlines = 0;
7057 int num_video_mlines = 0;
7058 int num_audio_tracks = 0;
7059 int num_video_tracks = 0;
7060 for (const ContentInfo& content : remote_offer.description()->contents()) {
7061 cricket::MediaType media_type = content.media_description()->type();
7062 int num_tracks = std::max(
7063 1, static_cast<int>(content.media_description()->streams().size()));
7064 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7065 num_audio_mlines += 1;
7066 num_audio_tracks += num_tracks;
7067 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7068 num_video_mlines += 1;
7069 num_video_tracks += num_tracks;
7070 }
7071 }
7072 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7073 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7074 format = kSdpFormatReceivedComplexUnifiedPlan;
7075 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7076 format = kSdpFormatReceivedComplexPlanB;
7077 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7078 format = kSdpFormatReceivedSimple;
7079 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007080 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7081 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007082}
7083
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007084void PeerConnection::ReportIceCandidateCollected(
7085 const cricket::Candidate& candidate) {
7086 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7087 if (candidate.address().IsPrivateIP()) {
7088 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7089 }
7090 if (candidate.address().IsUnresolvedIP()) {
7091 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7092 }
7093 if (candidate.address().family() == AF_INET6) {
7094 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7095 }
7096}
7097
7098void PeerConnection::ReportRemoteIceCandidateAdded(
7099 const cricket::Candidate& candidate) {
7100 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7101 if (candidate.address().IsPrivateIP()) {
7102 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7103 }
7104 if (candidate.address().IsUnresolvedIP()) {
7105 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7106 }
7107 if (candidate.address().family() == AF_INET6) {
7108 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7109 }
7110}
7111
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007112void PeerConnection::NoteUsageEvent(UsageEvent event) {
7113 RTC_DCHECK_RUN_ON(signaling_thread());
7114 usage_event_accumulator_ |= static_cast<int>(event);
7115}
7116
7117void PeerConnection::ReportUsagePattern() const {
7118 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007119 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7120 usage_event_accumulator_,
7121 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007122 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007123 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007124 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7125 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007126 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007127 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7128 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7129 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7130 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007131 // If called after close(), we can't report, because observer may have
7132 // been deallocated, and therefore pointer is null. Write to log instead.
7133 if (observer_) {
7134 Observer()->OnInterestingUsage(usage_event_accumulator_);
7135 } else {
7136 RTC_LOG(LS_INFO) << "Interesting usage signature "
7137 << usage_event_accumulator_
7138 << " observed after observer shutdown";
7139 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007140 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007141}
7142
Steve Anton0ffaaa22018-02-23 10:31:30 -08007143void PeerConnection::ReportNegotiatedSdpSemantics(
7144 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007145 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007146 switch (answer.description()->msid_signaling()) {
7147 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007148 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007149 break;
7150 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007151 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007152 break;
7153 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007154 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007155 break;
7156 case cricket::kMsidSignalingMediaSection |
7157 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007158 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007159 break;
7160 default:
7161 RTC_NOTREACHED();
7162 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007163 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7164 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007165}
7166
Steve Anton75737c02017-11-06 10:37:17 -08007167// We need to check the local/remote description for the Transport instead of
7168// the session, because a new Transport added during renegotiation may have
7169// them unset while the session has them set from the previous negotiation.
7170// Not doing so may trigger the auto generation of transport description and
7171// mess up DTLS identity information, ICE credential, etc.
7172bool PeerConnection::ReadyToUseRemoteCandidate(
7173 const IceCandidateInterface* candidate,
7174 const SessionDescriptionInterface* remote_desc,
7175 bool* valid) {
7176 *valid = true;
7177
7178 const SessionDescriptionInterface* current_remote_desc =
7179 remote_desc ? remote_desc : remote_description();
7180
7181 if (!current_remote_desc) {
7182 return false;
7183 }
7184
Guido Urdaneta41633172019-05-23 20:12:29 +02007185 RTCErrorOr<const cricket::ContentInfo*> result =
7186 FindContentInfo(current_remote_desc, candidate);
7187 if (!result.ok()) {
7188 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7189 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007190
7191 *valid = false;
7192 return false;
7193 }
7194
Guido Urdaneta41633172019-05-23 20:12:29 +02007195 std::string transport_name = GetTransportName(result.value()->name);
7196 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007197}
7198
7199bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007200 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007201 (dtls_enabled_ ||
7202 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007203}
7204
7205void PeerConnection::OnTransportControllerGatheringState(
7206 cricket::IceGatheringState state) {
7207 RTC_DCHECK(signaling_thread()->IsCurrent());
7208 if (state == cricket::kIceGatheringGathering) {
7209 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7210 } else if (state == cricket::kIceGatheringComplete) {
7211 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7212 }
7213}
7214
7215void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007216 std::map<std::string, std::set<cricket::MediaType>>
7217 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007218 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007219 if (transceiver->internal()->channel()) {
7220 const std::string& transport_name =
7221 transceiver->internal()->channel()->transport_name();
7222 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007223 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007224 }
Steve Anton75737c02017-11-06 10:37:17 -08007225 }
7226 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007227 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7228 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007229 }
Zhi Huange830e682018-03-30 10:48:35 -07007230
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007231 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007232 if (transport_name) {
7233 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007234 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007235 }
Zhi Huange830e682018-03-30 10:48:35 -07007236
Steve Antonc7b964c2018-02-01 14:39:45 -08007237 for (const auto& entry : media_types_by_transport_name) {
7238 const std::string& transport_name = entry.first;
7239 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007240 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007241 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007242 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007243 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007244 }
7245 }
7246}
7247// Walk through the ConnectionInfos to gather best connection usage
7248// for IPv4 and IPv6.
7249void PeerConnection::ReportBestConnectionState(
7250 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007251 for (const cricket::TransportChannelStats& channel_stats :
7252 stats.channel_stats) {
7253 for (const cricket::ConnectionInfo& connection_info :
7254 channel_stats.connection_infos) {
7255 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007256 continue;
7257 }
7258
Steve Antonc7b964c2018-02-01 14:39:45 -08007259 const cricket::Candidate& local = connection_info.local_candidate;
7260 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007261
7262 // Increment the counter for IceCandidatePairType.
7263 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7264 (local.type() == RELAY_PORT_TYPE &&
7265 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007266 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7267 GetIceCandidatePairCounter(local, remote),
7268 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007269 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007270 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7271 GetIceCandidatePairCounter(local, remote),
7272 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007273 } else {
7274 RTC_CHECK(0);
7275 }
Steve Anton75737c02017-11-06 10:37:17 -08007276
7277 // Increment the counter for IP type.
7278 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007279 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7280 kBestConnections_IPv4,
7281 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007282 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007283 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7284 kBestConnections_IPv6,
7285 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007286 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007287 RTC_CHECK(!local.address().hostname().empty() &&
7288 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007289 }
7290
7291 return;
7292 }
7293 }
7294}
7295
7296void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007297 const cricket::TransportStats& stats,
7298 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007299 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7300 return;
7301 }
7302
7303 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7304 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7305 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7306 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7307 return;
7308 }
7309
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007310 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7311 for (cricket::MediaType media_type : media_types) {
7312 switch (media_type) {
7313 case cricket::MEDIA_TYPE_AUDIO:
7314 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7315 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7316 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7317 break;
7318 case cricket::MEDIA_TYPE_VIDEO:
7319 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7320 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7321 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7322 break;
7323 case cricket::MEDIA_TYPE_DATA:
7324 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7325 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7326 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7327 break;
7328 default:
7329 RTC_NOTREACHED();
7330 continue;
7331 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007332 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007333 }
7334
7335 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7336 for (cricket::MediaType media_type : media_types) {
7337 switch (media_type) {
7338 case cricket::MEDIA_TYPE_AUDIO:
7339 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7340 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7341 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7342 break;
7343 case cricket::MEDIA_TYPE_VIDEO:
7344 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7345 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7346 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7347 break;
7348 case cricket::MEDIA_TYPE_DATA:
7349 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7350 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7351 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7352 break;
7353 default:
7354 RTC_NOTREACHED();
7355 continue;
7356 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007357 }
Steve Anton75737c02017-11-06 10:37:17 -08007358 }
7359}
7360
7361void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007362 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007363 RTC_DCHECK(call_);
7364 call_->OnSentPacket(sent_packet);
7365}
7366
7367const std::string PeerConnection::GetTransportName(
7368 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007369 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007370 if (channel) {
7371 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007372 }
Steve Anton6fec8802017-12-04 10:37:29 -08007373 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007374 RTC_DCHECK(sctp_mid_);
7375 if (content_name == *sctp_mid_) {
7376 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007377 }
7378 }
7379 // Return an empty string if failed to retrieve the transport name.
7380 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007381}
7382
Steve Anton6fec8802017-12-04 10:37:29 -08007383void PeerConnection::DestroyTransceiverChannel(
7384 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7385 transceiver) {
7386 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007387
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007388 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007389 if (channel) {
7390 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007391 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007392 }
7393}
7394
7395void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007396 if (rtp_data_channel_) {
7397 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007398 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007399 rtp_data_channel_ = nullptr;
7400 }
7401
7402 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7403 // grab a reference to this PeerConnection. If this is called from the
7404 // PeerConnection destructor, the RefCountedObject vtable will have already
7405 // been destroyed (since it is a subclass of PeerConnection) and using
7406 // rtc::Bind will cause "Pure virtual function called" error to appear.
7407
7408 if (sctp_transport_) {
7409 OnDataChannelDestroyed();
7410 network_thread()->Invoke<void>(RTC_FROM_HERE,
7411 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007412 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007413 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007414
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007415 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007416 OnDataChannelDestroyed();
7417 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7418 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007419 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007420 });
7421 }
Steve Anton6fec8802017-12-04 10:37:29 -08007422}
7423
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007424void PeerConnection::DestroyChannelInterface(
7425 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007426 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007427 switch (channel->media_type()) {
7428 case cricket::MEDIA_TYPE_AUDIO:
7429 channel_manager()->DestroyVoiceChannel(
7430 static_cast<cricket::VoiceChannel*>(channel));
7431 break;
7432 case cricket::MEDIA_TYPE_VIDEO:
7433 channel_manager()->DestroyVideoChannel(
7434 static_cast<cricket::VideoChannel*>(channel));
7435 break;
7436 case cricket::MEDIA_TYPE_DATA:
7437 channel_manager()->DestroyRtpDataChannel(
7438 static_cast<cricket::RtpDataChannel*>(channel));
7439 break;
7440 default:
7441 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7442 break;
7443 }
Zhi Huange830e682018-03-30 10:48:35 -07007444}
Steve Anton6fec8802017-12-04 10:37:29 -08007445
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007446bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007447 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007448 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007449 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007450 MediaTransportInterface* media_transport,
7451 DataChannelTransportInterface* data_channel_transport,
7452 JsepTransportController::NegotiationState negotiation_state) {
Karl Wibergac025892019-03-26 13:08:37 +01007453 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007454 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007455 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007456 auto base_channel = GetChannel(mid);
7457 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007458 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007459 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007460 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007461 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007462 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007463
Karl Wiberg5966c502019-02-21 23:55:09 +01007464 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007465 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007466 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007467
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007468 if (mid == sctp_mid_) {
7469 switch (negotiation_state) {
7470 case JsepTransportController::NegotiationState::kFinal:
7471 if (data_channel_transport) {
7472 if (sctp_transport_) {
7473 DestroySctpTransport_n();
7474 }
7475 } else {
7476 TeardownDataChannelTransport_n();
7477 }
7478 // We also need to mark the remaining transport as ready-to-send.
7479 RTC_FALLTHROUGH();
7480 case JsepTransportController::NegotiationState::kProvisional: {
7481 rtc::AsyncInvoker* invoker = data_channel_transport_invoker_
7482 ? data_channel_transport_invoker_.get()
7483 : sctp_invoker_.get();
7484 if (!invoker) {
7485 break; // Have neither SCTP nor DataChannelTransport, nothing to do.
7486 }
7487 invoker->AsyncInvoke<void>(
7488 RTC_FROM_HERE, signaling_thread(), [this, data_channel_transport] {
7489 RTC_DCHECK_RUN_ON(signaling_thread());
7490 if (data_channel_transport) {
7491 data_channel_transport_negotiated_ = true;
7492 if (data_channel_transport_ready_to_send_) {
7493 SignalDataChannelTransportWritable_s(
7494 data_channel_transport_ready_to_send_);
7495 }
7496 } else {
7497 sctp_negotiated_ = true;
7498 if (sctp_ready_to_send_data_) {
7499 SignalSctpReadyToSendData(sctp_ready_to_send_data_);
7500 }
7501 }
7502 });
7503 } break;
7504 case JsepTransportController::NegotiationState::kInitial:
7505 // Negotiation isn't finished. Nothing to do here.
7506 break;
7507 }
7508 }
7509
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007510 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007511}
7512
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007513void PeerConnection::OnSetStreams() {
7514 RTC_DCHECK_RUN_ON(signaling_thread());
7515 if (IsUnifiedPlan())
7516 UpdateNegotiationNeeded();
7517}
7518
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007519PeerConnectionObserver* PeerConnection::Observer() const {
7520 // In earlier production code, the pointer was not cleared on close,
7521 // which might have led to undefined behavior if the observer was not
7522 // deallocated, or strange crashes if it was.
7523 // We use CHECK in order to catch such behavior if it exists.
7524 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7525 RTC_CHECK(observer_);
7526 return observer_;
7527}
7528
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007529CryptoOptions PeerConnection::GetCryptoOptions() {
7530 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7531 // after it has been removed.
7532 return configuration_.crypto_options.has_value()
7533 ? *configuration_.crypto_options
7534 : factory_->options().crypto_options;
7535}
7536
Harald Alvestrand89061872018-01-02 14:08:34 +01007537void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007538 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007539 if (stats_collector_) {
7540 stats_collector_->ClearCachedStatsReport();
7541 }
7542}
7543
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007544void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007545 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7546 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007547}
7548
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007549void PeerConnection::UpdateNegotiationNeeded() {
7550 RTC_DCHECK_RUN_ON(signaling_thread());
7551 if (!IsUnifiedPlan()) {
7552 Observer()->OnRenegotiationNeeded();
7553 return;
7554 }
7555
7556 // If connection's [[IsClosed]] slot is true, abort these steps.
7557 if (IsClosed())
7558 return;
7559
7560 // If connection's signaling state is not "stable", abort these steps.
7561 if (signaling_state() != kStable)
7562 return;
7563
7564 // NOTE
7565 // The negotiation-needed flag will be updated once the state transitions to
7566 // "stable", as part of the steps for setting an RTCSessionDescription.
7567
7568 // If the result of checking if negotiation is needed is false, clear the
7569 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7570 // to false, and abort these steps.
7571 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7572 if (!is_negotiation_needed) {
7573 is_negotiation_needed_ = false;
7574 return;
7575 }
7576
7577 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7578 // steps.
7579 if (is_negotiation_needed_)
7580 return;
7581
7582 // Set connection's [[NegotiationNeeded]] slot to true.
7583 is_negotiation_needed_ = true;
7584
7585 // Queue a task that runs the following steps:
7586 // If connection's [[IsClosed]] slot is true, abort these steps.
7587 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7588 // Fire an event named negotiationneeded at connection.
7589 Observer()->OnRenegotiationNeeded();
7590}
7591
7592bool PeerConnection::CheckIfNegotiationIsNeeded() {
7593 RTC_DCHECK_RUN_ON(signaling_thread());
7594 // 1. If any implementation-specific negotiation is required, as described at
7595 // the start of this section, return true.
7596
Henrik Boström79b69802019-07-18 11:16:56 +02007597 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7598 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7599 return true;
7600 }
7601
7602 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007603 const SessionDescriptionInterface* description = current_local_description();
7604 if (!description)
7605 return true;
7606
Henrik Boström79b69802019-07-18 11:16:56 +02007607 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007608 // description has been negotiated yet for data, return true.
7609 if (!sctp_data_channels_.empty()) {
7610 if (!cricket::GetFirstDataContent(description->description()->contents()))
7611 return true;
7612 }
7613
Henrik Boström79b69802019-07-18 11:16:56 +02007614 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007615 // following checks:
7616 for (const auto& transceiver : transceivers_) {
7617 const ContentInfo* current_local_msection =
7618 FindTransceiverMSection(transceiver.get(), description);
7619
7620 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7621 transceiver.get(), current_remote_description());
7622
Henrik Boström79b69802019-07-18 11:16:56 +02007623 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007624 // but the associated m= section is not yet rejected in
7625 // connection.[[CurrentLocalDescription]] or
7626 // connection.[[CurrentRemoteDescription]], return true.
7627 if (transceiver->stopped()) {
7628 if (current_local_msection && !current_local_msection->rejected &&
7629 ((current_remote_msection && !current_remote_msection->rejected) ||
7630 !current_remote_msection)) {
7631 return true;
7632 }
7633 continue;
7634 }
7635
Henrik Boström79b69802019-07-18 11:16:56 +02007636 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007637 // section in description, return true.
7638 if (!current_local_msection)
7639 return true;
7640
7641 const MediaContentDescription* current_local_media_description =
7642 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007643 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007644 // in description then perform the following checks:
7645
Henrik Boström79b69802019-07-18 11:16:56 +02007646 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007647 // associated m= section in description either doesn't contain a single
7648 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7649 // m= section, or the MSID values themselves, differ from what is in
7650 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7651 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7652 if (current_local_media_description->streams().size() == 0)
7653 return true;
7654
7655 std::vector<std::string> msection_msids;
7656 for (const auto& stream : current_local_media_description->streams()) {
7657 for (const std::string& msid : stream.stream_ids())
7658 msection_msids.push_back(msid);
7659 }
7660
7661 std::vector<std::string> transceiver_msids =
7662 transceiver->sender()->stream_ids();
7663 if (msection_msids.size() != transceiver_msids.size())
7664 return true;
7665
7666 absl::c_sort(transceiver_msids);
7667 absl::c_sort(msection_msids);
7668 if (transceiver_msids != msection_msids)
7669 return true;
7670 }
7671
Henrik Boström79b69802019-07-18 11:16:56 +02007672 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007673 // associated m= section in neither connection.[[CurrentLocalDescription]]
7674 // nor connection.[[CurrentRemoteDescription]] matches
7675 // transceiver.[[Direction]], return true.
7676 if (description->GetType() == SdpType::kOffer) {
7677 if (!current_remote_description())
7678 return true;
7679
7680 if (!current_remote_msection)
7681 return true;
7682
7683 RtpTransceiverDirection current_local_direction =
7684 current_local_media_description->direction();
7685 RtpTransceiverDirection current_remote_direction =
7686 current_remote_msection->media_description()->direction();
7687 if (transceiver->direction() != current_local_direction &&
7688 transceiver->direction() !=
7689 RtpTransceiverDirectionReversed(current_remote_direction)) {
7690 return true;
7691 }
7692 }
7693
Henrik Boström79b69802019-07-18 11:16:56 +02007694 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007695 // associated m= section in the description does not match
7696 // transceiver.[[Direction]] intersected with the offered direction (as
7697 // described in [JSEP] (section 5.3.1.)), return true.
7698 if (description->GetType() == SdpType::kAnswer) {
7699 if (!remote_description())
7700 return true;
7701
7702 const ContentInfo* offered_remote_msection =
7703 FindTransceiverMSection(transceiver.get(), remote_description());
7704
7705 RtpTransceiverDirection offered_direction =
7706 offered_remote_msection
7707 ? offered_remote_msection->media_description()->direction()
7708 : RtpTransceiverDirection::kInactive;
7709
7710 if (current_local_media_description->direction() !=
7711 (RtpTransceiverDirectionIntersection(
7712 transceiver->direction(),
7713 RtpTransceiverDirectionReversed(offered_direction)))) {
7714 return true;
7715 }
7716 }
7717 }
7718
7719 // If all the preceding checks were performed and true was not returned,
7720 // nothing remains to be negotiated; return false.
7721 return false;
7722}
7723
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007724} // namespace webrtc