blob: 46a61ab517dc5897de8d47245c934f427672c262 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
Steve Antondcc3c022017-12-22 16:02:54 -080016#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080017#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080018#include <utility>
19#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000020
Steve Anton64b626b2019-01-28 17:25:26 -080021#include "absl/algorithm/container.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020028#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020029#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070030#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "logging/rtc_event_log/ice_logger.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Bjorn A Mellemb689af42019-08-21 10:44:59 -070059#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/trace_event.h"
61#include "system_wrappers/include/clock.h"
62#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070063#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080071using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080072using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080074using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080075using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080076using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080079using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070080using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080082
Steve Antonba818672017-11-06 10:21:57 -080083namespace webrtc {
84
Steve Anton75737c02017-11-06 10:37:17 -080085// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080089const char kInvalidCandidates[] = "Description contains invalid candidates.";
90const char kInvalidSdp[] = "Invalid session description.";
91const char kMlineMismatchInAnswer[] =
92 "The order of m-lines in answer doesn't match order in offer. Rejecting "
93 "answer.";
94const char kMlineMismatchInSubsequentOffer[] =
95 "The order of m-lines in subsequent offer doesn't match order from "
96 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080097const char kSdpWithoutDtlsFingerprint[] =
98 "Called with SDP without DTLS fingerprint.";
99const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
100const char kSdpWithoutIceUfragPwd[] =
101 "Called with SDP without ice-ufrag and ice-pwd.";
102const char kSessionError[] = "Session error code: ";
103const char kSessionErrorDesc[] = "Session error description: ";
104const char kDtlsSrtpSetupFailureRtp[] =
105 "Couldn't set up DTLS-SRTP on RTP channel.";
106const char kDtlsSrtpSetupFailureRtcp[] =
107 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108
Steve Anton75737c02017-11-06 10:37:17 -0800109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700111// Field trials.
112// Controls datagram transport support.
113const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700114// Controls datagram transport data channel support.
115const char kDatagramTransportDataChannelFieldTrial[] =
116 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700117
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800118// UMA metric names.
119const char kSimulcastVersionApplyLocalDescription[] =
120 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
121const char kSimulcastVersionApplyRemoteDescription[] =
122 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
123const char kSimulcastNumberOfEncodings[] =
124 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
125const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
126
Seth Hampson845e8782018-03-02 11:34:10 -0800127static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800128static const char kDefaultAudioSenderId[] = "defaulta0";
129static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700130
zhihuang8f65cdf2016-05-06 18:40:30 -0700131// The length of RTCP CNAMEs.
132static const int kRtcpCnameLength = 16;
133
Steve Antonad182762018-09-05 20:22:40 +0000134enum {
135 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
136 MSG_SET_SESSIONDESCRIPTION_FAILED,
137 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
138 MSG_GETSTATS,
139 MSG_FREE_DATACHANNELS,
140 MSG_REPORT_USAGE_PATTERN,
141};
142
Harald Alvestrand19793842018-06-25 12:03:50 +0200143static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
144
Steve Antonad182762018-09-05 20:22:40 +0000145struct SetSessionDescriptionMsg : public rtc::MessageData {
146 explicit SetSessionDescriptionMsg(
147 webrtc::SetSessionDescriptionObserver* observer)
148 : observer(observer) {}
149
150 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
151 RTCError error;
152};
153
154struct CreateSessionDescriptionMsg : public rtc::MessageData {
155 explicit CreateSessionDescriptionMsg(
156 webrtc::CreateSessionDescriptionObserver* observer)
157 : observer(observer) {}
158
159 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
160 RTCError error;
161};
162
163struct GetStatsMsg : public rtc::MessageData {
164 GetStatsMsg(webrtc::StatsObserver* observer,
165 webrtc::MediaStreamTrackInterface* track)
166 : observer(observer), track(track) {}
167 rtc::scoped_refptr<webrtc::StatsObserver> observer;
168 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
169};
170
deadbeefab9b2d12015-10-14 11:33:11 -0700171// Check if we can send |new_stream| on a PeerConnection.
172bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
173 webrtc::MediaStreamInterface* new_stream) {
174 if (!new_stream || !current_streams) {
175 return false;
176 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700177 if (current_streams->find(new_stream->id()) != nullptr) {
178 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700180 return false;
181 }
182 return true;
183}
184
deadbeef5e97fb52015-10-15 12:49:08 -0700185// If the direction is "recvonly" or "inactive", treat the description
186// as containing no streams.
187// See: https://code.google.com/p/webrtc/issues/detail?id=5054
188std::vector<cricket::StreamParams> GetActiveStreams(
189 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800190 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700191 ? desc->streams()
192 : std::vector<cricket::StreamParams>();
193}
194
deadbeefab9b2d12015-10-14 11:33:11 -0700195bool IsValidOfferToReceiveMedia(int value) {
196 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
197 return (value >= Options::kUndefined) &&
198 (value <= Options::kMaxOfferToReceiveMedia);
199}
200
zhihuang1c378ed2017-08-17 14:10:50 -0700201// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800202void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700203 const std::vector<rtc::scoped_refptr<
204 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700205 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200206 cricket::MediaDescriptionOptions* video_media_description_options,
207 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700208 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
210 if (audio_media_description_options) {
211 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700212 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 } else {
215 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
216 if (video_media_description_options) {
217 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800218 sender->id(), sender->internal()->stream_ids(), {},
219 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700220 }
221 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700222 }
zhihuang1c378ed2017-08-17 14:10:50 -0700223}
olka3c747662017-08-17 06:50:32 -0700224
zhihuang1c378ed2017-08-17 14:10:50 -0700225// Add options to |session_options| from |rtp_data_channels|.
226void AddRtpDataChannelOptions(
227 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
228 rtp_data_channels,
229 cricket::MediaDescriptionOptions* data_media_description_options) {
230 if (!data_media_description_options) {
231 return;
232 }
deadbeefab9b2d12015-10-14 11:33:11 -0700233 // Check for data channels.
234 for (const auto& kv : rtp_data_channels) {
235 const DataChannel* channel = kv.second;
236 if (channel->state() == DataChannel::kConnecting ||
237 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700238 // Legacy RTP data channels are signaled with the track/stream ID set to
239 // the data channel's label.
240 data_media_description_options->AddRtpDataChannel(channel->label(),
241 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700242 }
243 }
244}
245
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246uint32_t ConvertIceTransportTypeToCandidateFilter(
247 PeerConnectionInterface::IceTransportsType type) {
248 switch (type) {
249 case PeerConnectionInterface::kNone:
250 return cricket::CF_NONE;
251 case PeerConnectionInterface::kRelay:
252 return cricket::CF_RELAY;
253 case PeerConnectionInterface::kNoHost:
254 return (cricket::CF_ALL & ~cricket::CF_HOST);
255 case PeerConnectionInterface::kAll:
256 return cricket::CF_ALL;
257 default:
nissec80e7412017-01-11 05:56:46 -0800258 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700259 }
260 return cricket::CF_NONE;
261}
262
Steve Antonba818672017-11-06 10:21:57 -0800263std::string GetSignalingStateString(
264 PeerConnectionInterface::SignalingState state) {
265 switch (state) {
266 case PeerConnectionInterface::kStable:
267 return "kStable";
268 case PeerConnectionInterface::kHaveLocalOffer:
269 return "kHaveLocalOffer";
270 case PeerConnectionInterface::kHaveLocalPrAnswer:
271 return "kHavePrAnswer";
272 case PeerConnectionInterface::kHaveRemoteOffer:
273 return "kHaveRemoteOffer";
274 case PeerConnectionInterface::kHaveRemotePrAnswer:
275 return "kHaveRemotePrAnswer";
276 case PeerConnectionInterface::kClosed:
277 return "kClosed";
278 }
279 RTC_NOTREACHED();
280 return "";
281}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282
Steve Anton75737c02017-11-06 10:37:17 -0800283IceCandidatePairType GetIceCandidatePairCounter(
284 const cricket::Candidate& local,
285 const cricket::Candidate& remote) {
286 const auto& l = local.type();
287 const auto& r = remote.type();
288 const auto& host = LOCAL_PORT_TYPE;
289 const auto& srflx = STUN_PORT_TYPE;
290 const auto& relay = RELAY_PORT_TYPE;
291 const auto& prflx = PRFLX_PORT_TYPE;
292 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 bool local_hostname =
294 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
295 bool remote_hostname = !remote.address().hostname().empty() &&
296 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800297 bool local_private = IPIsPrivate(local.address().ipaddr());
298 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800299 if (local_hostname) {
300 if (remote_hostname) {
301 return kIceCandidatePairHostNameHostName;
302 } else if (remote_private) {
303 return kIceCandidatePairHostNameHostPrivate;
304 } else {
305 return kIceCandidatePairHostNameHostPublic;
306 }
307 } else if (local_private) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostPrivateHostName;
310 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800311 return kIceCandidatePairHostPrivateHostPrivate;
312 } else {
313 return kIceCandidatePairHostPrivateHostPublic;
314 }
315 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800316 if (remote_hostname) {
317 return kIceCandidatePairHostPublicHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPublicHostPrivate;
320 } else {
321 return kIceCandidatePairHostPublicHostPublic;
322 }
323 }
324 }
325 if (l == host && r == srflx)
326 return kIceCandidatePairHostSrflx;
327 if (l == host && r == relay)
328 return kIceCandidatePairHostRelay;
329 if (l == host && r == prflx)
330 return kIceCandidatePairHostPrflx;
331 if (l == srflx && r == host)
332 return kIceCandidatePairSrflxHost;
333 if (l == srflx && r == srflx)
334 return kIceCandidatePairSrflxSrflx;
335 if (l == srflx && r == relay)
336 return kIceCandidatePairSrflxRelay;
337 if (l == srflx && r == prflx)
338 return kIceCandidatePairSrflxPrflx;
339 if (l == relay && r == host)
340 return kIceCandidatePairRelayHost;
341 if (l == relay && r == srflx)
342 return kIceCandidatePairRelaySrflx;
343 if (l == relay && r == relay)
344 return kIceCandidatePairRelayRelay;
345 if (l == relay && r == prflx)
346 return kIceCandidatePairRelayPrflx;
347 if (l == prflx && r == host)
348 return kIceCandidatePairPrflxHost;
349 if (l == prflx && r == srflx)
350 return kIceCandidatePairPrflxSrflx;
351 if (l == prflx && r == relay)
352 return kIceCandidatePairPrflxRelay;
353 return kIceCandidatePairMax;
354}
355
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800356// Logic to decide if an m= section can be recycled. This means that the new
357// m= section is not rejected, but the old local or remote m= section is
358// rejected. |old_content_one| and |old_content_two| refer to the m= section
359// of the old remote and old local descriptions in no particular order.
360// We need to check both the old local and remote because either
361// could be the most current from the latest negotation.
362bool IsMediaSectionBeingRecycled(SdpType type,
363 const ContentInfo& content,
364 const ContentInfo* old_content_one,
365 const ContentInfo* old_content_two) {
366 return type == SdpType::kOffer && !content.rejected &&
367 ((old_content_one && old_content_one->rejected) ||
368 (old_content_two && old_content_two->rejected));
369}
370
Steve Anton75737c02017-11-06 10:37:17 -0800371// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372// |current_desc|. The number of m= sections in |new_desc| should be no
373// less than |current_desc|. In the case of checking an answer's
374// |new_desc|, the |current_desc| is the last offer that was set as the
375// local or remote. In the case of checking an offer's |new_desc| we
376// check against the local and remote descriptions stored from the last
377// negotiation, because either of these could be the most up to date for
378// possible rejected m sections. These are the |current_desc| and
379// |secondary_current_desc|.
380bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
381 const SessionDescription* secondary_current_desc,
382 const SessionDescription& new_desc,
383 const SdpType type) {
384 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800385 return false;
386 }
387
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
389 const cricket::ContentInfo* secondary_content_info = nullptr;
390 if (secondary_current_desc &&
391 i < secondary_current_desc->contents().size()) {
392 secondary_content_info = &secondary_current_desc->contents()[i];
393 }
394 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
395 &current_desc.contents()[i],
396 secondary_content_info)) {
397 // For new offer descriptions, if the media section can be recycled, it's
398 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800399 continue;
400 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800402 return false;
403 }
404 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800405 new_desc.contents()[i].media_description();
406 const MediaContentDescription* current_desc_mdesc =
407 current_desc.contents()[i].media_description();
408 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800409 return false;
410 }
411 }
412 return true;
413}
414
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800415bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
416 const SessionDescription& desc2) {
417 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800418}
419
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700420void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
421 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200422 // Array of structs needed to map {KeyExchangeProtocolType,
423 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
424 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
425 static constexpr struct {
426 KeyExchangeProtocolType protocol_type;
427 cricket::MediaType media_type;
428 KeyExchangeProtocolMedia protocol_media;
429 } kEnumCounterKeyProtocolMediaMap[] = {
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
434 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeDtlsData},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
437 kEnumCounterKeyProtocolMediaTypeSdesAudio},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
439 kEnumCounterKeyProtocolMediaTypeSdesVideo},
440 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
441 kEnumCounterKeyProtocolMediaTypeSdesData},
442 };
443
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
445 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100446
Mirko Bonadeiab499822018-09-11 10:43:20 +0200447 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
448 if (i.protocol_type == protocol_type && i.media_type == media_type) {
449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
450 i.protocol_media,
451 kEnumCounterKeyProtocolMediaTypeMax);
452 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100453 }
454}
455
Harald Alvestrand76829d72018-07-18 23:24:36 +0200456void NoteAddIceCandidateResult(int result) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
458 kAddIceCandidateMax);
459}
460
Steve Anton75737c02017-11-06 10:37:17 -0800461// Checks that each non-rejected content has SDES crypto keys or a DTLS
462// fingerprint, unless it's in a BUNDLE group, in which case only the
463// BUNDLE-tag section (first media section/description in the BUNDLE group)
464// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
465// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
466// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700467RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 const cricket::ContentGroup* bundle =
469 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800470 for (const cricket::ContentInfo& content_info : desc->contents()) {
471 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800472 continue;
473 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100474 // Note what media is used with each crypto protocol, for all sections.
475 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
476 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700477 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800478 const std::string& mid = content_info.name;
479 if (bundle && bundle->HasContentName(mid) &&
480 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 // This isn't the first media section in the BUNDLE group, so it's not
482 // required to have crypto attributes, since only the crypto attributes
483 // from the first section actually get used.
484 continue;
485 }
486
487 // If the content isn't rejected or bundled into another m= section, crypto
488 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800489 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800490 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (!media || !tinfo) {
492 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800494 }
495 if (dtls_enabled) {
496 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_WARNING)
498 << "Session description must have DTLS fingerprint if "
499 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError(RTCErrorType::INVALID_PARAMETER,
501 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 } else {
504 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800506 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800507 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800508 }
509 }
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800512}
513
514// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
515// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
516// media section/description in the BUNDLE group) needs a ufrag and pwd.
517bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
518 const cricket::ContentGroup* bundle =
519 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800520 for (const cricket::ContentInfo& content_info : desc->contents()) {
521 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 continue;
523 }
Steve Anton8a006912017-12-04 15:25:56 -0800524 const std::string& mid = content_info.name;
525 if (bundle && bundle->HasContentName(mid) &&
526 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 // This isn't the first media section in the BUNDLE group, so it's not
528 // required to have ufrag/password, since only the ufrag/password from
529 // the first section actually get used.
530 continue;
531 }
532
533 // If the content isn't rejected or bundled into another m= section,
534 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800535 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800536 if (!tinfo) {
537 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 if (tinfo->description.ice_ufrag.empty() ||
542 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 }
547 return true;
548}
549
Steve Anton75737c02017-11-06 10:37:17 -0800550// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
551bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
552 const SessionDescriptionInterface* new_desc,
553 const std::string& content_name) {
554 if (!old_desc) {
555 return false;
556 }
557 const SessionDescription* new_sd = new_desc->description();
558 const SessionDescription* old_sd = old_desc->description();
559 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
560 if (!cinfo || cinfo->rejected) {
561 return false;
562 }
563 // If the content isn't rejected, check if ufrag and password has changed.
564 const cricket::TransportDescription* new_transport_desc =
565 new_sd->GetTransportDescriptionByName(content_name);
566 const cricket::TransportDescription* old_transport_desc =
567 old_sd->GetTransportDescriptionByName(content_name);
568 if (!new_transport_desc || !old_transport_desc) {
569 // No transport description exists. This is not an ICE restart.
570 return false;
571 }
572 if (cricket::IceCredentialsChanged(
573 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
574 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
576 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800577 return true;
578 }
579 return false;
580}
581
Steve Anton80dd7b52018-02-16 17:08:42 -0800582// Generates a string error message for SetLocalDescription/SetRemoteDescription
583// from an RTCError.
584std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
585 SdpType type,
586 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200587 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800588 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
589 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200590 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800591}
592
Seth Hampson5b4f0752018-04-02 16:31:36 -0700593std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
594 std::string output = "streams=[";
595 const char* separator = "";
596 for (const auto& stream_id : stream_ids) {
597 output.append(separator).append(stream_id);
598 separator = ", ";
599 }
600 output.append("]");
601 return output;
602}
603
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200604absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700605 int rtc_configuration_parameter) {
606 if (rtc_configuration_parameter ==
607 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200608 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700609 }
610 return rtc_configuration_parameter;
611}
612
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800613void ReportSimulcastApiVersion(const char* name,
614 const SessionDescription& session) {
615 bool has_legacy = false;
616 bool has_spec_compliant = false;
617 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200618 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800619 continue;
620 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200621 has_spec_compliant |= content.media_description()->HasSimulcast();
622 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800623 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
624 }
625 }
626
627 if (has_legacy) {
628 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
629 kSimulcastApiVersionMax);
630 }
631 if (has_spec_compliant) {
632 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
633 kSimulcastApiVersionMax);
634 }
635 if (!has_legacy && !has_spec_compliant) {
636 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
637 kSimulcastApiVersionMax);
638 }
639}
640
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200641const ContentInfo* FindTransceiverMSection(
642 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
643 const SessionDescriptionInterface* session_description) {
644 return transceiver->mid()
645 ? session_description->description()->GetContentByName(
646 *transceiver->mid())
647 : nullptr;
648}
649
Henrik Boströma3728d32019-10-28 12:09:49 +0100650// Wraps a CreateSessionDescriptionObserver and an OperationsChain operation
651// complete callback. When the observer is invoked, the wrapped observer is
652// invoked followed by invoking the completion callback.
653class CreateSessionDescriptionObserverOperationWrapper
654 : public CreateSessionDescriptionObserver {
655 public:
656 CreateSessionDescriptionObserverOperationWrapper(
657 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer,
658 std::function<void()> operation_complete_callback)
659 : observer_(std::move(observer)),
660 operation_complete_callback_(std::move(operation_complete_callback)) {
661 RTC_DCHECK(observer_);
662 }
663 ~CreateSessionDescriptionObserverOperationWrapper() override {
664 RTC_DCHECK(was_called_);
665 }
666
667 void OnSuccess(SessionDescriptionInterface* desc) override {
668 RTC_DCHECK(!was_called_);
669#ifdef RTC_DCHECK_IS_ON
670 was_called_ = true;
671#endif // RTC_DCHECK_IS_ON
672 // Completing the operation before invoking the observer allows the observer
673 // to execute SetLocalDescription() without delay.
674 operation_complete_callback_();
675 observer_->OnSuccess(desc);
676 }
677
678 void OnFailure(RTCError error) override {
679 RTC_DCHECK(!was_called_);
680#ifdef RTC_DCHECK_IS_ON
681 was_called_ = true;
682#endif // RTC_DCHECK_IS_ON
683 operation_complete_callback_();
684 observer_->OnFailure(std::move(error));
685 }
686
687 private:
688#ifdef RTC_DCHECK_IS_ON
689 bool was_called_ = false;
690#endif // RTC_DCHECK_IS_ON
691 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer_;
692 std::function<void()> operation_complete_callback_;
693};
694
Steve Anton75737c02017-11-06 10:37:17 -0800695} // namespace
696
Henrik Boström4e196702019-10-30 10:35:50 +0100697// Used by parameterless SetLocalDescription() to create an offer or answer.
698// Upon completion of creating the session description, SetLocalDescription() is
699// invoked with the result.
700// For consistency with DoSetLocalDescription(), if the PeerConnection is
701// destroyed midst operation, we DO NOT inform the
702// |set_local_description_observer| that the operation failed.
703// TODO(hbos): If/when we process SLD messages in ~PeerConnection, the
704// consistent thing would be to inform the observer here.
705class PeerConnection::ImplicitCreateSessionDescriptionObserver
706 : public CreateSessionDescriptionObserver {
707 public:
708 ImplicitCreateSessionDescriptionObserver(
709 rtc::WeakPtr<PeerConnection> pc,
710 rtc::scoped_refptr<SetSessionDescriptionObserver>
711 set_local_description_observer)
712 : pc_(std::move(pc)),
713 set_local_description_observer_(
714 std::move(set_local_description_observer)) {}
715 ~ImplicitCreateSessionDescriptionObserver() override {
716 RTC_DCHECK(was_called_);
717 }
718
719 void SetOperationCompleteCallback(
720 std::function<void()> operation_complete_callback) {
721 operation_complete_callback_ = std::move(operation_complete_callback);
722 }
723
724 bool was_called() const { return was_called_; }
725
726 void OnSuccess(SessionDescriptionInterface* desc_ptr) override {
727 RTC_DCHECK(!was_called_);
728 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
729 was_called_ = true;
730
731 // Abort early if |pc_| is no longer valid.
732 if (!pc_) {
733 operation_complete_callback_();
734 return;
735 }
736 // DoSetLocalDescription() is currently implemented as a synchronous
737 // operation but where the |set_local_description_observer_|'s callbacks are
738 // invoked asynchronously in a post to PeerConnection::OnMessage().
739 pc_->DoSetLocalDescription(std::move(desc),
740 std::move(set_local_description_observer_));
741 // For backwards-compatability reasons, we declare the operation as
742 // completed here (rather than in PeerConnection::OnMessage()). This ensures
743 // that subsequent offer/answer operations can start immediately (without
744 // waiting for OnMessage()).
745 operation_complete_callback_();
746 }
747
748 void OnFailure(RTCError error) override {
749 RTC_DCHECK(!was_called_);
750 was_called_ = true;
751
752 // Abort early if |pc_| is no longer valid.
753 if (!pc_) {
754 operation_complete_callback_();
755 return;
756 }
757 // DoSetLocalDescription() reports its failures in a post. We do the
758 // same thing here for consistency.
759 pc_->PostSetSessionDescriptionFailure(
760 set_local_description_observer_,
761 RTCError(error.type(),
762 std::string("SetLocalDescription failed to create "
763 "session description - ") +
764 error.message()));
765 operation_complete_callback_();
766 }
767
768 private:
769 bool was_called_ = false;
770 rtc::WeakPtr<PeerConnection> pc_;
771 rtc::scoped_refptr<SetSessionDescriptionObserver>
772 set_local_description_observer_;
773 std::function<void()> operation_complete_callback_;
774};
775
Henrik Boström79b69802019-07-18 11:16:56 +0200776class PeerConnection::LocalIceCredentialsToReplace {
777 public:
778 // Sets the ICE credentials that need restarting to the ICE credentials of
779 // the current and pending descriptions.
780 void SetIceCredentialsFromLocalDescriptions(
781 const SessionDescriptionInterface* current_local_description,
782 const SessionDescriptionInterface* pending_local_description) {
783 ice_credentials_.clear();
784 if (current_local_description) {
785 AppendIceCredentialsFromSessionDescription(*current_local_description);
786 }
787 if (pending_local_description) {
788 AppendIceCredentialsFromSessionDescription(*pending_local_description);
789 }
790 }
791
792 void ClearIceCredentials() { ice_credentials_.clear(); }
793
794 // Returns true if we have ICE credentials that need restarting.
795 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
796
797 // Returns true if |local_description| shares no ICE credentials with the
798 // ICE credentials that need restarting.
799 bool SatisfiesIceRestart(
800 const SessionDescriptionInterface& local_description) const {
801 for (const auto& transport_info :
802 local_description.description()->transport_infos()) {
803 if (ice_credentials_.find(std::make_pair(
804 transport_info.description.ice_ufrag,
805 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
806 return false;
807 }
808 }
809 return true;
810 }
811
812 private:
813 void AppendIceCredentialsFromSessionDescription(
814 const SessionDescriptionInterface& desc) {
815 for (const auto& transport_info : desc.description()->transport_infos()) {
816 ice_credentials_.insert(
817 std::make_pair(transport_info.description.ice_ufrag,
818 transport_info.description.ice_pwd));
819 }
820 }
821
822 std::set<std::pair<std::string, std::string>> ice_credentials_;
823};
824
Henrik Boström31638672017-11-23 17:48:32 +0100825// Upon completion, posts a task to execute the callback of the
826// SetSessionDescriptionObserver asynchronously on the same thread. At this
827// point, the state of the peer connection might no longer reflect the effects
828// of the SetRemoteDescription operation, as the peer connection could have been
829// modified during the post.
830// TODO(hbos): Remove this class once we remove the version of
831// PeerConnectionInterface::SetRemoteDescription() that takes a
832// SetSessionDescriptionObserver as an argument.
833class PeerConnection::SetRemoteDescriptionObserverAdapter
834 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
835 public:
836 SetRemoteDescriptionObserverAdapter(
837 rtc::scoped_refptr<PeerConnection> pc,
838 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
839 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
840
841 // SetRemoteDescriptionObserverInterface implementation.
842 void OnSetRemoteDescriptionComplete(RTCError error) override {
843 if (error.ok())
844 pc_->PostSetSessionDescriptionSuccess(wrapper_);
845 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100846 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100847 }
848
849 private:
850 rtc::scoped_refptr<PeerConnection> pc_;
851 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
852};
853
deadbeef293e9262017-01-11 12:28:30 -0800854bool PeerConnectionInterface::RTCConfiguration::operator==(
855 const PeerConnectionInterface::RTCConfiguration& o) const {
856 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700857 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800858 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000859 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700860 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800861 BundlePolicy bundle_policy;
862 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700863 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
864 int ice_candidate_pool_size;
865 bool disable_ipv6;
866 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700867 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100868 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700869 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200870 absl::optional<int> screencast_min_bitrate;
871 absl::optional<bool> combined_audio_video_bwe;
872 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800873 TcpCandidatePolicy tcp_candidate_policy;
874 CandidateNetworkPolicy candidate_network_policy;
875 int audio_jitter_buffer_max_packets;
876 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100877 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100878 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800879 int ice_connection_receiving_timeout;
880 int ice_backup_candidate_pair_ping_interval;
881 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800882 bool prioritize_most_likely_ice_candidate_pairs;
883 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800884 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700885 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 12:28:30 -0800886 bool presume_writable_when_fully_relayed;
887 bool enable_ice_renomination;
888 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700889 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200890 absl::optional<int> ice_check_interval_strong_connectivity;
891 absl::optional<int> ice_check_interval_weak_connectivity;
892 absl::optional<int> ice_check_min_interval;
893 absl::optional<int> ice_unwritable_timeout;
894 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800895 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200896 absl::optional<int> stun_candidate_keepalive_interval;
897 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200898 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800899 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200900 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700901 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700902 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700903 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700904 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700905 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700906 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700907 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100908 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200909 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 18:29:44 +0300910 bool enable_implicit_rollback;
philipel16cec3b2019-10-25 12:23:02 +0200911 absl::optional<bool> allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800912 };
913 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
914 "Did you add something to RTCConfiguration and forget to "
915 "update operator==?");
916 return type == o.type && servers == o.servers &&
917 bundle_policy == o.bundle_policy &&
918 rtcp_mux_policy == o.rtcp_mux_policy &&
919 tcp_candidate_policy == o.tcp_candidate_policy &&
920 candidate_network_policy == o.candidate_network_policy &&
921 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
922 audio_jitter_buffer_fast_accelerate ==
923 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100924 audio_jitter_buffer_min_delay_ms ==
925 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100926 audio_jitter_buffer_enable_rtx_handling ==
927 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800928 ice_connection_receiving_timeout ==
929 o.ice_connection_receiving_timeout &&
930 ice_backup_candidate_pair_ping_interval ==
931 o.ice_backup_candidate_pair_ping_interval &&
932 continual_gathering_policy == o.continual_gathering_policy &&
933 certificates == o.certificates &&
934 prioritize_most_likely_ice_candidate_pairs ==
935 o.prioritize_most_likely_ice_candidate_pairs &&
936 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800937 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700938 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100939 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800940 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800941 screencast_min_bitrate == o.screencast_min_bitrate &&
942 combined_audio_video_bwe == o.combined_audio_video_bwe &&
943 enable_dtls_srtp == o.enable_dtls_srtp &&
944 ice_candidate_pool_size == o.ice_candidate_pool_size &&
945 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700946 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 12:28:30 -0800947 presume_writable_when_fully_relayed ==
948 o.presume_writable_when_fully_relayed &&
949 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800950 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700951 surface_ice_candidates_on_ice_transport_type_changed ==
952 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800953 ice_check_interval_strong_connectivity ==
954 o.ice_check_interval_strong_connectivity &&
955 ice_check_interval_weak_connectivity ==
956 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700957 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700958 ice_unwritable_timeout == o.ice_unwritable_timeout &&
959 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800960 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800961 stun_candidate_keepalive_interval ==
962 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200963 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800964 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800965 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700966 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700967 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700968 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700969 use_media_transport_for_data_channels ==
970 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700971 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700972 use_datagram_transport_for_data_channels ==
973 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700974 use_datagram_transport_for_data_channels_receive_only ==
975 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100976 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200977 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 18:29:44 +0300978 turn_logging_id == o.turn_logging_id &&
philipel16cec3b2019-10-25 12:23:02 +0200979 enable_implicit_rollback == o.enable_implicit_rollback &&
980 allow_codec_switching == o.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800981}
982
983bool PeerConnectionInterface::RTCConfiguration::operator!=(
984 const PeerConnectionInterface::RTCConfiguration& o) const {
985 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800986}
987
zhihuang8f65cdf2016-05-06 18:40:30 -0700988// Generate a RTCP CNAME when a PeerConnection is created.
989std::string GenerateRtcpCname() {
990 std::string cname;
991 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100992 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800993 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700994 }
995 return cname;
996}
997
zhihuang1c378ed2017-08-17 14:10:50 -0700998bool ValidateOfferAnswerOptions(
999 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
1000 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
1001 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -07001002}
1003
zhihuang1c378ed2017-08-17 14:10:50 -07001004// From |rtc_options|, fill parts of |session_options| shared by all generated
1005// m= sections (in other words, nothing that involves a map/array).
1006void ExtractSharedMediaSessionOptions(
1007 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1008 cricket::MediaSessionOptions* session_options) {
1009 session_options->vad_enabled = rtc_options.voice_activity_detection;
1010 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +02001011 session_options->raw_packetization_for_video =
1012 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -07001013}
zhihuanga77e6bb2017-08-14 18:17:48 -07001014
zhihuang38ede132017-06-15 12:52:32 -07001015PeerConnection::PeerConnection(PeerConnectionFactory* factory,
1016 std::unique_ptr<RtcEventLog> event_log,
1017 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -07001019 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +01001020 event_log_ptr_(event_log_.get()),
Henrik Boströma3728d32019-10-28 12:09:49 +01001021 operations_chain_(rtc::OperationsChain::Create()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001022 datagram_transport_config_(
1023 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001024 datagram_transport_data_channel_config_(
1025 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -07001026 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -07001027 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -07001028 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001029 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +02001030 call_ptr_(call_.get()),
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001031 data_channel_transport_(nullptr),
Henrik Boströma3728d32019-10-28 12:09:49 +01001032 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()),
1033 weak_ptr_factory_(this) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034
1035PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001036 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -08001037 RTC_DCHECK_RUN_ON(signaling_thread());
1038
Henrik Boströma3728d32019-10-28 12:09:49 +01001039 weak_ptr_factory_.InvalidateWeakPtrs();
1040
Steve Anton8af21862017-12-15 11:20:13 -08001041 // Need to stop transceivers before destroying the stats collector because
1042 // AudioRtpSender has a reference to the StatsCollector it will update when
1043 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +01001044 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08001045 transceiver->Stop();
1046 }
Steve Anton4171afb2017-11-20 10:20:22 -08001047
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001048 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -08001049 if (stats_collector_) {
1050 stats_collector_->WaitForPendingRequest();
1051 stats_collector_ = nullptr;
1052 }
Steve Anton75737c02017-11-06 10:37:17 -08001053
Steve Anton8af21862017-12-15 11:20:13 -08001054 // Don't destroy BaseChannels until after stats has been cleaned up so that
1055 // the last stats request can still read from the channels.
1056 DestroyAllChannels();
1057
Mirko Bonadei675513b2017-11-09 11:09:25 +01001058 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -08001059
1060 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001061 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001062 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001063 transport_controller_.reset();
1064
deadbeef91dd5672016-05-18 16:55:30 -07001065 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001066 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1067 RTC_DCHECK_RUN_ON(network_thread());
1068 port_allocator_.reset();
1069 });
eladalon248fd4f2017-09-06 05:18:15 -07001070 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -07001071 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01001072 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07001073 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -08001074 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -07001075 event_log_.reset();
1076 });
Henrik Boströma3728d32019-10-28 12:09:49 +01001077
1078 // Process all pending notifications in the message queue. If we don't do
1079 // this, requests will linger and not know they succeeded or failed.
1080 rtc::MessageList list;
1081 signaling_thread()->Clear(this, rtc::MQID_ANY, &list);
1082 for (auto& msg : list) {
1083 if (msg.message_id == MSG_CREATE_SESSIONDESCRIPTION_FAILED) {
1084 // Processing CreateOffer() and CreateAnswer() messages ensures their
1085 // observers are invoked even if the PeerConnection is destroyed early.
1086 OnMessage(&msg);
1087 } else {
1088 // TODO(hbos): Consider processing all pending messages. This would mean
1089 // that SetLocalDescription() and SetRemoteDescription() observers are
1090 // informed of successes and failures; this is currently NOT the case.
1091 delete msg.pdata;
1092 }
1093 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094}
1095
Steve Anton8af21862017-12-15 11:20:13 -08001096void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -08001097 // Destroy video channels first since they may have a pointer to a voice
1098 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +01001099 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001100 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001101 DestroyTransceiverChannel(transceiver);
1102 }
1103 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01001104 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001105 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001106 DestroyTransceiverChannel(transceiver);
1107 }
1108 }
1109 DestroyDataChannel();
1110}
1111
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001113 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -07001114 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001115 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01001116 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01001117 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -07001118
1119 RTCError config_error = ValidateConfiguration(configuration);
1120 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001121 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -07001122 return false;
1123 }
1124
Benjamin Wrightcab58882018-05-02 15:12:47 -07001125 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001126 RTC_LOG(LS_ERROR)
1127 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001128 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001129 return false;
1130 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001131
Benjamin Wrightcab58882018-05-02 15:12:47 -07001132 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001133 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001134 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001135 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001136 return false;
1137 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001138
Benjamin Wrightcab58882018-05-02 15:12:47 -07001139 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001140 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001141 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001142 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001143
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001144 cricket::ServerAddresses stun_servers;
1145 std::vector<cricket::RelayServerConfig> turn_servers;
1146
1147 RTCErrorType parse_error =
1148 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1149 if (parse_error != RTCErrorType::NONE) {
1150 return false;
1151 }
1152
Jonas Oreland3c028422019-08-22 16:16:35 +02001153 // Add the turn logging id to all turn servers
1154 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1155 turn_server.turn_logging_id = configuration.turn_logging_id;
1156 }
1157
deadbeef91dd5672016-05-18 16:55:30 -07001158 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001159 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001160 const auto pa_result =
1161 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001162 RTC_FROM_HERE,
1163 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001164 stun_servers, turn_servers, configuration));
1165
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001166 // If initialization was successful, note if STUN or TURN servers
1167 // were supplied.
1168 if (!stun_servers.empty()) {
1169 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1170 }
1171 if (!turn_servers.empty()) {
1172 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1173 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001175 // Send information about IPv4/IPv6 status.
1176 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001177 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001178 address_family = kPeerConnection_IPv6;
1179 } else {
1180 address_family = kPeerConnection_IPv4;
1181 }
1182 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1183 kPeerConnectionAddressFamilyCounter_Max);
1184
Zhi Huange830e682018-03-30 10:48:35 -07001185 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1186
Steve Anton75737c02017-11-06 10:37:17 -08001187 // RFC 3264: The numeric value of the session id and version in the
1188 // o line MUST be representable with a "64 bit signed integer".
1189 // Due to this constraint session id |session_id_| is max limited to
1190 // LLONG_MAX.
1191 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001192 JsepTransportController::Config config;
1193 config.redetermine_role_on_ice_restart =
1194 configuration.redetermine_role_on_ice_restart;
1195 config.ssl_max_version = factory_->options().ssl_max_version;
1196 config.disable_encryption = options.disable_encryption;
1197 config.bundle_policy = configuration.bundle_policy;
1198 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001199 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1200 // stub.
1201 config.crypto_options = configuration.crypto_options.has_value()
1202 ? *configuration.crypto_options
1203 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001204 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001205 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1206 // since the JsepTransportController instance is owned by this PeerConnection
1207 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1208 // pointer.
1209 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1210 int64_t packet_time_us) {
1211 RTC_DCHECK_RUN_ON(network_thread());
1212 rtcp_invoker_.AsyncInvoke<void>(
1213 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1214 RTC_DCHECK_RUN_ON(worker_thread());
1215 // |call_| is reset on the worker thread in the PeerConnection
1216 // destructor, so we check that it's still valid before propagating
1217 // the packet.
1218 if (call_) {
1219 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1220 packet_time_us);
1221 }
1222 });
1223 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001224 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001225#if defined(ENABLE_EXTERNAL_AUTH)
1226 config.enable_external_auth = true;
1227#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001228 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001229
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001230 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001231 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001232 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001233 use_datagram_transport_for_data_channels_ =
1234 datagram_transport_data_channel_config_.enabled &&
1235 configuration.use_datagram_transport_for_data_channels.value_or(
1236 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001237 use_datagram_transport_for_data_channels_receive_only_ =
1238 configuration.use_datagram_transport_for_data_channels_receive_only
1239 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001240 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1241 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001242 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001243 if (!factory_->media_transport_factory()) {
1244 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001245 << "PeerConnecton is initialized with use_media_transport = true or "
1246 << "use_media_transport_for_data_channels = true "
1247 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001248 return false;
1249 }
1250
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001251 if (configuration.use_media_transport ||
1252 configuration.use_media_transport_for_data_channels) {
1253 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1254 // RTP media transport is introduced. But until then, we require SDES to
1255 // be enabled.
1256 if (configuration.enable_dtls_srtp.has_value() &&
1257 configuration.enable_dtls_srtp.value()) {
1258 RTC_LOG(LS_WARNING)
1259 << "When media transport is used, SDES must be enabled. Set "
1260 "configuration.enable_dtls_srtp to false. use_media_transport="
1261 << configuration.use_media_transport
1262 << ", use_media_transport_for_data_channels="
1263 << configuration.use_media_transport_for_data_channels;
1264 return false;
1265 }
1266 }
1267
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001268 config.use_media_transport_for_media = configuration.use_media_transport;
1269 config.use_media_transport_for_data_channels =
1270 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001271 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001272 config.use_datagram_transport_for_data_channels =
1273 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001274 config.use_datagram_transport_for_data_channels_receive_only =
1275 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001276 config.media_transport_factory = factory_->media_transport_factory();
1277 }
1278
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001279 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1280 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1281 if (!configuration.certificates.empty()) {
1282 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1283 // just picking the first one. The decision should be made based on the DTLS
1284 // handshake. The DTLS negotiations need to know about all certificates.
1285 certificate = configuration.certificates[0];
1286 }
1287
1288 if (options.disable_encryption) {
1289 dtls_enabled_ = false;
1290 } else {
1291 // Enable DTLS by default if we have an identity store or a certificate.
1292 dtls_enabled_ = (dependencies.cert_generator || certificate);
1293 // |configuration| can override the default |dtls_enabled_| value.
1294 if (configuration.enable_dtls_srtp) {
1295 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1296 }
1297 }
1298
1299 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1300
1301 if (use_datagram_transport_for_data_channels_) {
1302 if (configuration.enable_rtp_data_channel) {
1303 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1304 "use_datagram_transport_for_data_channels are "
1305 "incompatible and cannot both be set to true";
1306 return false;
1307 }
1308 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1309 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1310 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1311 } else {
1312 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1313 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1314 config.sctp_factory = sctp_factory_.get();
1315 }
1316 } else if (configuration.use_media_transport_for_data_channels) {
1317 if (configuration.enable_rtp_data_channel) {
1318 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1319 "use_media_transport_for_data_channels are "
1320 "incompatible and cannot both be set to true";
1321 return false;
1322 }
1323 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1324 } else if (configuration.enable_rtp_data_channel) {
1325 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1326 // set. It takes precendence over the disable_sctp_data_channels
1327 // PeerConnectionFactoryInterface::Options.
1328 data_channel_type_ = cricket::DCT_RTP;
1329 } else {
1330 // DTLS has to be enabled to use SCTP.
1331 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1332 data_channel_type_ = cricket::DCT_SCTP;
1333 config.sctp_factory = sctp_factory_.get();
1334 }
1335 }
1336
Zhi Huange830e682018-03-30 10:48:35 -07001337 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001338 signaling_thread(), network_thread(), port_allocator_.get(),
1339 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001340 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001341 this, &PeerConnection::OnTransportControllerConnectionState);
1342 transport_controller_->SignalStandardizedIceConnectionState.connect(
1343 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001344 transport_controller_->SignalConnectionState.connect(
1345 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001346 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001347 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001348 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001349 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001350 transport_controller_->SignalIceCandidateError.connect(
1351 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001352 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001353 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1354 transport_controller_->SignalDtlsHandshakeError.connect(
1355 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001356 transport_controller_->SignalIceCandidatePairChanged.connect(
1357 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001358
deadbeefab9b2d12015-10-14 11:33:11 -07001359 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001360 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361
Steve Antonba818672017-11-06 10:21:57 -08001362 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001363 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001364
Steve Antond25da372017-11-06 14:50:29 -08001365 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001366
Steve Anton75737c02017-11-06 10:37:17 -08001367 video_options_.screencast_min_bitrate_kbps =
1368 configuration.screencast_min_bitrate;
1369 audio_options_.combined_audio_video_bwe =
1370 configuration.combined_audio_video_bwe;
1371
1372 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001373 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001374
1375 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001376 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001377
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001378 audio_options_.audio_jitter_buffer_min_delay_ms =
1379 configuration.audio_jitter_buffer_min_delay_ms;
1380
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001381 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1382 configuration.audio_jitter_buffer_enable_rtx_handling;
1383
Steve Anton75737c02017-11-06 10:37:17 -08001384 // Whether the certificate generator/certificate is null or not determines
1385 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1386 // the right instructions by clearing the variables if needed.
1387 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001388 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001389 certificate = nullptr;
1390 } else if (certificate) {
1391 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001392 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001393 }
1394
1395 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1396 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001397 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001398 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1399 this, &PeerConnection::OnCertificateReady);
1400
1401 if (options.disable_encryption) {
1402 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1403 }
1404
1405 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001406 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001407 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408
Steve Anton4171afb2017-11-20 10:20:22 -08001409 // Add default audio/video transceivers for Plan B SDP.
1410 if (!IsUnifiedPlan()) {
1411 transceivers_.push_back(
1412 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1413 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1414 transceivers_.push_back(
1415 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1416 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1417 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001418 int delay_ms =
1419 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001420 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1421 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001422
1423 if (dependencies.video_bitrate_allocator_factory) {
1424 video_bitrate_allocator_factory_ =
1425 std::move(dependencies.video_bitrate_allocator_factory);
1426 } else {
1427 video_bitrate_allocator_factory_ =
1428 CreateBuiltinVideoBitrateAllocatorFactory();
1429 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430 return true;
1431}
1432
Steve Anton038834f2017-07-14 15:59:59 -07001433RTCError PeerConnection::ValidateConfiguration(
1434 const RTCConfiguration& config) const {
1435 if (config.ice_regather_interval_range &&
1436 config.continual_gathering_policy == GATHER_ONCE) {
1437 return RTCError(RTCErrorType::INVALID_PARAMETER,
1438 "ice_regather_interval_range specified but continual "
1439 "gathering policy is GATHER_ONCE");
1440 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001441 auto result =
1442 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1443 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001444}
1445
Yves Gerey665174f2018-06-19 15:03:05 +02001446rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001447 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001448 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1449 "Plan SdpSemantics. Please use GetSenders "
1450 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001451 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452}
1453
Yves Gerey665174f2018-06-19 15:03:05 +02001454rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001455 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001456 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1457 "Plan SdpSemantics. Please use GetReceivers "
1458 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001459 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460}
1461
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001462bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001463 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001464 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1465 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001466 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467 if (IsClosed()) {
1468 return false;
1469 }
deadbeefab9b2d12015-10-14 11:33:11 -07001470 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 return false;
1472 }
deadbeefab9b2d12015-10-14 11:33:11 -07001473
1474 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001475 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1476 observer->SignalAudioTrackAdded.connect(this,
1477 &PeerConnection::OnAudioTrackAdded);
1478 observer->SignalAudioTrackRemoved.connect(
1479 this, &PeerConnection::OnAudioTrackRemoved);
1480 observer->SignalVideoTrackAdded.connect(this,
1481 &PeerConnection::OnVideoTrackAdded);
1482 observer->SignalVideoTrackRemoved.connect(
1483 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001484 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001485
deadbeefab9b2d12015-10-14 11:33:11 -07001486 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001487 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001488 }
1489 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001490 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001491 }
1492
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001493 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001494 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495 return true;
1496}
1497
1498void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001499 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001500 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1501 "Plan SdpSemantics. Please use RemoveTrack "
1502 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001503 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001504 if (!IsClosed()) {
1505 for (const auto& track : local_stream->GetAudioTracks()) {
1506 RemoveAudioTrack(track.get(), local_stream);
1507 }
1508 for (const auto& track : local_stream->GetVideoTracks()) {
1509 RemoveVideoTrack(track.get(), local_stream);
1510 }
deadbeefab9b2d12015-10-14 11:33:11 -07001511 }
deadbeefab9b2d12015-10-14 11:33:11 -07001512 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001513 stream_observers_.erase(
1514 std::remove_if(
1515 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001516 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001517 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001518 }),
1519 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001520
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001521 if (IsClosed()) {
1522 return;
1523 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001524 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001525}
1526
Steve Anton2d6c76a2018-01-05 17:10:52 -08001527RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001528 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001529 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001530 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001531 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001532 if (!track) {
1533 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1534 }
1535 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1536 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1537 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1538 "Track has invalid kind: " + track->kind());
1539 }
Steve Antonf9381f02017-12-14 10:23:57 -08001540 if (IsClosed()) {
1541 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1542 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001543 }
Steve Anton4171afb2017-11-20 10:20:22 -08001544 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001545 LOG_AND_RETURN_ERROR(
1546 RTCErrorType::INVALID_PARAMETER,
1547 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001548 }
Steve Antonf9381f02017-12-14 10:23:57 -08001549 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001550 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1551 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001552 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001553 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001554 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001555 }
1556 return sender_or_error;
1557}
deadbeefe1f9d832016-01-14 15:35:42 -08001558
Steve Antonf9381f02017-12-14 10:23:57 -08001559RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1560PeerConnection::AddTrackPlanB(
1561 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001562 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001563 if (stream_ids.size() > 1u) {
1564 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1565 "AddTrack with more than one stream is not "
1566 "supported with Plan B semantics.");
1567 }
1568 std::vector<std::string> adjusted_stream_ids = stream_ids;
1569 if (adjusted_stream_ids.empty()) {
1570 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1571 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001572 cricket::MediaType media_type =
1573 (track->kind() == MediaStreamTrackInterface::kAudioKind
1574 ? cricket::MEDIA_TYPE_AUDIO
1575 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001576 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001577 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001578 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001579 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001580 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001581 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001582 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001583 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001584 if (sender_info) {
1585 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001586 }
Steve Antonf9381f02017-12-14 10:23:57 -08001587 } else {
1588 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001589 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001590 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001591 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001592 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001593 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001594 if (sender_info) {
1595 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001596 }
deadbeefe1f9d832016-01-14 15:35:42 -08001597 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001598 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001599}
deadbeefe1f9d832016-01-14 15:35:42 -08001600
Steve Antonf9381f02017-12-14 10:23:57 -08001601RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1602PeerConnection::AddTrackUnifiedPlan(
1603 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001604 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001605 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1606 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001607 RTC_LOG(LS_INFO) << "Reusing an existing "
1608 << cricket::MediaTypeToString(transceiver->media_type())
1609 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001610 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001611 transceiver->internal()->set_direction(
1612 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001613 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001614 transceiver->internal()->set_direction(
1615 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001616 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001617 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001618 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001619 } else {
1620 cricket::MediaType media_type =
1621 (track->kind() == MediaStreamTrackInterface::kAudioKind
1622 ? cricket::MEDIA_TYPE_AUDIO
1623 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001624 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1625 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001626 std::string sender_id = track->id();
1627 // Avoid creating a sender with an existing ID by generating a random ID.
1628 // This can happen if this is the second time AddTrack has created a sender
1629 // for this track.
1630 if (FindSenderById(sender_id)) {
1631 sender_id = rtc::CreateRandomUuid();
1632 }
Florent Castelli892acf02018-10-01 22:47:20 +02001633 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001634 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1635 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001636 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001637 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001638 }
Steve Antonf9381f02017-12-14 10:23:57 -08001639 return transceiver->sender();
1640}
1641
1642rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1643PeerConnection::FindFirstTransceiverForAddedTrack(
1644 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1645 RTC_DCHECK(track);
1646 for (auto transceiver : transceivers_) {
1647 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001648 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001649 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001650 !transceiver->internal()->has_ever_been_used_to_send() &&
1651 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001652 return transceiver;
1653 }
1654 }
1655 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001656}
1657
1658bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1659 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001660 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001661}
1662
Steve Anton24db5732018-07-23 10:27:33 -07001663RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001664 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001665 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001666 if (!sender) {
1667 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1668 }
deadbeefe1f9d832016-01-14 15:35:42 -08001669 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1671 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001672 }
Steve Antonf9381f02017-12-14 10:23:57 -08001673 if (IsUnifiedPlan()) {
1674 auto transceiver = FindTransceiverBySender(sender);
1675 if (!transceiver || !sender->track()) {
1676 return RTCError::OK();
1677 }
1678 sender->SetTrack(nullptr);
1679 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001680 transceiver->internal()->set_direction(
1681 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001682 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001683 transceiver->internal()->set_direction(
1684 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001685 }
Steve Anton4171afb2017-11-20 10:20:22 -08001686 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001687 bool removed;
1688 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1689 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1690 } else {
1691 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1692 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1693 }
1694 if (!removed) {
1695 LOG_AND_RETURN_ERROR(
1696 RTCErrorType::INVALID_PARAMETER,
1697 "Couldn't find sender " + sender->id() + " to remove.");
1698 }
Steve Anton4171afb2017-11-20 10:20:22 -08001699 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001700 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001701 return RTCError::OK();
1702}
1703
1704rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1705PeerConnection::FindTransceiverBySender(
1706 rtc::scoped_refptr<RtpSenderInterface> sender) {
1707 for (auto transceiver : transceivers_) {
1708 if (transceiver->sender() == sender) {
1709 return transceiver;
1710 }
1711 }
1712 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001713}
1714
Steve Anton9158ef62017-11-27 13:01:52 -08001715RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1716PeerConnection::AddTransceiver(
1717 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1718 return AddTransceiver(track, RtpTransceiverInit());
1719}
1720
1721RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1722PeerConnection::AddTransceiver(
1723 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1724 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001725 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001726 RTC_CHECK(IsUnifiedPlan())
1727 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001728 if (!track) {
1729 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1730 }
1731 cricket::MediaType media_type;
1732 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1733 media_type = cricket::MEDIA_TYPE_AUDIO;
1734 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1735 media_type = cricket::MEDIA_TYPE_VIDEO;
1736 } else {
1737 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1738 "Track kind is not audio or video");
1739 }
1740 return AddTransceiver(media_type, track, init);
1741}
1742
1743RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1744PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1745 return AddTransceiver(media_type, RtpTransceiverInit());
1746}
1747
1748RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1749PeerConnection::AddTransceiver(cricket::MediaType media_type,
1750 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001751 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001752 RTC_CHECK(IsUnifiedPlan())
1753 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001754 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1755 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1756 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1757 "media type is not audio or video");
1758 }
1759 return AddTransceiver(media_type, nullptr, init);
1760}
1761
1762RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1763PeerConnection::AddTransceiver(
1764 cricket::MediaType media_type,
1765 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001766 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001767 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001768 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1769 media_type == cricket::MEDIA_TYPE_VIDEO));
1770 if (track) {
1771 RTC_DCHECK_EQ(media_type,
1772 (track->kind() == MediaStreamTrackInterface::kAudioKind
1773 ? cricket::MEDIA_TYPE_AUDIO
1774 : cricket::MEDIA_TYPE_VIDEO));
1775 }
1776
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001777 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1778 init.send_encodings.size(), 0, 7, 8);
1779
Amit Hilbuchaa584152019-02-06 17:09:52 -08001780 size_t num_rids = absl::c_count_if(init.send_encodings,
1781 [](const RtpEncodingParameters& encoding) {
1782 return !encoding.rid.empty();
1783 });
1784 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001785 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001786 RTCErrorType::INVALID_PARAMETER,
1787 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001788 }
1789
Amit Hilbuchf4770402019-04-08 14:11:57 -07001790 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1791 [](const RtpEncodingParameters& encoding) {
1792 return !IsLegalRsidName(encoding.rid);
1793 })) {
1794 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1795 "Invalid RID value provided.");
1796 }
1797
Amit Hilbuchaa584152019-02-06 17:09:52 -08001798 if (absl::c_any_of(init.send_encodings,
1799 [](const RtpEncodingParameters& encoding) {
1800 return encoding.ssrc.has_value();
1801 })) {
1802 LOG_AND_RETURN_ERROR(
1803 RTCErrorType::UNSUPPORTED_PARAMETER,
1804 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001805 }
1806
1807 RtpParameters parameters;
1808 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001809
1810 // Encodings are dropped from the tail if too many are provided.
1811 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1812 parameters.encodings.erase(
1813 parameters.encodings.begin() + kMaxSimulcastStreams,
1814 parameters.encodings.end());
1815 }
1816
1817 // Single RID should be removed.
1818 if (parameters.encodings.size() == 1 &&
1819 !parameters.encodings[0].rid.empty()) {
1820 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1821 parameters.encodings[0].rid.clear();
1822 }
1823
1824 // If RIDs were not provided, they are generated for simulcast scenario.
1825 if (parameters.encodings.size() > 1 && num_rids == 0) {
1826 rtc::UniqueStringGenerator rid_generator;
1827 for (RtpEncodingParameters& encoding : parameters.encodings) {
1828 encoding.rid = rid_generator();
1829 }
1830 }
1831
Florent Castelli892acf02018-10-01 22:47:20 +02001832 if (UnimplementedRtpParameterHasValue(parameters)) {
1833 LOG_AND_RETURN_ERROR(
1834 RTCErrorType::UNSUPPORTED_PARAMETER,
1835 "Attempted to set an unimplemented parameter of RtpParameters.");
1836 }
Steve Anton9158ef62017-11-27 13:01:52 -08001837
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001838 auto result = cricket::CheckRtpParametersValues(parameters);
1839 if (!result.ok()) {
1840 LOG_AND_RETURN_ERROR(result.type(), result.message());
1841 }
1842
Steve Anton3d954a62018-04-02 11:27:23 -07001843 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1844 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001845 // Set the sender ID equal to the track ID if the track is specified unless
1846 // that sender ID is already in use.
1847 std::string sender_id =
1848 (track && !FindSenderById(track->id()) ? track->id()
1849 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001850 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001851 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001852 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1853 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1854 transceiver->internal()->set_direction(init.direction);
1855
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001856 if (update_negotiation_needed) {
1857 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001858 }
Steve Antonf9381f02017-12-14 10:23:57 -08001859
1860 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1861}
1862
Steve Anton02ee47c2018-01-10 16:26:06 -08001863rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1864PeerConnection::CreateSender(
1865 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001866 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001867 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001868 const std::vector<std::string>& stream_ids,
1869 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001870 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001871 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001872 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1873 RTC_DCHECK(!track ||
1874 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1875 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1876 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001877 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001878 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001879 } else {
1880 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1881 RTC_DCHECK(!track ||
1882 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1883 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001884 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001885 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001886 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001887 bool set_track_succeeded = sender->SetTrack(track);
1888 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001889 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001890 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001891 return sender;
1892}
1893
1894rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1895PeerConnection::CreateReceiver(cricket::MediaType media_type,
1896 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001897 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1898 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001899 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001900 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001901 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1902 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001903 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001904 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001905 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001906 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001907 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1908 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001909 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001910 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001911 return receiver;
1912}
1913
1914rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1915PeerConnection::CreateAndAddTransceiver(
1916 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1917 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1918 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001919 // Ensure that the new sender does not have an ID that is already in use by
1920 // another sender.
1921 // Allow receiver IDs to conflict since those come from remote SDP (which
1922 // could be invalid, but should not cause a crash).
1923 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001924 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001925 signaling_thread(),
1926 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001927 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001928 transceiver->internal()->SignalNegotiationNeeded.connect(
1929 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001930 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001931}
1932
Steve Anton52d86772018-02-20 15:48:12 -08001933void PeerConnection::OnNegotiationNeeded() {
1934 RTC_DCHECK_RUN_ON(signaling_thread());
1935 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001936 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001937}
1938
deadbeeffac06552015-11-25 11:26:01 -08001939rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001940 const std::string& kind,
1941 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001942 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001943 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1944 "Plan SdpSemantics. Please use AddTransceiver "
1945 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001946 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001947 if (IsClosed()) {
1948 return nullptr;
1949 }
Steve Anton4171afb2017-11-20 10:20:22 -08001950
Seth Hampson5b4f0752018-04-02 16:31:36 -07001951 // Internally we need to have one stream with Plan B semantics, so we
1952 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001953 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001954 if (stream_id.empty()) {
1955 stream_ids.push_back(rtc::CreateRandomUuid());
1956 RTC_LOG(LS_INFO)
1957 << "No stream_id specified for sender. Generated stream ID: "
1958 << stream_ids[0];
1959 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001960 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001961 }
1962
Steve Anton4171afb2017-11-20 10:20:22 -08001963 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001964 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001965 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001966 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001967 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001968 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001969 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001970 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001971 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001972 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001973 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001974 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001975 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001976 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001977 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001978 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001979 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001980 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001981 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001982 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001983 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001984
deadbeefe1f9d832016-01-14 15:35:42 -08001985 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001986}
1987
deadbeef70ab1a12015-09-28 16:53:55 -07001988std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1989 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001990 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001991 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001992 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001993 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001994 }
1995 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001996}
1997
Steve Anton4171afb2017-11-20 10:20:22 -08001998std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1999PeerConnection::GetSendersInternal() const {
2000 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
2001 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002002 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08002003 auto senders = transceiver->internal()->senders();
2004 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
2005 }
2006 return all_senders;
2007}
2008
deadbeef70ab1a12015-09-28 16:53:55 -07002009std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
2010PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01002011 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07002012 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08002013 for (const auto& receiver : GetReceiversInternal()) {
2014 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07002015 }
2016 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07002017}
2018
Steve Anton4171afb2017-11-20 10:20:22 -08002019std::vector<
2020 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2021PeerConnection::GetReceiversInternal() const {
2022 std::vector<
2023 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2024 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002025 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08002026 auto receivers = transceiver->internal()->receivers();
2027 all_receivers.insert(all_receivers.end(), receivers.begin(),
2028 receivers.end());
2029 }
2030 return all_receivers;
2031}
2032
Steve Anton9158ef62017-11-27 13:01:52 -08002033std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2034PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01002035 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08002036 RTC_CHECK(IsUnifiedPlan())
2037 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08002038 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002039 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08002040 all_transceivers.push_back(transceiver);
2041 }
2042 return all_transceivers;
2043}
2044
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002046 MediaStreamTrackInterface* track,
2047 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002048 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002049 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08002050 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002051 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002052 return false;
2053 }
2054
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002055 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07002056 // The StatsCollector is used to tell if a track is valid because it may
2057 // remember tracks that the PeerConnection previously removed.
2058 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002059 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
2060 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07002061 return false;
2062 }
Steve Antonad182762018-09-05 20:22:40 +00002063 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
2064 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002065 return true;
2066}
2067
hbos74e1a4f2016-09-15 23:33:01 -07002068void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01002069 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002070 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07002071 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01002072 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07002073 stats_collector_->GetStatsReport(callback);
2074}
2075
Henrik Boström1df1bf82018-03-20 13:24:20 +01002076void PeerConnection::GetStats(
2077 rtc::scoped_refptr<RtpSenderInterface> selector,
2078 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2079 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002080 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002081 RTC_DCHECK(callback);
2082 RTC_DCHECK(stats_collector_);
2083 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
2084 if (selector) {
2085 for (const auto& proxy_transceiver : transceivers_) {
2086 for (const auto& proxy_sender :
2087 proxy_transceiver->internal()->senders()) {
2088 if (proxy_sender == selector) {
2089 internal_sender = proxy_sender->internal();
2090 break;
2091 }
2092 }
2093 if (internal_sender)
2094 break;
2095 }
2096 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002097 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01002098 // belong to the PeerConnection (in Plan B, senders can be removed from the
2099 // PeerConnection). This means that "all the stats objects representing the
2100 // selector" is an empty set. Invoking GetStatsReport() with a null selector
2101 // produces an empty stats report.
2102 stats_collector_->GetStatsReport(internal_sender, callback);
2103}
2104
2105void PeerConnection::GetStats(
2106 rtc::scoped_refptr<RtpReceiverInterface> selector,
2107 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2108 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002109 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002110 RTC_DCHECK(callback);
2111 RTC_DCHECK(stats_collector_);
2112 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
2113 if (selector) {
2114 for (const auto& proxy_transceiver : transceivers_) {
2115 for (const auto& proxy_receiver :
2116 proxy_transceiver->internal()->receivers()) {
2117 if (proxy_receiver == selector) {
2118 internal_receiver = proxy_receiver->internal();
2119 break;
2120 }
2121 }
2122 if (internal_receiver)
2123 break;
2124 }
2125 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002126 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01002127 // not belong to the PeerConnection (in Plan B, receivers can be removed from
2128 // the PeerConnection). This means that "all the stats objects representing
2129 // the selector" is an empty set. Invoking GetStatsReport() with a null
2130 // selector produces an empty stats report.
2131 stats_collector_->GetStatsReport(internal_receiver, callback);
2132}
2133
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002135 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136 return signaling_state_;
2137}
2138
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139PeerConnectionInterface::IceConnectionState
2140PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002141 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142 return ice_connection_state_;
2143}
2144
Alex Loiko9289eda2018-11-23 16:18:59 +00002145PeerConnectionInterface::IceConnectionState
2146PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002147 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00002148 return standardized_ice_connection_state_;
2149}
2150
Jonas Olsson635474e2018-10-18 15:58:17 +02002151PeerConnectionInterface::PeerConnectionState
2152PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002153 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002154 return connection_state_;
2155}
2156
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002157PeerConnectionInterface::IceGatheringState
2158PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002159 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160 return ice_gathering_state_;
2161}
2162
Yves Gerey665174f2018-06-19 15:03:05 +02002163rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002164 const std::string& label,
2165 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002166 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002167 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002168
deadbeefab9b2d12015-10-14 11:33:11 -07002169 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002170
kwibergd1fe2812016-04-27 06:47:29 -07002171 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002172 if (config) {
2173 internal_config.reset(new InternalDataChannelInit(*config));
2174 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002175 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002176 InternalCreateDataChannel(label, internal_config.get()));
2177 if (!channel.get()) {
2178 return nullptr;
2179 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002181 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2182 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002183 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002184 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002185 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002186 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187 return DataChannelProxy::Create(signaling_thread(), channel.get());
2188}
2189
Henrik Boström79b69802019-07-18 11:16:56 +02002190void PeerConnection::RestartIce() {
2191 RTC_DCHECK_RUN_ON(signaling_thread());
2192 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2193 current_local_description_.get(), pending_local_description_.get());
2194 UpdateNegotiationNeeded();
2195}
2196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002198 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002199 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002200 // Chain this operation. If asynchronous operations are pending on the chain,
2201 // this operation will be queued to be invoked, otherwise the contents of the
2202 // lambda will execute immediately.
2203 operations_chain_->ChainOperation(
2204 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2205 observer_refptr =
2206 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2207 options](std::function<void()> operations_chain_callback) {
2208 // Abort early if |this_weak_ptr| is no longer valid.
2209 if (!this_weak_ptr) {
2210 observer_refptr->OnFailure(
2211 RTCError(RTCErrorType::INTERNAL_ERROR,
2212 "CreateOffer failed because the session was shut down"));
2213 operations_chain_callback();
2214 return;
2215 }
2216 // The operation completes asynchronously when the wrapper is invoked.
2217 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2218 observer_wrapper(new rtc::RefCountedObject<
2219 CreateSessionDescriptionObserverOperationWrapper>(
2220 std::move(observer_refptr),
2221 std::move(operations_chain_callback)));
2222 this_weak_ptr->DoCreateOffer(options, observer_wrapper);
2223 });
2224}
2225
2226void PeerConnection::DoCreateOffer(
2227 const RTCOfferAnswerOptions& options,
2228 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2229 RTC_DCHECK_RUN_ON(signaling_thread());
2230 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002231
nisse7ce109a2017-01-31 00:57:56 -08002232 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002233 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002234 return;
2235 }
deadbeefab9b2d12015-10-14 11:33:11 -07002236
Steve Anton8d3444d2017-10-20 15:30:51 -07002237 if (IsClosed()) {
2238 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002239 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002240 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002241 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002242 return;
2243 }
2244
Steve Anton25ca0ac2019-06-25 10:40:48 -07002245 // If a session error has occurred the PeerConnection is in a possibly
2246 // inconsistent state so fail right away.
2247 if (session_error() != SessionError::kNone) {
2248 std::string error_message = GetSessionErrorMsg();
2249 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2250 PostCreateSessionDescriptionFailure(
2251 observer,
2252 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2253 return;
2254 }
2255
zhihuang1c378ed2017-08-17 14:10:50 -07002256 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002257 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002258 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002259 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002260 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002261 return;
2262 }
2263
Steve Anton22da89f2018-01-25 13:58:07 -08002264 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2265 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2266 if (IsUnifiedPlan()) {
2267 RTCError error = HandleLegacyOfferOptions(options);
2268 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002269 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002270 return;
2271 }
2272 }
2273
zhihuang1c378ed2017-08-17 14:10:50 -07002274 cricket::MediaSessionOptions session_options;
2275 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002276 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277}
2278
Steve Anton22da89f2018-01-25 13:58:07 -08002279RTCError PeerConnection::HandleLegacyOfferOptions(
2280 const RTCOfferAnswerOptions& options) {
2281 RTC_DCHECK(IsUnifiedPlan());
2282
2283 if (options.offer_to_receive_audio == 0) {
2284 RemoveRecvDirectionFromReceivingTransceiversOfType(
2285 cricket::MEDIA_TYPE_AUDIO);
2286 } else if (options.offer_to_receive_audio == 1) {
2287 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2288 } else if (options.offer_to_receive_audio > 1) {
2289 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2290 "offer_to_receive_audio > 1 is not supported.");
2291 }
2292
2293 if (options.offer_to_receive_video == 0) {
2294 RemoveRecvDirectionFromReceivingTransceiversOfType(
2295 cricket::MEDIA_TYPE_VIDEO);
2296 } else if (options.offer_to_receive_video == 1) {
2297 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2298 } else if (options.offer_to_receive_video > 1) {
2299 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2300 "offer_to_receive_video > 1 is not supported.");
2301 }
2302
2303 return RTCError::OK();
2304}
2305
2306void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2307 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002308 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002309 RtpTransceiverDirection new_direction =
2310 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2311 if (new_direction != transceiver->direction()) {
2312 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2313 << " transceiver (MID="
2314 << transceiver->mid().value_or("<not set>") << ") from "
2315 << RtpTransceiverDirectionToString(
2316 transceiver->direction())
2317 << " to "
2318 << RtpTransceiverDirectionToString(new_direction)
2319 << " since CreateOffer specified offer_to_receive=0";
2320 transceiver->internal()->set_direction(new_direction);
2321 }
Steve Anton22da89f2018-01-25 13:58:07 -08002322 }
2323}
2324
2325void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2326 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002327 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002328 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002329 RTC_LOG(LS_INFO)
2330 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2331 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002332 RtpTransceiverInit init;
2333 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002334 AddTransceiver(media_type, nullptr, init,
2335 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002336 }
2337}
2338
2339std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2340PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2341 std::vector<
2342 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2343 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002344 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002345 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002346 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2347 receiving_transceivers.push_back(transceiver);
2348 }
2349 }
2350 return receiving_transceivers;
2351}
2352
htaa2a49d92016-03-04 02:51:39 -08002353void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2354 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002355 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002356 // Chain this operation. If asynchronous operations are pending on the chain,
2357 // this operation will be queued to be invoked, otherwise the contents of the
2358 // lambda will execute immediately.
2359 operations_chain_->ChainOperation(
2360 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2361 observer_refptr =
2362 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2363 options](std::function<void()> operations_chain_callback) {
2364 // Abort early if |this_weak_ptr| is no longer valid.
2365 if (!this_weak_ptr) {
2366 observer_refptr->OnFailure(RTCError(
2367 RTCErrorType::INTERNAL_ERROR,
2368 "CreateAnswer failed because the session was shut down"));
2369 operations_chain_callback();
2370 return;
2371 }
2372 // The operation completes asynchronously when the wrapper is invoked.
2373 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2374 observer_wrapper(new rtc::RefCountedObject<
2375 CreateSessionDescriptionObserverOperationWrapper>(
2376 std::move(observer_refptr),
2377 std::move(operations_chain_callback)));
2378 this_weak_ptr->DoCreateAnswer(options, observer_wrapper);
2379 });
2380}
2381
2382void PeerConnection::DoCreateAnswer(
2383 const RTCOfferAnswerOptions& options,
2384 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2385 RTC_DCHECK_RUN_ON(signaling_thread());
2386 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002387 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002388 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002389 return;
2390 }
2391
Steve Anton25ca0ac2019-06-25 10:40:48 -07002392 // If a session error has occurred the PeerConnection is in a possibly
2393 // inconsistent state so fail right away.
2394 if (session_error() != SessionError::kNone) {
2395 std::string error_message = GetSessionErrorMsg();
2396 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2397 PostCreateSessionDescriptionFailure(
2398 observer,
2399 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2400 return;
2401 }
2402
Steve Antondffead82018-02-06 10:31:29 -08002403 if (!(signaling_state_ == kHaveRemoteOffer ||
2404 signaling_state_ == kHaveLocalPrAnswer)) {
2405 std::string error =
2406 "PeerConnection cannot create an answer in a state other than "
2407 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002408 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002409 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002410 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002411 return;
2412 }
2413
Steve Antondffead82018-02-06 10:31:29 -08002414 // The remote description should be set if we're in the right state.
2415 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002416
Steve Anton22da89f2018-01-25 13:58:07 -08002417 if (IsUnifiedPlan()) {
2418 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2419 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2420 "supported with Unified Plan semantics. Use the "
2421 "RtpTransceiver API instead.";
2422 }
2423 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2424 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2425 "supported with Unified Plan semantics. Use the "
2426 "RtpTransceiver API instead.";
2427 }
2428 }
2429
htaa2a49d92016-03-04 02:51:39 -08002430 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002431 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002432
Steve Antond25da372017-11-06 14:50:29 -08002433 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434}
2435
2436void PeerConnection::SetLocalDescription(
2437 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002438 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002439 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002440 // Chain this operation. If asynchronous operations are pending on the chain,
2441 // this operation will be queued to be invoked, otherwise the contents of the
2442 // lambda will execute immediately.
2443 operations_chain_->ChainOperation(
2444 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2445 observer_refptr =
2446 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2447 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2448 std::function<void()> operations_chain_callback) mutable {
2449 // Abort early if |this_weak_ptr| is no longer valid.
2450 if (!this_weak_ptr) {
2451 // For consistency with DoSetLocalDescription(), we DO NOT inform the
2452 // |observer_refptr| that the operation failed in this case.
2453 // TODO(hbos): If/when we process SLD messages in ~PeerConnection,
2454 // the consistent thing would be to inform the observer here.
2455 operations_chain_callback();
2456 return;
2457 }
2458 this_weak_ptr->DoSetLocalDescription(std::move(desc),
2459 std::move(observer_refptr));
2460 // DoSetLocalDescription() is currently implemented as a synchronous
2461 // operation but where the |observer|'s callbacks are invoked
2462 // asynchronously in a post to OnMessage().
2463 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 10:35:50 +01002464 // completed here (rather than in OnMessage()). This ensures that
2465 // subsequent offer/answer operations can start immediately (without
2466 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 12:09:49 +01002467 operations_chain_callback();
2468 });
2469}
Steve Anton8a006912017-12-04 15:25:56 -08002470
Henrik Boström4e196702019-10-30 10:35:50 +01002471void PeerConnection::SetLocalDescription(
2472 SetSessionDescriptionObserver* observer) {
2473 RTC_DCHECK_RUN_ON(signaling_thread());
2474 // The |create_sdp_observer| handles performing DoSetLocalDescription() with
2475 // the resulting description as well as completing the operation.
2476 rtc::scoped_refptr<ImplicitCreateSessionDescriptionObserver>
2477 create_sdp_observer(
2478 new rtc::RefCountedObject<ImplicitCreateSessionDescriptionObserver>(
2479 weak_ptr_factory_.GetWeakPtr(),
2480 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer)));
2481 // Chain this operation. If asynchronous operations are pending on the chain,
2482 // this operation will be queued to be invoked, otherwise the contents of the
2483 // lambda will execute immediately.
2484 operations_chain_->ChainOperation(
2485 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2486 create_sdp_observer](std::function<void()> operations_chain_callback) {
2487 // The |create_sdp_observer| is responsible for completing the
2488 // operation.
2489 create_sdp_observer->SetOperationCompleteCallback(
2490 std::move(operations_chain_callback));
2491 // Abort early if |this_weak_ptr| is no longer valid. This triggers the
2492 // same code path as if DoCreateOffer() or DoCreateAnswer() failed.
2493 if (!this_weak_ptr) {
2494 create_sdp_observer->OnFailure(RTCError(
2495 RTCErrorType::INTERNAL_ERROR,
2496 "SetLocalDescription failed because the session was shut down"));
2497 return;
2498 }
2499 switch (this_weak_ptr->signaling_state()) {
2500 case PeerConnectionInterface::kStable:
2501 case PeerConnectionInterface::kHaveLocalOffer:
2502 case PeerConnectionInterface::kHaveRemotePrAnswer:
2503 // TODO(hbos): If [LastCreatedOffer] exists and still represents the
2504 // current state of the system, use that instead of creating another
2505 // offer.
2506 this_weak_ptr->DoCreateOffer(RTCOfferAnswerOptions(),
2507 create_sdp_observer);
2508 break;
2509 case PeerConnectionInterface::kHaveLocalPrAnswer:
2510 case PeerConnectionInterface::kHaveRemoteOffer:
2511 // TODO(hbos): If [LastCreatedAnswer] exists and still represents
2512 // the current state of the system, use that instead of creating
2513 // another answer.
2514 this_weak_ptr->DoCreateAnswer(RTCOfferAnswerOptions(),
2515 create_sdp_observer);
2516 break;
2517 case PeerConnectionInterface::kClosed:
2518 create_sdp_observer->OnFailure(RTCError(
2519 RTCErrorType::INVALID_STATE,
2520 "SetLocalDescription called when PeerConnection is closed."));
2521 break;
2522 }
2523 });
2524}
2525
Henrik Boströma3728d32019-10-28 12:09:49 +01002526void PeerConnection::DoSetLocalDescription(
2527 std::unique_ptr<SessionDescriptionInterface> desc,
2528 rtc::scoped_refptr<SetSessionDescriptionObserver> observer) {
2529 RTC_DCHECK_RUN_ON(signaling_thread());
2530 TRACE_EVENT0("webrtc", "PeerConnection::DoSetLocalDescription");
Steve Anton80dd7b52018-02-16 17:08:42 -08002531
nisse7ce109a2017-01-31 00:57:56 -08002532 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002533 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534 return;
2535 }
Steve Anton8a006912017-12-04 15:25:56 -08002536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002538 PostSetSessionDescriptionFailure(
2539 observer,
2540 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002541 return;
2542 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002543
Steve Anton80dd7b52018-02-16 17:08:42 -08002544 // If a session error has occurred the PeerConnection is in a possibly
2545 // inconsistent state so fail right away.
2546 if (session_error() != SessionError::kNone) {
2547 std::string error_message = GetSessionErrorMsg();
2548 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002549 PostSetSessionDescriptionFailure(
2550 observer,
2551 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002552 return;
2553 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002554
Eldar Rello5ab79e62019-10-09 18:29:44 +03002555 // For SLD we support only explicit rollback.
2556 if (desc->GetType() == SdpType::kRollback) {
2557 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002558 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002559 if (error.ok()) {
2560 PostSetSessionDescriptionSuccess(observer);
2561 } else {
2562 PostSetSessionDescriptionFailure(observer, std::move(error));
2563 }
2564 } else {
2565 PostSetSessionDescriptionFailure(
2566 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2567 "Rollback not supported in Plan B"));
2568 }
2569 return;
2570 }
2571
Steve Anton80dd7b52018-02-16 17:08:42 -08002572 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2573 if (!error.ok()) {
2574 std::string error_message = GetSetDescriptionErrorMessage(
2575 cricket::CS_LOCAL, desc->GetType(), error);
2576 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002577 PostSetSessionDescriptionFailure(
2578 observer,
2579 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002580 return;
2581 }
2582
2583 // Grab the description type before moving ownership to ApplyLocalDescription,
2584 // which may destroy it before returning.
2585 const SdpType type = desc->GetType();
2586
2587 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002588 // |desc| may be destroyed at this point.
2589
2590 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002591 // If ApplyLocalDescription fails, the PeerConnection could be in an
2592 // inconsistent state, so act conservatively here and set the session error
2593 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2594 SetSessionError(SessionError::kContent, error.message());
2595 std::string error_message =
2596 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2597 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002598 PostSetSessionDescriptionFailure(
2599 observer,
2600 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002601 return;
2602 }
Steve Anton8a006912017-12-04 15:25:56 -08002603 RTC_DCHECK(local_description());
2604
2605 PostSetSessionDescriptionSuccess(observer);
2606
Steve Antonad182762018-09-05 20:22:40 +00002607 // MaybeStartGathering needs to be called after posting
2608 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2609 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002610 transport_controller_->MaybeStartGathering();
2611
Steve Antona3a92c22017-12-07 10:27:41 -08002612 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002613 // TODO(deadbeef): We already had to hop to the network thread for
2614 // MaybeStartGathering...
2615 network_thread()->Invoke<void>(
2616 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2617 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002618 // Make UMA notes about what was agreed to.
2619 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002620 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002621
2622 if (IsUnifiedPlan()) {
2623 bool was_negotiation_needed = is_negotiation_needed_;
2624 UpdateNegotiationNeeded();
2625 if (signaling_state() == kStable && was_negotiation_needed &&
2626 is_negotiation_needed_) {
2627 Observer()->OnRenegotiationNeeded();
2628 }
2629 }
2630
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002631 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002632}
2633
2634RTCError PeerConnection::ApplyLocalDescription(
2635 std::unique_ptr<SessionDescriptionInterface> desc) {
2636 RTC_DCHECK_RUN_ON(signaling_thread());
2637 RTC_DCHECK(desc);
2638
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002639 // Update stats here so that we have the most recent stats for tracks and
2640 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002641 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002642
Steve Antondcc3c022017-12-22 16:02:54 -08002643 // Take a reference to the old local description since it's used below to
2644 // compare against the new local description. When setting the new local
2645 // description, grab ownership of the replaced session description in case it
2646 // is the same as |old_local_description|, to keep it alive for the duration
2647 // of the method.
2648 const SessionDescriptionInterface* old_local_description =
2649 local_description();
2650 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002651 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002652 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002653 replaced_local_description = pending_local_description_
2654 ? std::move(pending_local_description_)
2655 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002656 current_local_description_ = std::move(desc);
2657 pending_local_description_ = nullptr;
2658 current_remote_description_ = std::move(pending_remote_description_);
2659 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002660 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002661 pending_local_description_ = std::move(desc);
2662 }
2663 // The session description to apply now must be accessed by
2664 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002665 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002666
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002667 // Report statistics about any use of simulcast.
2668 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2669 *local_description()->description());
2670
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002671 if (!is_caller_) {
2672 if (remote_description()) {
2673 // Remote description was applied first, so this PC is the callee.
2674 is_caller_ = false;
2675 } else {
2676 // Local description is applied first, so this PC is the caller.
2677 is_caller_ = true;
2678 }
2679 }
2680
Zhi Huange830e682018-03-30 10:48:35 -07002681 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2682 if (!error.ok()) {
2683 return error;
2684 }
2685
Steve Antondcc3c022017-12-22 16:02:54 -08002686 if (IsUnifiedPlan()) {
2687 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002688 cricket::CS_LOCAL, *local_description(), old_local_description,
2689 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002690 if (!error.ok()) {
2691 return error;
2692 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002693 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2694 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002695 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002696 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2697 // Note that code paths that don't set MID won't be able to use
2698 // information about DTLS transports.
2699 if (transceiver->mid()) {
2700 auto dtls_transport =
2701 LookupDtlsTransportByMidInternal(*transceiver->mid());
2702 transceiver->internal()->sender_internal()->set_transport(
2703 dtls_transport);
2704 transceiver->internal()->receiver_internal()->set_transport(
2705 dtls_transport);
2706 }
2707
Steve Antondcc3c022017-12-22 16:02:54 -08002708 const ContentInfo* content =
2709 FindMediaSectionForTransceiver(transceiver, local_description());
2710 if (!content) {
2711 continue;
2712 }
2713 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002714 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2715 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002716 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002717 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2718 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2719 // "recvonly", process the removal of a remote track for the media
2720 // description, given transceiver, removeList, and muteTracks.
2721 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2722 (transceiver->internal()->fired_direction() &&
2723 RtpTransceiverDirectionHasRecv(
2724 *transceiver->internal()->fired_direction()))) {
2725 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2726 &removed_streams);
2727 }
2728 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2729 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002730 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002731 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002732 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002733 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002734 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002735 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002736 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002737 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002738 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002739 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002740 }
2741 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002742 // Media channels will be created only when offer is set. These may use new
2743 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002744 if (type == SdpType::kOffer) {
2745 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2746 // description is applied. Restore back to old description.
2747 RTCError error = CreateChannels(*local_description()->description());
2748 if (!error.ok()) {
2749 return error;
2750 }
2751 }
Steve Antondcc3c022017-12-22 16:02:54 -08002752 // Remove unused channels if MediaContentDescription is rejected.
2753 RemoveUnusedChannels(local_description()->description());
2754 }
Steve Anton8a006912017-12-04 15:25:56 -08002755
Zhi Huange830e682018-03-30 10:48:35 -07002756 error = UpdateSessionState(type, cricket::CS_LOCAL,
2757 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002758 if (!error.ok()) {
2759 return error;
2760 }
Steve Antondcc3c022017-12-22 16:02:54 -08002761
Steve Anton8a006912017-12-04 15:25:56 -08002762 if (remote_description()) {
2763 // Now that we have a local description, we can push down remote candidates.
2764 UseCandidatesInSessionDescription(remote_description());
2765 }
2766
2767 pending_ice_restarts_.clear();
2768 if (session_error() != SessionError::kNone) {
2769 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2770 }
2771
deadbeefab9b2d12015-10-14 11:33:11 -07002772 // If setting the description decided our SSL role, allocate any necessary
2773 // SCTP sids.
2774 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002775 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002776 AllocateSctpSids(role);
2777 }
2778
Steve Antond3679212018-01-17 17:41:02 -08002779 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002780 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002781 const ContentInfo* content =
2782 FindMediaSectionForTransceiver(transceiver, local_description());
2783 if (!content) {
2784 continue;
2785 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002786 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2787 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002788 // 0 is a special value meaning "this sender has no associated send
2789 // stream". Need to call this so the sender won't attempt to configure
2790 // a no longer existing stream and run into DCHECKs in the lower
2791 // layers.
2792 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002793 } else {
2794 // Get the StreamParams from the channel which could generate SSRCs.
2795 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002796 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002797 streams[0].stream_ids());
2798 transceiver->internal()->sender_internal()->SetSsrc(
2799 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002800 }
2801 }
2802 } else {
2803 // Plan B semantics.
2804
Steve Antondcc3c022017-12-22 16:02:54 -08002805 // Update state and SSRC of local MediaStreams and DataChannels based on the
2806 // local session description.
2807 const cricket::ContentInfo* audio_content =
2808 GetFirstAudioContent(local_description()->description());
2809 if (audio_content) {
2810 if (audio_content->rejected) {
2811 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2812 } else {
2813 const cricket::AudioContentDescription* audio_desc =
2814 audio_content->media_description()->as_audio();
2815 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2816 }
deadbeeffaac4972015-11-12 15:33:07 -08002817 }
deadbeefab9b2d12015-10-14 11:33:11 -07002818
Steve Antondcc3c022017-12-22 16:02:54 -08002819 const cricket::ContentInfo* video_content =
2820 GetFirstVideoContent(local_description()->description());
2821 if (video_content) {
2822 if (video_content->rejected) {
2823 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2824 } else {
2825 const cricket::VideoContentDescription* video_desc =
2826 video_content->media_description()->as_video();
2827 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2828 }
deadbeeffaac4972015-11-12 15:33:07 -08002829 }
deadbeefab9b2d12015-10-14 11:33:11 -07002830 }
2831
2832 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002833 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002834 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002835 const cricket::RtpDataContentDescription* rtp_data_desc =
2836 data_content->media_description()->as_rtp_data();
2837 // rtp_data_desc will be null if this is an SCTP description.
2838 if (rtp_data_desc) {
2839 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002840 }
2841 }
2842
Henrik Boström79b69802019-07-18 11:16:56 +02002843 if (type == SdpType::kAnswer &&
2844 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2845 *current_local_description_)) {
2846 local_ice_credentials_to_replace_->ClearIceCredentials();
2847 }
2848
Steve Anton8a006912017-12-04 15:25:56 -08002849 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850}
2851
Steve Anton06817cd2018-12-18 15:55:30 -08002852// The SDP parser used to populate these values by default for the 'content
2853// name' if an a=mid line was absent.
2854static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2855 switch (media_type) {
2856 case cricket::MEDIA_TYPE_AUDIO:
2857 return cricket::CN_AUDIO;
2858 case cricket::MEDIA_TYPE_VIDEO:
2859 return cricket::CN_VIDEO;
2860 case cricket::MEDIA_TYPE_DATA:
2861 return cricket::CN_DATA;
2862 }
2863 RTC_NOTREACHED();
2864 return "";
2865}
2866
2867void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002868 cricket::SessionDescription* new_remote_description) {
2869 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002870 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002871 const cricket::ContentInfos& local_contents =
2872 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002873 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002874 const cricket::ContentInfos& remote_contents =
2875 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002876 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002877 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2878 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002879 if (!content.name.empty()) {
2880 continue;
2881 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002882 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002883 absl::string_view source_explanation;
2884 if (IsUnifiedPlan()) {
2885 if (i < local_contents.size()) {
2886 new_mid = local_contents[i].name;
2887 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002888 } else if (i < remote_contents.size()) {
2889 new_mid = remote_contents[i].name;
2890 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002891 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002892 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002893 source_explanation = "generated just now";
2894 }
2895 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002896 new_mid = std::string(
2897 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002898 source_explanation = "to match pre-existing behavior";
2899 }
Steve Antond7180cc2019-02-07 10:44:53 -08002900 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002901 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002902 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002903 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2904 << " is missing an a=mid line. Filling in the value '"
2905 << new_mid << "' " << source_explanation << ".";
2906 }
2907}
2908
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002910 SetSessionDescriptionObserver* observer,
Henrik Boströma3728d32019-10-28 12:09:49 +01002911 SessionDescriptionInterface* desc_ptr) {
2912 RTC_DCHECK_RUN_ON(signaling_thread());
2913 // Chain this operation. If asynchronous operations are pending on the chain,
2914 // this operation will be queued to be invoked, otherwise the contents of the
2915 // lambda will execute immediately.
2916 operations_chain_->ChainOperation(
2917 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2918 observer_refptr =
2919 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2920 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2921 std::function<void()> operations_chain_callback) mutable {
2922 // Abort early if |this_weak_ptr| is no longer valid.
2923 if (!this_weak_ptr) {
2924 // For consistency with SetRemoteDescriptionObserverAdapter, we DO NOT
2925 // inform the |observer_refptr| that the operation failed in this
2926 // case.
2927 // TODO(hbos): If/when we process SRD messages in ~PeerConnection,
2928 // the consistent thing would be to inform the observer here.
2929 operations_chain_callback();
2930 return;
2931 }
2932 this_weak_ptr->DoSetRemoteDescription(
2933 std::move(desc),
2934 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2935 new SetRemoteDescriptionObserverAdapter(
2936 this_weak_ptr.get(), std::move(observer_refptr))));
2937 // DoSetRemoteDescription() is currently implemented as a synchronous
2938 // operation but where SetRemoteDescriptionObserverAdapter ensures that
2939 // the |observer|'s callbacks are invoked asynchronously in a post to
2940 // OnMessage().
2941 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 10:35:50 +01002942 // completed here (rather than in OnMessage()). This ensures that
2943 // subsequent offer/answer operations can start immediately (without
2944 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 12:09:49 +01002945 operations_chain_callback();
2946 });
Henrik Boström31638672017-11-23 17:48:32 +01002947}
2948
2949void PeerConnection::SetRemoteDescription(
2950 std::unique_ptr<SessionDescriptionInterface> desc,
2951 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002952 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002953 // Chain this operation. If asynchronous operations are pending on the chain,
2954 // this operation will be queued to be invoked, otherwise the contents of the
2955 // lambda will execute immediately.
2956 operations_chain_->ChainOperation(
2957 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer,
2958 desc = std::move(desc)](
2959 std::function<void()> operations_chain_callback) mutable {
2960 // Abort early if |this_weak_ptr| is no longer valid.
2961 if (!this_weak_ptr) {
2962 // For consistency with DoSetRemoteDescription(), we DO inform the
2963 // |observer| that the operation failed in this case.
2964 observer->OnSetRemoteDescriptionComplete(RTCError(
2965 RTCErrorType::INVALID_STATE,
2966 "Failed to set remote offer sdp: failed because the session was "
2967 "shut down"));
2968 operations_chain_callback();
2969 return;
2970 }
2971 this_weak_ptr->DoSetRemoteDescription(std::move(desc),
2972 std::move(observer));
2973 // DoSetRemoteDescription() is currently implemented as a synchronous
2974 // operation. The |observer| will already have been informed that it
2975 // completed, and we can mark this operation as complete without any
2976 // loose ends.
2977 operations_chain_callback();
2978 });
2979}
2980
2981void PeerConnection::DoSetRemoteDescription(
2982 std::unique_ptr<SessionDescriptionInterface> desc,
2983 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
2984 RTC_DCHECK_RUN_ON(signaling_thread());
2985 TRACE_EVENT0("webrtc", "PeerConnection::DoSetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002986
nisse7ce109a2017-01-31 00:57:56 -08002987 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002988 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002989 return;
2990 }
Steve Anton8a006912017-12-04 15:25:56 -08002991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002993 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002994 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 return;
2996 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002997
Steve Anton80dd7b52018-02-16 17:08:42 -08002998 // If a session error has occurred the PeerConnection is in a possibly
2999 // inconsistent state so fail right away.
3000 if (session_error() != SessionError::kNone) {
3001 std::string error_message = GetSessionErrorMsg();
3002 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
3003 observer->OnSetRemoteDescriptionComplete(
3004 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
3005 return;
3006 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003007 if (IsUnifiedPlan()) {
3008 if (configuration_.enable_implicit_rollback) {
3009 if (desc->GetType() == SdpType::kOffer &&
3010 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 23:01:31 +03003011 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03003012 }
3013 }
3014 // Explicit rollback.
3015 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 23:01:31 +03003016 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 18:29:44 +03003017 return;
3018 }
3019 } else if (desc->GetType() == SdpType::kRollback) {
3020 observer->OnSetRemoteDescriptionComplete(
3021 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
3022 "Rollback not supported in Plan B"));
3023 return;
3024 }
Steve Antonba42e992018-04-09 14:10:01 -07003025 if (desc->GetType() == SdpType::kOffer) {
3026 // Report to UMA the format of the received offer.
3027 ReportSdpFormatReceived(*desc);
3028 }
3029
Steve Anton06817cd2018-12-18 15:55:30 -08003030 // Handle remote descriptions missing a=mid lines for interop with legacy end
3031 // points.
3032 FillInMissingRemoteMids(desc->description());
3033
Steve Anton80dd7b52018-02-16 17:08:42 -08003034 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08003035 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08003036 std::string error_message = GetSetDescriptionErrorMessage(
3037 cricket::CS_REMOTE, desc->GetType(), error);
3038 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08003039 observer->OnSetRemoteDescriptionComplete(
3040 RTCError(error.type(), std::move(error_message)));
3041 return;
3042 }
Steve Anton71439a62018-02-15 11:53:06 -08003043
Steve Anton80dd7b52018-02-16 17:08:42 -08003044 // Grab the description type before moving ownership to
3045 // ApplyRemoteDescription, which may destroy it before returning.
3046 const SdpType type = desc->GetType();
3047
3048 error = ApplyRemoteDescription(std::move(desc));
3049 // |desc| may be destroyed at this point.
3050
3051 if (!error.ok()) {
3052 // If ApplyRemoteDescription fails, the PeerConnection could be in an
3053 // inconsistent state, so act conservatively here and set the session error
3054 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
3055 SetSessionError(SessionError::kContent, error.message());
3056 std::string error_message =
3057 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
3058 RTC_LOG(LS_ERROR) << error_message;
3059 observer->OnSetRemoteDescriptionComplete(
3060 RTCError(error.type(), std::move(error_message)));
3061 return;
3062 }
3063 RTC_DCHECK(remote_description());
3064
3065 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08003066 // TODO(deadbeef): We already had to hop to the network thread for
3067 // MaybeStartGathering...
3068 network_thread()->Invoke<void>(
3069 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3070 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01003071 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08003072 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08003073 }
3074
Guido Urdaneta70c2db12019-04-16 12:24:14 +02003075 if (IsUnifiedPlan()) {
3076 bool was_negotiation_needed = is_negotiation_needed_;
3077 UpdateNegotiationNeeded();
3078 if (signaling_state() == kStable && was_negotiation_needed &&
3079 is_negotiation_needed_) {
3080 Observer()->OnRenegotiationNeeded();
3081 }
3082 }
3083
Steve Anton8a006912017-12-04 15:25:56 -08003084 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003085 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08003086}
3087
3088RTCError PeerConnection::ApplyRemoteDescription(
3089 std::unique_ptr<SessionDescriptionInterface> desc) {
3090 RTC_DCHECK_RUN_ON(signaling_thread());
3091 RTC_DCHECK(desc);
3092
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003093 // Update stats here so that we have the most recent stats for tracks and
3094 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003095 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08003096
Steve Antondcc3c022017-12-22 16:02:54 -08003097 // Take a reference to the old remote description since it's used below to
3098 // compare against the new remote description. When setting the new remote
3099 // description, grab ownership of the replaced session description in case it
3100 // is the same as |old_remote_description|, to keep it alive for the duration
3101 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08003102 const SessionDescriptionInterface* old_remote_description =
3103 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08003104 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08003105 SdpType type = desc->GetType();
3106 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08003107 replaced_remote_description = pending_remote_description_
3108 ? std::move(pending_remote_description_)
3109 : std::move(current_remote_description_);
3110 current_remote_description_ = std::move(desc);
3111 pending_remote_description_ = nullptr;
3112 current_local_description_ = std::move(pending_local_description_);
3113 } else {
3114 replaced_remote_description = std::move(pending_remote_description_);
3115 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116 }
Steve Anton8a006912017-12-04 15:25:56 -08003117 // The session description to apply now must be accessed by
3118 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01003119 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003120
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003121 // Report statistics about any use of simulcast.
3122 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
3123 *remote_description()->description());
3124
Zhi Huange830e682018-03-30 10:48:35 -07003125 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
3126 if (!error.ok()) {
3127 return error;
3128 }
Steve Anton8a006912017-12-04 15:25:56 -08003129 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08003130 if (IsUnifiedPlan()) {
3131 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003132 cricket::CS_REMOTE, *remote_description(), local_description(),
3133 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08003134 if (!error.ok()) {
3135 return error;
3136 }
Steve Antondcc3c022017-12-22 16:02:54 -08003137 } else {
Zhi Huange830e682018-03-30 10:48:35 -07003138 // Media channels will be created only when offer is set. These may use new
3139 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08003140 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07003141 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08003142 // description is applied. Restore back to old description.
3143 RTCError error = CreateChannels(*remote_description()->description());
3144 if (!error.ok()) {
3145 return error;
3146 }
3147 }
Steve Antondcc3c022017-12-22 16:02:54 -08003148 // Remove unused channels if MediaContentDescription is rejected.
3149 RemoveUnusedChannels(remote_description()->description());
3150 }
Steve Anton8a006912017-12-04 15:25:56 -08003151
Zhi Huange830e682018-03-30 10:48:35 -07003152 // NOTE: Candidates allocation will be initiated only when
3153 // SetLocalDescription is called.
3154 error = UpdateSessionState(type, cricket::CS_REMOTE,
3155 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08003156 if (!error.ok()) {
3157 return error;
3158 }
3159
3160 if (local_description() &&
3161 !UseCandidatesInSessionDescription(remote_description())) {
3162 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
3163 }
3164
3165 if (old_remote_description) {
3166 for (const cricket::ContentInfo& content :
3167 old_remote_description->description()->contents()) {
3168 // Check if this new SessionDescription contains new ICE ufrag and
3169 // password that indicates the remote peer requests an ICE restart.
3170 // TODO(deadbeef): When we start storing both the current and pending
3171 // remote description, this should reset pending_ice_restarts and compare
3172 // against the current description.
3173 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3174 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08003175 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08003176 pending_ice_restarts_.insert(content.name);
3177 }
3178 } else {
3179 // We retain all received candidates only if ICE is not restarted.
3180 // When ICE is restarted, all previous candidates belong to an old
3181 // generation and should not be kept.
3182 // TODO(deadbeef): This goes against the W3C spec which says the remote
3183 // description should only contain candidates from the last set remote
3184 // description plus any candidates added since then. We should remove
3185 // this once we're sure it won't break anything.
3186 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3187 old_remote_description, content.name, mutable_remote_description());
3188 }
3189 }
3190 }
3191
3192 if (session_error() != SessionError::kNone) {
3193 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3194 }
3195
3196 // Set the the ICE connection state to connecting since the connection may
3197 // become writable with peer reflexive candidates before any remote candidate
3198 // is signaled.
3199 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3200 // is to have a new signal the indicates a change in checking state from the
3201 // transport and expose a new checking() member from transport that can be
3202 // read to determine the current checking state. The existing SignalConnecting
3203 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08003204 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07003205 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08003206 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3207 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3208 }
3209
deadbeefab9b2d12015-10-14 11:33:11 -07003210 // If setting the description decided our SSL role, allocate any necessary
3211 // SCTP sids.
3212 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003213 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07003214 AllocateSctpSids(role);
3215 }
3216
Steve Antondcc3c022017-12-22 16:02:54 -08003217 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08003218 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07003219 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07003220 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08003221 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07003222 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01003223 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08003224 const ContentInfo* content =
3225 FindMediaSectionForTransceiver(transceiver, remote_description());
3226 if (!content) {
3227 continue;
3228 }
3229 const MediaContentDescription* media_desc = content->media_description();
3230 RtpTransceiverDirection local_direction =
3231 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003232 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
3233 // RTCSessionDescription: Set the associated remote streams given
3234 // transceiver.[[Receiver]], msids, addList, and removeList".
3235 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
3236 if (RtpTransceiverDirectionHasRecv(local_direction)) {
3237 std::vector<std::string> stream_ids;
3238 if (!media_desc->streams().empty()) {
3239 // The remote description has signaled the stream IDs.
3240 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08003241 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003242 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
3243 << " (" << GetStreamIdsString(stream_ids) << ").";
3244 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
3245 stream_ids, &added_streams,
3246 &removed_streams);
3247 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
3248 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
3249 // and transceiver's current direction is neither sendrecv nor recvonly,
3250 // process the addition of a remote track for the media description.
3251 if (!transceiver->fired_direction() ||
3252 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
3253 RTC_LOG(LS_INFO)
3254 << "Processing the addition of a remote track for MID="
3255 << content->name << ".";
3256 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01003257 }
Steve Antondcc3c022017-12-22 16:02:54 -08003258 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003259 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07003260 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
3261 // removal of a remote track for the media description, given transceiver,
3262 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08003263 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07003264 (transceiver->fired_direction() &&
3265 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
3266 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
3267 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08003268 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003269 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07003270 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003271 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07003272 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08003273 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003274 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07003275 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08003276 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003277 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
3278 if (transceiver->mid()) {
3279 auto dtls_transport =
3280 LookupDtlsTransportByMidInternal(*transceiver->mid());
3281 transceiver->internal()->sender_internal()->set_transport(
3282 dtls_transport);
3283 transceiver->internal()->receiver_internal()->set_transport(
3284 dtls_transport);
3285 }
Steve Antondcc3c022017-12-22 16:02:54 -08003286 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003287 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07003288 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08003289 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07003290 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
3291 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08003292 transceiver->Stop();
3293 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003294 if (!content->rejected &&
3295 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07003296 if (!media_desc->streams().empty() &&
3297 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07003298 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
3299 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
3300 } else {
3301 transceiver->internal()
3302 ->receiver_internal()
3303 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08003304 }
Steve Antond3679212018-01-17 17:41:02 -08003305 }
Steve Antondcc3c022017-12-22 16:02:54 -08003306 }
Steve Antonc49bcd92018-02-14 14:28:13 -08003307 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003308 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01003309 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08003310 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003311 observer->OnTrack(transceiver);
3312 observer->OnAddTrack(transceiver->receiver(),
3313 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08003314 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003315 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003316 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08003317 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003318 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003319 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07003320 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003321 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003322 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07003323 }
Steve Antondcc3c022017-12-22 16:02:54 -08003324 }
3325
Henrik Boströmfdb92012017-11-09 19:55:44 +01003326 const cricket::ContentInfo* audio_content =
3327 GetFirstAudioContent(remote_description()->description());
3328 const cricket::ContentInfo* video_content =
3329 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003330 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003331 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003332 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003333 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003334 const cricket::RtpDataContentDescription* rtp_data_desc =
3335 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003336
3337 // Check if the descriptions include streams, just in case the peer supports
3338 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01003339 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08003340 (audio_desc && !audio_desc->streams().empty()) ||
3341 (video_desc && !video_desc->streams().empty())) {
3342 remote_peer_supports_msid_ = true;
3343 }
deadbeefab9b2d12015-10-14 11:33:11 -07003344
3345 // We wait to signal new streams until we finish processing the description,
3346 // since only at that point will new streams have all their tracks.
3347 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
3348
Steve Antondcc3c022017-12-22 16:02:54 -08003349 if (!IsUnifiedPlan()) {
3350 // TODO(steveanton): When removing RTP senders/receivers in response to a
3351 // rejected media section, there is some cleanup logic that expects the
3352 // voice/ video channel to still be set. But in this method the voice/video
3353 // channel would have been destroyed by the SetRemoteDescription caller
3354 // above so the cleanup that relies on them fails to run. The RemoveSenders
3355 // calls should be moved to right before the DestroyChannel calls to fix
3356 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07003357
Steve Antondcc3c022017-12-22 16:02:54 -08003358 // Find all audio rtp streams and create corresponding remote AudioTracks
3359 // and MediaStreams.
3360 if (audio_content) {
3361 if (audio_content->rejected) {
3362 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3363 } else {
3364 bool default_audio_track_needed =
3365 !remote_peer_supports_msid_ &&
3366 RtpTransceiverDirectionHasSend(audio_desc->direction());
3367 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3368 default_audio_track_needed, audio_desc->type(),
3369 new_streams);
3370 }
deadbeeffaac4972015-11-12 15:33:07 -08003371 }
deadbeefab9b2d12015-10-14 11:33:11 -07003372
Steve Antondcc3c022017-12-22 16:02:54 -08003373 // Find all video rtp streams and create corresponding remote VideoTracks
3374 // and MediaStreams.
3375 if (video_content) {
3376 if (video_content->rejected) {
3377 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3378 } else {
3379 bool default_video_track_needed =
3380 !remote_peer_supports_msid_ &&
3381 RtpTransceiverDirectionHasSend(video_desc->direction());
3382 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3383 default_video_track_needed, video_desc->type(),
3384 new_streams);
3385 }
deadbeeffaac4972015-11-12 15:33:07 -08003386 }
deadbeefab9b2d12015-10-14 11:33:11 -07003387
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003388 // If this is an RTP data transport, update the DataChannels with the
3389 // information from the remote peer.
3390 if (rtp_data_desc) {
3391 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003392 }
deadbeefab9b2d12015-10-14 11:33:11 -07003393
Steve Antondcc3c022017-12-22 16:02:54 -08003394 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003395 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003396 for (size_t i = 0; i < new_streams->count(); ++i) {
3397 MediaStreamInterface* new_stream = new_streams->at(i);
3398 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003399 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003400 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3401 }
deadbeefab9b2d12015-10-14 11:33:11 -07003402
Steve Antondcc3c022017-12-22 16:02:54 -08003403 UpdateEndedRemoteMediaStreams();
3404 }
deadbeefab9b2d12015-10-14 11:33:11 -07003405
Henrik Boström79b69802019-07-18 11:16:56 +02003406 if (type == SdpType::kAnswer &&
3407 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3408 *current_local_description_)) {
3409 local_ice_credentials_to_replace_->ClearIceCredentials();
3410 }
3411
Steve Anton8a006912017-12-04 15:25:56 -08003412 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003413}
3414
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003415void PeerConnection::SetAssociatedRemoteStreams(
3416 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3417 const std::vector<std::string>& stream_ids,
3418 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3419 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3420 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3421 for (const std::string& stream_id : stream_ids) {
3422 rtc::scoped_refptr<MediaStreamInterface> stream =
3423 remote_streams_->find(stream_id);
3424 if (!stream) {
3425 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3426 MediaStream::Create(stream_id));
3427 remote_streams_->AddStream(stream);
3428 added_streams->push_back(stream);
3429 }
3430 media_streams.push_back(stream);
3431 }
3432 // Special case: "a=msid" missing, use random stream ID.
3433 if (media_streams.empty() &&
3434 !(remote_description()->description()->msid_signaling() &
3435 cricket::kMsidSignalingMediaSection)) {
3436 if (!missing_msid_default_stream_) {
3437 missing_msid_default_stream_ = MediaStreamProxy::Create(
3438 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3439 added_streams->push_back(missing_msid_default_stream_);
3440 }
3441 media_streams.push_back(missing_msid_default_stream_);
3442 }
3443 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3444 receiver->streams();
3445 // SetStreams() will add/remove the receiver's track to/from the streams. This
3446 // differs from the spec - the spec uses an "addList" and "removeList" to
3447 // update the stream-track relationships in a later step. We do this earlier,
3448 // changing the order of things, but the end-result is the same.
3449 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3450 // instead. https://crbug.com/webrtc/9480
3451 receiver->SetStreams(media_streams);
3452 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3453}
3454
Steve Anton0f5400a2018-07-17 14:25:36 -07003455void PeerConnection::ProcessRemovalOfRemoteTrack(
3456 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3457 transceiver,
3458 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3459 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3460 RTC_DCHECK(transceiver->mid());
3461 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3462 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003463 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003464 transceiver->internal()->receiver_internal()->streams();
3465 // This will remove the remote track from the streams.
3466 transceiver->internal()->receiver_internal()->set_stream_ids({});
3467 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003468 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3469}
3470
3471void PeerConnection::RemoveRemoteStreamsIfEmpty(
3472 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3473 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3474 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3475 // streams, see if the stream was removed by checking if this was the last
3476 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003477 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003478 if (remote_stream->GetAudioTracks().empty() &&
3479 remote_stream->GetVideoTracks().empty()) {
3480 remote_streams_->RemoveStream(remote_stream);
3481 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003482 }
3483 }
3484}
3485
Steve Antondcc3c022017-12-22 16:02:54 -08003486RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3487 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003488 const SessionDescriptionInterface& new_session,
3489 const SessionDescriptionInterface* old_local_description,
3490 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003491 RTC_DCHECK(IsUnifiedPlan());
3492
Steve Anton7464fca2018-01-19 11:10:37 -08003493 const cricket::ContentGroup* bundle_group = nullptr;
3494 if (new_session.GetType() == SdpType::kOffer) {
3495 auto bundle_group_or_error =
3496 GetEarlyBundleGroup(*new_session.description());
3497 if (!bundle_group_or_error.ok()) {
3498 return bundle_group_or_error.MoveError();
3499 }
3500 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003501 }
Steve Antondcc3c022017-12-22 16:02:54 -08003502
Steve Antondcc3c022017-12-22 16:02:54 -08003503 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003504 for (size_t i = 0; i < new_contents.size(); ++i) {
3505 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003506 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003507 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003508 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3509 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003510 const cricket::ContentInfo* old_local_content = nullptr;
3511 if (old_local_description &&
3512 i < old_local_description->description()->contents().size()) {
3513 old_local_content =
3514 &old_local_description->description()->contents()[i];
3515 }
3516 const cricket::ContentInfo* old_remote_content = nullptr;
3517 if (old_remote_description &&
3518 i < old_remote_description->description()->contents().size()) {
3519 old_remote_content =
3520 &old_remote_description->description()->contents()[i];
3521 }
Steve Antondcc3c022017-12-22 16:02:54 -08003522 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003523 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3524 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003525 if (!transceiver_or_error.ok()) {
3526 return transceiver_or_error.MoveError();
3527 }
3528 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003529 RTCError error =
3530 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3531 if (!error.ok()) {
3532 return error;
3533 }
3534 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003535 if (GetDataMid() && new_content.name != *GetDataMid()) {
3536 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003537 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3538 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003539 continue;
3540 }
3541 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3542 if (!error.ok()) {
3543 return error;
3544 }
Steve Antondcc3c022017-12-22 16:02:54 -08003545 } else {
3546 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3547 "Unknown section type.");
3548 }
3549 }
3550
3551 return RTCError::OK();
3552}
3553
3554RTCError PeerConnection::UpdateTransceiverChannel(
3555 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3556 transceiver,
3557 const cricket::ContentInfo& content,
3558 const cricket::ContentGroup* bundle_group) {
3559 RTC_DCHECK(IsUnifiedPlan());
3560 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003561 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003562 if (content.rejected) {
3563 if (channel) {
3564 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003565 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003566 }
3567 } else {
3568 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003569 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003570 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003571 } else {
Steve Anton69470252018-02-09 11:43:08 -08003572 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003573 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003574 }
3575 if (!channel) {
3576 LOG_AND_RETURN_ERROR(
3577 RTCErrorType::INTERNAL_ERROR,
3578 "Failed to create channel for mid=" + content.name);
3579 }
3580 transceiver->internal()->SetChannel(channel);
3581 }
3582 }
3583 return RTCError::OK();
3584}
3585
Steve Antonfa2260d2017-12-28 16:38:23 -08003586RTCError PeerConnection::UpdateDataChannel(
3587 cricket::ContentSource source,
3588 const cricket::ContentInfo& content,
3589 const cricket::ContentGroup* bundle_group) {
3590 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003591 // If data channels are disabled, ignore this media section. CreateAnswer
3592 // will take care of rejecting it.
3593 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003594 }
3595 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003596 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003597 DestroyDataChannel();
3598 } else {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07003599 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003600 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003601 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003602 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3603 "Failed to create data channel.");
3604 }
3605 }
3606 if (source == cricket::CS_REMOTE) {
3607 const MediaContentDescription* data_desc = content.media_description();
3608 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3609 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3610 }
3611 }
3612 }
3613 return RTCError::OK();
3614}
3615
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003616// This method will extract any send encodings that were sent by the remote
3617// connection. This is currently only relevant for Simulcast scenario (where
3618// the number of layers may be communicated by the server).
3619static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3620 const MediaContentDescription& desc) {
3621 if (!desc.HasSimulcast()) {
3622 return {};
3623 }
3624 std::vector<RtpEncodingParameters> result;
3625 const SimulcastDescription& simulcast = desc.simulcast_description();
3626
3627 // This is a remote description, the parameters we are after should appear
3628 // as receive streams.
3629 for (const auto& alternatives : simulcast.receive_layers()) {
3630 RTC_DCHECK(!alternatives.empty());
3631 // There is currently no way to specify or choose from alternatives.
3632 // We will always use the first alternative, which is the most preferred.
3633 const SimulcastLayer& layer = alternatives[0];
3634 RtpEncodingParameters parameters;
3635 parameters.rid = layer.rid;
3636 parameters.active = !layer.is_paused;
3637 result.push_back(parameters);
3638 }
3639
3640 return result;
3641}
3642
3643static RTCError UpdateSimulcastLayerStatusInSender(
3644 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003645 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003646 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003647 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003648 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003649
3650 // The simulcast envelope cannot be changed, only the status of the streams.
3651 // So we will iterate over the send encodings rather than the layers.
3652 for (RtpEncodingParameters& encoding : parameters.encodings) {
3653 auto iter = std::find_if(layers.begin(), layers.end(),
3654 [&encoding](const SimulcastLayer& layer) {
3655 return layer.rid == encoding.rid;
3656 });
3657 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003658 if (iter == layers.end()) {
3659 disabled_layers.push_back(encoding.rid);
3660 continue;
3661 }
3662
3663 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003664 }
3665
Amit Hilbuch619b2942019-02-26 15:55:19 -08003666 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003667 if (result.ok()) {
3668 result = sender->DisableEncodingLayers(disabled_layers);
3669 }
3670
3671 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003672}
3673
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003674static bool SimulcastIsRejected(
3675 const ContentInfo* local_content,
3676 const MediaContentDescription& answer_media_desc) {
3677 bool simulcast_offered = local_content &&
3678 local_content->media_description() &&
3679 local_content->media_description()->HasSimulcast();
3680 bool simulcast_answered = answer_media_desc.HasSimulcast();
3681 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3682 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3683 return simulcast_offered && (!simulcast_answered || !rids_supported);
3684}
3685
Amit Hilbuch2297d332019-02-19 12:49:22 -08003686static RTCError DisableSimulcastInSender(
3687 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003688 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003689 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003690 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003691 return RTCError::OK();
3692 }
3693
Amit Hilbuch2297d332019-02-19 12:49:22 -08003694 std::vector<std::string> disabled_layers;
3695 std::transform(
3696 parameters.encodings.begin() + 1, parameters.encodings.end(),
3697 std::back_inserter(disabled_layers),
3698 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3699 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003700}
3701
Steve Antondcc3c022017-12-22 16:02:54 -08003702RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3703PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003704 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003705 size_t mline_index,
3706 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003707 const ContentInfo* old_local_content,
3708 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003709 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003710 // If this is an offer then the m= section might be recycled. If the m=
3711 // section is being recycled (defined as: rejected in the current local or
3712 // remote description and not rejected in new description), dissociate the
3713 // currently associated RtpTransceiver by setting its mid property to null,
3714 // and discard the mapping between the transceiver and its m= section index.
3715 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3716 old_remote_content)) {
3717 // We want to dissociate the transceiver that has the rejected mid.
3718 const std::string& old_mid =
3719 (old_local_content && old_local_content->rejected)
3720 ? old_local_content->name
3721 : old_remote_content->name;
3722 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003723 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003724 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3725 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003726 old_transceiver->internal()->set_mid(absl::nullopt);
3727 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003728 }
3729 }
3730 const MediaContentDescription* media_desc = content.media_description();
3731 auto transceiver = GetAssociatedTransceiver(content.name);
3732 if (source == cricket::CS_LOCAL) {
3733 // Find the RtpTransceiver that corresponds to this m= section, using the
3734 // mapping between transceivers and m= section indices established when
3735 // creating the offer.
3736 if (!transceiver) {
3737 transceiver = GetTransceiverByMLineIndex(mline_index);
3738 }
3739 if (!transceiver) {
3740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3741 "Unknown transceiver");
3742 }
3743 } else {
3744 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3745 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3746 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003747 // When simulcast is requested, a transceiver cannot be associated because
3748 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003749 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003750 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3751 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003752 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3753 }
3754 // If no RtpTransceiver was found in the previous step, create one with a
3755 // recvonly direction.
3756 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003757 RTC_LOG(LS_INFO) << "Adding "
3758 << cricket::MediaTypeToString(media_desc->type())
3759 << " transceiver for MID=" << content.name
3760 << " at i=" << mline_index
3761 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003762 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003763 std::vector<RtpEncodingParameters> send_encodings =
3764 GetSendEncodingsFromRemoteDescription(*media_desc);
3765 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3766 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003767 std::string receiver_id;
3768 if (!media_desc->streams().empty()) {
3769 receiver_id = media_desc->streams()[0].id;
3770 } else {
3771 receiver_id = rtc::CreateRandomUuid();
3772 }
3773 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003774 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003775 transceiver->internal()->set_direction(
3776 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 18:29:44 +03003777 if (type == SdpType::kOffer) {
3778 transceiver_stable_states_by_transceivers_[transceiver] =
3779 TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
3780 absl::nullopt, absl::nullopt, true);
3781 }
Steve Antondcc3c022017-12-22 16:02:54 -08003782 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003783 // Check if the offer indicated simulcast but the answer rejected it.
3784 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003785 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003786 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003787 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003788 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003789 if (!error.ok()) {
3790 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3791 return std::move(error);
3792 }
3793 }
Steve Antondcc3c022017-12-22 16:02:54 -08003794 }
3795 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003796 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003797 LOG_AND_RETURN_ERROR(
3798 RTCErrorType::INVALID_PARAMETER,
3799 "Transceiver type does not match media description type.");
3800 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003801 if (media_desc->HasSimulcast()) {
3802 std::vector<SimulcastLayer> layers =
3803 source == cricket::CS_LOCAL
3804 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3805 : media_desc->simulcast_description()
3806 .receive_layers()
3807 .GetAllLayers();
3808 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003809 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003810 if (!error.ok()) {
3811 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3812 return std::move(error);
3813 }
3814 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003815 if (type == SdpType::kOffer) {
3816 // Make sure we don't overwrite existing stable states and that the
3817 // state is really going to change when adding new record to the map.
3818 auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
3819 if (it == transceiver_stable_states_by_transceivers_.end() &&
3820 (transceiver->internal()->mid() != content.name ||
3821 transceiver->internal()->mline_index() != mline_index)) {
3822 transceiver_stable_states_by_transceivers_[transceiver] =
3823 TransceiverStableState(transceiver->internal()->direction(),
3824 transceiver->internal()->mid(),
3825 transceiver->internal()->mline_index(), false);
3826 }
3827 }
3828
Steve Antondcc3c022017-12-22 16:02:54 -08003829 // Associate the found or created RtpTransceiver with the m= section by
3830 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3831 // section, and establish a mapping between the transceiver and the index of
3832 // the m= section.
3833 transceiver->internal()->set_mid(content.name);
3834 transceiver->internal()->set_mline_index(mline_index);
3835 return std::move(transceiver);
3836}
3837
3838rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3839PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3840 RTC_DCHECK(IsUnifiedPlan());
3841 for (auto transceiver : transceivers_) {
3842 if (transceiver->mid() == mid) {
3843 return transceiver;
3844 }
3845 }
3846 return nullptr;
3847}
3848
3849rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3850PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3851 RTC_DCHECK(IsUnifiedPlan());
3852 for (auto transceiver : transceivers_) {
3853 if (transceiver->internal()->mline_index() == mline_index) {
3854 return transceiver;
3855 }
3856 }
3857 return nullptr;
3858}
3859
3860rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3861PeerConnection::FindAvailableTransceiverToReceive(
3862 cricket::MediaType media_type) const {
3863 RTC_DCHECK(IsUnifiedPlan());
3864 // From JSEP section 5.10 (Applying a Remote Description):
3865 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3866 // the same type that were added to the PeerConnection by addTrack and are not
3867 // associated with any m= section and are not stopped, find the first such
3868 // RtpTransceiver.
3869 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003870 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003871 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3872 !transceiver->stopped()) {
3873 return transceiver;
3874 }
3875 }
3876 return nullptr;
3877}
3878
Steve Antoned10bd92017-12-05 10:52:59 -08003879const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3880 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3881 transceiver,
3882 const SessionDescriptionInterface* sdesc) const {
3883 RTC_DCHECK(transceiver);
3884 RTC_DCHECK(sdesc);
3885 if (IsUnifiedPlan()) {
3886 if (!transceiver->internal()->mid()) {
3887 // This transceiver is not associated with a media section yet.
3888 return nullptr;
3889 }
3890 return sdesc->description()->GetContentByName(
3891 *transceiver->internal()->mid());
3892 } else {
3893 // Plan B only allows at most one audio and one video section, so use the
3894 // first media section of that type.
3895 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003896 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003897 }
3898}
3899
deadbeef46c73892016-11-16 19:42:04 -08003900PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003901 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003902 return configuration_;
3903}
3904
Niels Möller2579f0c2019-08-19 09:58:17 +02003905RTCError PeerConnection::SetConfiguration(
3906 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003907 RTC_DCHECK_RUN_ON(signaling_thread());
3908 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003909 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003910 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003911 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3912 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003913 }
3914
Qingsi Wanga2d60672018-04-11 16:57:45 -07003915 // According to JSEP, after setLocalDescription, changing the candidate pool
3916 // size is not allowed, and changing the set of ICE servers will not result
3917 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003918 if (local_description() && configuration.ice_candidate_pool_size !=
3919 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003920 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3921 "Can't change candidate pool size after calling "
3922 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003923 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003924
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003925 if (local_description() &&
3926 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003927 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3928 "Can't change media_transport after calling "
3929 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003930 }
3931
3932 if (remote_description() &&
3933 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003934 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3935 "Can't change media_transport after calling "
3936 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003937 }
3938
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003939 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003940 configuration.use_media_transport_for_data_channels !=
3941 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003942 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3943 "Can't change media_transport_for_data_channels "
3944 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003945 }
3946
3947 if (remote_description() &&
3948 configuration.use_media_transport_for_data_channels !=
3949 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003950 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3951 "Can't change media_transport_for_data_channels "
3952 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003953 }
3954
3955 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003956 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003957 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3958 "Can't change crypto_options after calling "
3959 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003960 }
3961
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003962 if (local_description() && configuration.use_datagram_transport !=
3963 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003964 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3965 "Can't change use_datagram_transport "
3966 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003967 }
3968
3969 if (remote_description() && configuration.use_datagram_transport !=
3970 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003971 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3972 "Can't change use_datagram_transport "
3973 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003974 }
3975
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003976 if (local_description() &&
3977 configuration.use_datagram_transport_for_data_channels !=
3978 configuration_.use_datagram_transport_for_data_channels) {
3979 LOG_AND_RETURN_ERROR(
3980 RTCErrorType::INVALID_MODIFICATION,
3981 "Can't change use_datagram_transport_for_data_channels "
3982 "after calling SetLocalDescription.");
3983 }
3984
3985 if (remote_description() &&
3986 configuration.use_datagram_transport_for_data_channels !=
3987 configuration_.use_datagram_transport_for_data_channels) {
3988 LOG_AND_RETURN_ERROR(
3989 RTCErrorType::INVALID_MODIFICATION,
3990 "Can't change use_datagram_transport_for_data_channels "
3991 "after calling SetRemoteDescription.");
3992 }
3993
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003994 if (local_description() &&
3995 configuration.use_datagram_transport_for_data_channels_receive_only !=
3996 configuration_
3997 .use_datagram_transport_for_data_channels_receive_only) {
3998 LOG_AND_RETURN_ERROR(
3999 RTCErrorType::INVALID_MODIFICATION,
4000 "Can't change use_datagram_transport_for_data_channels_receive_only "
4001 "after calling SetLocalDescription.");
4002 }
4003
4004 if (remote_description() &&
4005 configuration.use_datagram_transport_for_data_channels_receive_only !=
4006 configuration_
4007 .use_datagram_transport_for_data_channels_receive_only) {
4008 LOG_AND_RETURN_ERROR(
4009 RTCErrorType::INVALID_MODIFICATION,
4010 "Can't change use_datagram_transport_for_data_channels_receive_only "
4011 "after calling SetRemoteDescription.");
4012 }
4013
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08004014 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07004015 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004016 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004017 *configuration.use_datagram_transport) ||
4018 (configuration.use_datagram_transport_for_data_channels &&
4019 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08004020 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
4021 << "Media transport requires MaxBundle policy.";
4022 }
4023
deadbeef293e9262017-01-11 12:28:30 -08004024 // The simplest (and most future-compatible) way to tell if the config was
4025 // modified in an invalid way is to copy each property we do support
4026 // modifying, then use operator==. There are far more properties we don't
4027 // support modifying than those we do, and more could be added.
4028 RTCConfiguration modified_config = configuration_;
4029 modified_config.servers = configuration.servers;
4030 modified_config.type = configuration.type;
4031 modified_config.ice_candidate_pool_size =
4032 configuration.ice_candidate_pool_size;
4033 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004034 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 14:56:02 -07004035 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
4036 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08004037 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08004038 modified_config.ice_check_interval_strong_connectivity =
4039 configuration.ice_check_interval_strong_connectivity;
4040 modified_config.ice_check_interval_weak_connectivity =
4041 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07004042 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
4043 modified_config.ice_unwritable_min_checks =
4044 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08004045 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004046 modified_config.stun_candidate_keepalive_interval =
4047 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004048 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004049 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07004050 modified_config.active_reset_srtp_params =
4051 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07004052 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07004053 modified_config.use_media_transport_for_data_channels =
4054 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004055 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004056 modified_config.use_datagram_transport_for_data_channels =
4057 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004058 modified_config.use_datagram_transport_for_data_channels_receive_only =
4059 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 16:16:35 +02004060 modified_config.turn_logging_id = configuration.turn_logging_id;
philipel16cec3b2019-10-25 12:23:02 +02004061 modified_config.allow_codec_switching = configuration.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -08004062 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004063 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
4064 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08004065 }
4066
Steve Anton038834f2017-07-14 15:59:59 -07004067 // Validate the modified configuration.
4068 RTCError validate_error = ValidateConfiguration(modified_config);
4069 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004070 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07004071 }
4072
deadbeef293e9262017-01-11 12:28:30 -08004073 // Note that this isn't possible through chromium, since it's an unsigned
4074 // short in WebIDL.
4075 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07004076 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004077 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08004078 }
4079
4080 // Parse ICE servers before hopping to network thread.
4081 cricket::ServerAddresses stun_servers;
4082 std::vector<cricket::RelayServerConfig> turn_servers;
4083 RTCErrorType parse_error =
4084 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
4085 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004086 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08004087 }
Jonas Oreland3c028422019-08-22 16:16:35 +02004088 // Add the turn logging id to all turn servers
4089 for (cricket::RelayServerConfig& turn_server : turn_servers) {
4090 turn_server.turn_logging_id = configuration.turn_logging_id;
4091 }
4092
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004093 // Note if STUN or TURN servers were supplied.
4094 if (!stun_servers.empty()) {
4095 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
4096 }
4097 if (!turn_servers.empty()) {
4098 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
4099 }
deadbeef293e9262017-01-11 12:28:30 -08004100
4101 // In theory this shouldn't fail.
4102 if (!network_thread()->Invoke<bool>(
4103 RTC_FROM_HERE,
4104 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
4105 stun_servers, turn_servers, modified_config.type,
4106 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004107 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004108 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02004109 modified_config.stun_candidate_keepalive_interval,
4110 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004111 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4112 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08004113 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004114
deadbeefd1a38b52016-12-10 13:15:33 -08004115 // As described in JSEP, calling setConfiguration with new ICE servers or
4116 // candidate policy must set a "needs-ice-restart" bit so that the next offer
4117 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08004118 if (modified_config.servers != configuration_.servers ||
4119 modified_config.type != configuration_.type ||
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004120 modified_config.GetTurnPortPrunePolicy() !=
4121 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 14:50:29 -08004122 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08004123 }
skvladd1f5fda2017-02-03 16:54:05 -08004124
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08004125 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004126
4127 use_datagram_transport_ = datagram_transport_config_.enabled &&
4128 modified_config.use_datagram_transport.value_or(
4129 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004130 use_datagram_transport_for_data_channels_ =
4131 datagram_transport_data_channel_config_.enabled &&
4132 modified_config.use_datagram_transport_for_data_channels.value_or(
4133 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004134 use_datagram_transport_for_data_channels_receive_only_ =
4135 modified_config.use_datagram_transport_for_data_channels_receive_only
4136 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08004137 transport_controller_->SetMediaTransportSettings(
4138 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07004139 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004140 use_datagram_transport_, use_datagram_transport_for_data_channels_,
4141 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-03 16:54:05 -08004142
Zhi Huangb57e1692018-06-12 11:41:11 -07004143 if (configuration_.active_reset_srtp_params !=
4144 modified_config.active_reset_srtp_params) {
4145 transport_controller_->SetActiveResetSrtpParams(
4146 modified_config.active_reset_srtp_params);
4147 }
4148
philipel16cec3b2019-10-25 12:23:02 +02004149 if (modified_config.allow_codec_switching.has_value()) {
4150 video_media_channel()->SetVideoCodecSwitchingEnabled(
4151 *modified_config.allow_codec_switching);
4152 }
4153
deadbeef293e9262017-01-11 12:28:30 -08004154 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01004155 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02004156 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00004157}
4158
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004159bool PeerConnection::AddIceCandidate(
4160 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004161 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004162 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07004163 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004164 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004165 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07004166 return false;
4167 }
Steve Antond25da372017-11-06 14:50:29 -08004168
4169 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004170 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004171 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004172 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08004173 return false;
4174 }
4175
4176 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07004177 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004178 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08004179 return false;
4180 }
4181
4182 bool valid = false;
4183 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
4184 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004185 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08004186 return false;
4187 }
4188
4189 // Add this candidate to the remote session description.
4190 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07004191 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004192 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08004193 return false;
4194 }
4195
4196 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004197 bool result = UseCandidate(ice_candidate);
4198 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004199 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02004200 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
4201 } else {
4202 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
4203 }
4204 return result;
Steve Antond25da372017-11-06 14:50:29 -08004205 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07004206 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004207 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08004208 return true;
4209 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004210}
4211
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004212bool PeerConnection::RemoveIceCandidates(
4213 const std::vector<cricket::Candidate>& candidates) {
4214 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004215 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07004216 if (IsClosed()) {
4217 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
4218 return false;
4219 }
4220
Steve Antond25da372017-11-06 14:50:29 -08004221 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004222 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
4223 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08004224 return false;
4225 }
4226
4227 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004228 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08004229 return false;
4230 }
4231
4232 size_t number_removed =
4233 mutable_remote_description()->RemoveCandidates(candidates);
4234 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004235 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07004236 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004237 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01004238 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08004239 }
4240
4241 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07004242 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
4243 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004244 RTC_LOG(LS_ERROR)
4245 << "RemoveIceCandidates: Error when removing remote candidates: "
4246 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08004247 }
4248 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004249}
4250
Niels Möller0c4f7be2018-05-07 14:01:37 +02004251RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07004252 if (!worker_thread()->IsCurrent()) {
4253 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02004254 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07004255 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01004256 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07004257
Niels Möller0c4f7be2018-05-07 14:01:37 +02004258 const bool has_min = bitrate.min_bitrate_bps.has_value();
4259 const bool has_start = bitrate.start_bitrate_bps.has_value();
4260 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07004261 if (has_min && *bitrate.min_bitrate_bps < 0) {
4262 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4263 "min_bitrate_bps <= 0");
4264 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02004265 if (has_start) {
4266 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004267 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004268 "start_bitrate_bps < min_bitrate_bps");
4269 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07004270 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4271 "curent_bitrate_bps < 0");
4272 }
4273 }
4274 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02004275 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004277 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07004278 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
4279 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4280 "max_bitrate_bps < min_bitrate_bps");
4281 } else if (*bitrate.max_bitrate_bps < 0) {
4282 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4283 "max_bitrate_bps < 0");
4284 }
4285 }
4286
zstein4b979802017-06-02 14:37:37 -07004287 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07004288 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07004289
4290 return RTCError::OK();
4291}
4292
henrika5f6bf242017-11-01 11:06:56 +01004293void PeerConnection::SetAudioPlayout(bool playout) {
4294 if (!worker_thread()->IsCurrent()) {
4295 worker_thread()->Invoke<void>(
4296 RTC_FROM_HERE,
4297 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
4298 return;
4299 }
4300 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004301 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004302 audio_state->SetPlayout(playout);
4303}
4304
4305void PeerConnection::SetAudioRecording(bool recording) {
4306 if (!worker_thread()->IsCurrent()) {
4307 worker_thread()->Invoke<void>(
4308 RTC_FROM_HERE,
4309 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
4310 return;
4311 }
4312 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004313 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004314 audio_state->SetRecording(recording);
4315}
4316
Steve Anton8c0f7a72017-10-03 10:03:10 -07004317std::unique_ptr<rtc::SSLCertificate>
4318PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004319 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
4320 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07004321 return nullptr;
4322 }
Steve Antonf25303e2018-10-16 15:23:31 -07004323 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07004324}
4325
Zhi Huang70b820f2018-01-27 14:16:15 -08004326std::unique_ptr<rtc::SSLCertChain>
4327PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01004328 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08004329 auto audio_transceiver = GetFirstAudioTransceiver();
4330 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08004331 return nullptr;
4332 }
Zhi Huang70b820f2018-01-27 14:16:15 -08004333 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08004334 audio_transceiver->internal()->channel()->transport_name());
4335}
4336
4337rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4338PeerConnection::GetFirstAudioTransceiver() const {
4339 for (auto transceiver : transceivers_) {
4340 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4341 return transceiver;
4342 }
4343 }
4344 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08004345}
4346
Bjorn Tereliusde939432017-11-20 17:38:14 +01004347bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
4348 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01004349 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02004350 RTC_FROM_HERE,
4351 [this, output = std::move(output), output_period_ms]() mutable {
4352 return StartRtcEventLog_w(std::move(output), output_period_ms);
4353 });
ivoc14d5dbe2016-07-04 07:06:55 -07004354}
4355
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004356bool PeerConnection::StartRtcEventLog(
4357 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02004358 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4359 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4360 output_period_ms = 5000;
4361 }
4362 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004363}
4364
ivoc14d5dbe2016-07-04 07:06:55 -07004365void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004366 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004367 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4368}
4369
Harald Alvestrandad88c882018-11-28 16:47:46 +01004370rtc::scoped_refptr<DtlsTransportInterface>
4371PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004372 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004373 return transport_controller_->LookupDtlsTransportByMid(mid);
4374}
4375
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004376rtc::scoped_refptr<DtlsTransport>
4377PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004378 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004379 return transport_controller_->LookupDtlsTransportByMid(mid);
4380}
4381
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004382rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4383 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004384 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004385 if (!sctp_mid_) {
4386 return nullptr;
4387 }
4388 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004389}
4390
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004391const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004392 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004393 return pending_local_description_ ? pending_local_description_.get()
4394 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004395}
4396
4397const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004398 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004399 return pending_remote_description_ ? pending_remote_description_.get()
4400 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004401}
4402
deadbeeffe4a8a42016-12-20 17:56:17 -08004403const SessionDescriptionInterface* PeerConnection::current_local_description()
4404 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004405 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004406 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004407}
4408
4409const SessionDescriptionInterface* PeerConnection::current_remote_description()
4410 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004411 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004412 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004413}
4414
4415const SessionDescriptionInterface* PeerConnection::pending_local_description()
4416 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004417 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004418 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004419}
4420
4421const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4422 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004423 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004424 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004425}
4426
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004427void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004428 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004429 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004430 // Update stats here so that we have the most recent stats for tracks and
4431 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004432 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004433
Steve Anton75737c02017-11-06 10:37:17 -08004434 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004435 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004436
Mirko Bonadei739baf02019-01-27 17:29:42 +01004437 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004438 transceiver->Stop();
4439 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004440
4441 // Ensure that all asynchronous stats requests are completed before destroying
4442 // the transport controller below.
4443 if (stats_collector_) {
4444 stats_collector_->WaitForPendingRequest();
4445 }
4446
4447 // Don't destroy BaseChannels until after stats has been cleaned up so that
4448 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004449 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004450
Qingsi Wang93a84392018-01-30 17:13:09 -08004451 // The event log is used in the transport controller, which must be outlived
4452 // by the former. CreateOffer by the peer connection is implemented
4453 // asynchronously and if the peer connection is closed without resetting the
4454 // WebRTC session description factory, the session description factory would
4455 // call the transport controller.
4456 webrtc_session_desc_factory_.reset();
4457 transport_controller_.reset();
4458
deadbeef42a42632017-03-10 15:18:00 -08004459 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004460 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4461 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004462
Steve Anton978b8762017-09-29 12:15:02 -07004463 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004464 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004465 call_.reset();
4466 // The event log must outlive call (and any other object that uses it).
4467 event_log_.reset();
4468 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004469 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004470 // The .h file says that observer can be discarded after close() returns.
4471 // Make sure this is true.
4472 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004473}
4474
Steve Antonad182762018-09-05 20:22:40 +00004475void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004476 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004477 switch (msg->message_id) {
4478 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4479 SetSessionDescriptionMsg* param =
4480 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4481 param->observer->OnSuccess();
4482 delete param;
4483 break;
4484 }
4485 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4486 SetSessionDescriptionMsg* param =
4487 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4488 param->observer->OnFailure(std::move(param->error));
4489 delete param;
4490 break;
4491 }
4492 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4493 CreateSessionDescriptionMsg* param =
4494 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4495 param->observer->OnFailure(std::move(param->error));
4496 delete param;
4497 break;
4498 }
4499 case MSG_GETSTATS: {
4500 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4501 StatsReports reports;
4502 stats_->GetStats(param->track, &reports);
4503 param->observer->OnComplete(reports);
4504 delete param;
4505 break;
4506 }
4507 case MSG_FREE_DATACHANNELS: {
4508 sctp_data_channels_to_free_.clear();
4509 break;
4510 }
4511 case MSG_REPORT_USAGE_PATTERN: {
4512 ReportUsagePattern();
4513 break;
4514 }
4515 default:
4516 RTC_NOTREACHED() << "Not implemented";
4517 break;
4518 }
4519}
4520
Steve Antonafb0bb72018-02-20 11:35:37 -08004521cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4522 RTC_DCHECK(!IsUnifiedPlan());
4523 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4524 GetAudioTransceiver()->internal()->channel());
4525 if (voice_channel) {
4526 return voice_channel->media_channel();
4527 } else {
4528 return nullptr;
4529 }
4530}
4531
4532cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4533 RTC_DCHECK(!IsUnifiedPlan());
4534 auto* video_channel = static_cast<cricket::VideoChannel*>(
4535 GetVideoTransceiver()->internal()->channel());
4536 if (video_channel) {
4537 return video_channel->media_channel();
4538 } else {
4539 return nullptr;
4540 }
4541}
4542
Steve Anton4171afb2017-11-20 10:20:22 -08004543void PeerConnection::CreateAudioReceiver(
4544 MediaStreamInterface* stream,
4545 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004546 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4547 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004548 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4549 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004550 auto* audio_receiver = new AudioRtpReceiver(
4551 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004552 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004553 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4554 audio_receiver->SetupUnsignaledMediaChannel();
4555 } else {
4556 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4557 }
Steve Antond3679212018-01-17 17:41:02 -08004558 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4559 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004560 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004561 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004562 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004563}
4564
Steve Anton4171afb2017-11-20 10:20:22 -08004565void PeerConnection::CreateVideoReceiver(
4566 MediaStreamInterface* stream,
4567 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004568 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4569 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004570 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4571 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004572 auto* video_receiver = new VideoRtpReceiver(
4573 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004574 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004575 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4576 video_receiver->SetupUnsignaledMediaChannel();
4577 } else {
4578 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4579 }
Steve Antond3679212018-01-17 17:41:02 -08004580 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4581 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004582 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004583 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004584 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004585}
4586
deadbeef70ab1a12015-09-28 16:53:55 -07004587// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4588// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004589rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004590 const RtpSenderInfo& remote_sender_info) {
4591 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4592 if (!receiver) {
4593 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4594 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004595 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004596 }
Steve Anton4171afb2017-11-20 10:20:22 -08004597 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4598 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4599 } else {
4600 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4601 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004602 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004603}
4604
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004605void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4606 MediaStreamInterface* stream) {
4607 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004608 RTC_DCHECK(track);
4609 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004610 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004611 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004612 // We already have a sender for this track, so just change the stream_id
4613 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004614 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004615 return;
4616 }
4617
4618 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004619 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004620 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004621 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004622 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004623 // If the sender has already been configured in SDP, we call SetSsrc,
4624 // which will connect the sender to the underlying transport. This can
4625 // occur if a local session description that contains the ID of the sender
4626 // is set before AddStream is called. It can also occur if the local
4627 // session description is not changed and RemoveStream is called, and
4628 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004629 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004630 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004631 if (sender_info) {
4632 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004633 }
4634}
4635
4636// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4637// indefinitely, when we have unified plan SDP.
4638void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4639 MediaStreamInterface* stream) {
4640 RTC_DCHECK(!IsClosed());
4641 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004642 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004643 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4644 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004645 return;
4646 }
Steve Anton4171afb2017-11-20 10:20:22 -08004647 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004648}
4649
4650void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4651 MediaStreamInterface* stream) {
4652 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004653 RTC_DCHECK(track);
4654 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004655 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004656 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004657 // We already have a sender for this track, so just change the stream_id
4658 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004659 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004660 return;
4661 }
4662
4663 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004664 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004665 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004666 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004667 GetVideoTransceiver()->internal()->AddSender(new_sender);
4668 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004669 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004670 if (sender_info) {
4671 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004672 }
4673}
4674
4675void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4676 MediaStreamInterface* stream) {
4677 RTC_DCHECK(!IsClosed());
4678 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004679 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004680 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4681 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004682 return;
4683 }
Steve Anton4171afb2017-11-20 10:20:22 -08004684 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004685}
4686
Steve Antonba818672017-11-06 10:21:57 -08004687void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004688 if (ice_connection_state_ == new_state) {
4689 return;
4690 }
4691
deadbeefcbecd352015-09-23 11:50:27 -07004692 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004693 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004694 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004695 return;
4696 }
Steve Antonba818672017-11-06 10:21:57 -08004697
Mirko Bonadei675513b2017-11-09 11:09:25 +01004698 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4699 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004700 RTC_DCHECK(ice_connection_state_ !=
4701 PeerConnectionInterface::kIceConnectionClosed);
4702
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004703 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004704 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004705}
4706
Alex Loiko9289eda2018-11-23 16:18:59 +00004707void PeerConnection::SetStandardizedIceConnectionState(
4708 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004709 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004710 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004711 }
4712
4713 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004714 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004715 }
4716
4717 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4718 << standardized_ice_connection_state_ << " => " << new_state;
4719
Alex Loiko9289eda2018-11-23 16:18:59 +00004720 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004721 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004722}
4723
Jonas Olsson635474e2018-10-18 15:58:17 +02004724void PeerConnection::SetConnectionState(
4725 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004726 if (connection_state_ == new_state)
4727 return;
4728 if (IsClosed())
4729 return;
4730 connection_state_ = new_state;
4731 Observer()->OnConnectionChange(new_state);
4732}
4733
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004734void PeerConnection::OnIceGatheringChange(
4735 PeerConnectionInterface::IceGatheringState new_state) {
4736 if (IsClosed()) {
4737 return;
4738 }
4739 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004740 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004741}
4742
jbauch81bf7b02017-03-25 08:31:12 -07004743void PeerConnection::OnIceCandidate(
4744 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004745 if (IsClosed()) {
4746 return;
4747 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004748 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004749 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004750}
4751
Eldar Relloda13ea22019-06-01 12:23:43 +03004752void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4753 const std::string& url,
4754 int error_code,
4755 const std::string& error_text) {
4756 if (IsClosed()) {
4757 return;
4758 }
4759 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4760}
4761
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004762void PeerConnection::OnIceCandidatesRemoved(
4763 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004764 if (IsClosed()) {
4765 return;
4766 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004767 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004768}
4769
Alex Drake00c7ecf2019-08-06 10:54:47 -07004770void PeerConnection::OnSelectedCandidatePairChanged(
4771 const cricket::CandidatePairChangeEvent& event) {
4772 if (IsClosed()) {
4773 return;
4774 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004775
Qingsi Wangcc46b102019-09-12 11:19:01 -07004776 if (event.selected_candidate_pair.local_candidate().type() ==
4777 LOCAL_PORT_TYPE &&
4778 event.selected_candidate_pair.remote_candidate().type() ==
4779 LOCAL_PORT_TYPE) {
4780 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4781 }
4782
Alex Drake00c7ecf2019-08-06 10:54:47 -07004783 Observer()->OnIceSelectedCandidatePairChanged(event);
4784}
4785
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004786void PeerConnection::ChangeSignalingState(
4787 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004788 if (signaling_state_ == signaling_state) {
4789 return;
4790 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004791 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4792 << GetSignalingStateString(signaling_state_)
4793 << " New state: "
4794 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004795 signaling_state_ = signaling_state;
4796 if (signaling_state == kClosed) {
4797 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004798 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004799 standardized_ice_connection_state_ =
4800 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004801 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4802 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004803 if (ice_gathering_state_ != kIceGatheringComplete) {
4804 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004805 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004806 }
4807 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004808 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004809}
4810
deadbeefeb459812015-12-15 19:24:43 -08004811void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4812 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004813 if (IsClosed()) {
4814 return;
4815 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004816 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004817 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004818}
4819
deadbeefeb459812015-12-15 19:24:43 -08004820void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4821 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004822 if (IsClosed()) {
4823 return;
4824 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004825 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004826 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004827}
4828
4829void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4830 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004831 if (IsClosed()) {
4832 return;
4833 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004834 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004835 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004836}
4837
4838void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4839 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004840 if (IsClosed()) {
4841 return;
4842 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004843 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004844 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004845}
4846
Henrik Boström31638672017-11-23 17:48:32 +01004847void PeerConnection::PostSetSessionDescriptionSuccess(
4848 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004849 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4850 signaling_thread()->Post(RTC_FROM_HERE, this,
4851 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004852}
4853
deadbeefab9b2d12015-10-14 11:33:11 -07004854void PeerConnection::PostSetSessionDescriptionFailure(
4855 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004856 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004857 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004858 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4859 msg->error = std::move(error);
4860 signaling_thread()->Post(RTC_FROM_HERE, this,
4861 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004862}
4863
4864void PeerConnection::PostCreateSessionDescriptionFailure(
4865 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004866 RTCError error) {
4867 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004868 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4869 msg->error = std::move(error);
4870 signaling_thread()->Post(RTC_FROM_HERE, this,
4871 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004872}
4873
zhihuang1c378ed2017-08-17 14:10:50 -07004874void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004875 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004876 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004877 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004878
Steve Antondcc3c022017-12-22 16:02:54 -08004879 if (IsUnifiedPlan()) {
4880 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4881 } else {
4882 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4883 }
4884
Steve Antonfa2260d2017-12-28 16:38:23 -08004885 // Intentionally unset the data channel type for RTP data channel with the
4886 // second condition. Otherwise the RTP data channels would be successfully
4887 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4888 // when building with chromium. We want to leave RTP data channels broken, so
4889 // people won't try to use them.
4890 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4891 session_options->data_channel_type = data_channel_type();
4892 }
4893
Steve Antondcc3c022017-12-22 16:02:54 -08004894 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004895 bool ice_restart = offer_answer_options.ice_restart ||
4896 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004897 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004898 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004899 options.transport_options.enable_ice_renomination =
4900 configuration_.enable_ice_renomination;
4901 }
4902
4903 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004904 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004905 session_options->pooled_ice_credentials =
4906 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4907 RTC_FROM_HERE,
4908 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4909 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004910 session_options->offer_extmap_allow_mixed =
4911 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004912
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004913 if (configuration_.use_media_transport ||
4914 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004915 session_options->media_transport_settings =
4916 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4917 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004918
4919 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004920 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004921 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004922 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004923 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004924 if (!params) {
4925 continue;
4926 }
4927 options.transport_options.opaque_parameters = params;
4928 if ((use_datagram_transport_ &&
4929 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4930 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4931 (use_datagram_transport_for_data_channels_ &&
4932 options.type == cricket::MEDIA_TYPE_DATA)) {
4933 options.alt_protocol = params->protocol;
4934 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004935 }
4936 }
4937
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004938 // Allow fallback for using obsolete SCTP syntax.
4939 // Note that the default in |session_options| is true, while
4940 // the default in |options| is false.
4941 session_options->use_obsolete_sctp_sdp =
4942 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004943}
4944
4945void PeerConnection::GetOptionsForPlanBOffer(
4946 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4947 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004948 // Figure out transceiver directional preferences.
4949 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4950 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4951
4952 // By default, generate sendrecv/recvonly m= sections.
4953 bool recv_audio = true;
4954 bool recv_video = true;
4955
4956 // By default, only offer a new m= section if we have media to send with it.
4957 bool offer_new_audio_description = send_audio;
4958 bool offer_new_video_description = send_video;
4959 bool offer_new_data_description = HasDataChannels();
4960
4961 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004962 if (offer_answer_options.offer_to_receive_audio !=
4963 RTCOfferAnswerOptions::kUndefined) {
4964 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004965 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004966 offer_new_audio_description ||
4967 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004968 }
Steve Antondcc3c022017-12-22 16:02:54 -08004969 if (offer_answer_options.offer_to_receive_video !=
4970 RTCOfferAnswerOptions::kUndefined) {
4971 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004972 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004973 offer_new_video_description ||
4974 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004975 }
4976
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004977 absl::optional<size_t> audio_index;
4978 absl::optional<size_t> video_index;
4979 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004980 // If a current description exists, generate m= sections in the same order,
4981 // using the first audio/video/data section that appears and rejecting
4982 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004983 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004984 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004985 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004986 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4987 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4988 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004989 }
4990
zhihuang1c378ed2017-08-17 14:10:50 -07004991 // Add audio/video/data m= sections to the end if needed.
4992 if (!audio_index && offer_new_audio_description) {
4993 session_options->media_description_options.push_back(
4994 cricket::MediaDescriptionOptions(
4995 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004996 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4997 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004998 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004999 }
zhihuang1c378ed2017-08-17 14:10:50 -07005000 if (!video_index && offer_new_video_description) {
5001 session_options->media_description_options.push_back(
5002 cricket::MediaDescriptionOptions(
5003 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08005004 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5005 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005006 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07005007 }
zhihuang1c378ed2017-08-17 14:10:50 -07005008 if (!data_index && offer_new_data_description) {
5009 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005010 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005011 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005012 }
5013
5014 cricket::MediaDescriptionOptions* audio_media_description_options =
5015 !audio_index ? nullptr
5016 : &session_options->media_description_options[*audio_index];
5017 cricket::MediaDescriptionOptions* video_media_description_options =
5018 !video_index ? nullptr
5019 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005020
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005021 AddPlanBRtpSenderOptions(GetSendersInternal(),
5022 audio_media_description_options,
5023 video_media_description_options,
5024 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005025}
5026
Steve Antondcc3c022017-12-22 16:02:54 -08005027static cricket::MediaDescriptionOptions
5028GetMediaDescriptionOptionsForTransceiver(
5029 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5030 transceiver,
5031 const std::string& mid) {
5032 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08005033 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08005034 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02005035 media_description_options.codec_preferences =
5036 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08005037 // This behavior is specified in JSEP. The gist is that:
5038 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
5039 // sendrecv.
5040 // 2. If the MSID is included, then it must be included in any subsequent
5041 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005042 if (transceiver->stopped() ||
5043 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
5044 !transceiver->internal()->has_ever_been_used_to_send())) {
5045 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08005046 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005047
5048 cricket::SenderOptions sender_options;
5049 sender_options.track_id = transceiver->sender()->id();
5050 sender_options.stream_ids = transceiver->sender()->stream_ids();
5051
5052 // The following sets up RIDs and Simulcast.
5053 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08005054 RtpParameters send_parameters =
5055 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005056 bool has_rids = std::any_of(send_parameters.encodings.begin(),
5057 send_parameters.encodings.end(),
5058 [](const RtpEncodingParameters& encoding) {
5059 return !encoding.rid.empty();
5060 });
5061
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08005062 std::vector<RidDescription> send_rids;
5063 SimulcastLayerList send_layers;
5064 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
5065 if (encoding.rid.empty()) {
5066 continue;
5067 }
5068 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
5069 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
5070 }
5071
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005072 if (has_rids) {
5073 sender_options.rids = send_rids;
5074 }
5075
5076 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005077 // When RIDs are configured, we must set num_sim_layers to 0 to.
5078 // Otherwise, num_sim_layers must be 1 because either there is no
5079 // simulcast, or simulcast is acheived by munging the SDP.
5080 sender_options.num_sim_layers = has_rids ? 0 : 1;
5081 media_description_options.sender_options.push_back(sender_options);
5082
Steve Antondcc3c022017-12-22 16:02:54 -08005083 return media_description_options;
5084}
5085
Steve Anton5c72e712018-12-10 14:25:30 -08005086// Returns the ContentInfo at mline index |i|, or null if none exists.
5087static const ContentInfo* GetContentByIndex(
5088 const SessionDescriptionInterface* sdesc,
5089 size_t i) {
5090 if (!sdesc) {
5091 return nullptr;
5092 }
5093 const ContentInfos& contents = sdesc->description()->contents();
5094 return (i < contents.size() ? &contents[i] : nullptr);
5095}
5096
Steve Antondcc3c022017-12-22 16:02:54 -08005097void PeerConnection::GetOptionsForUnifiedPlanOffer(
5098 const RTCOfferAnswerOptions& offer_answer_options,
5099 cricket::MediaSessionOptions* session_options) {
5100 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
5101 // Offers) and 5.2.2 (Subsequent Offers).
5102 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02005103 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08005104 const ContentInfos& local_contents =
5105 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005106 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005107 const ContentInfos& remote_contents =
5108 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005109 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005110 // The mline indices that can be recycled. New transceivers should reuse these
5111 // slots first.
5112 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08005113 // First, go through each media section that exists in either the local or
5114 // remote description and generate a media section in this offer for the
5115 // associated transceiver. If a media section can be recycled, generate a
5116 // default, rejected media section here that can be later overwritten.
5117 for (size_t i = 0;
5118 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
5119 // Either |local_content| or |remote_content| is non-null.
5120 const ContentInfo* local_content =
5121 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005122 const ContentInfo* current_local_content =
5123 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08005124 const ContentInfo* remote_content =
5125 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005126 const ContentInfo* current_remote_content =
5127 GetContentByIndex(current_remote_description(), i);
5128 bool had_been_rejected =
5129 (current_local_content && current_local_content->rejected) ||
5130 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08005131 const std::string& mid =
5132 (local_content ? local_content->name : remote_content->name);
5133 cricket::MediaType media_type =
5134 (local_content ? local_content->media_description()->type()
5135 : remote_content->media_description()->type());
5136 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5137 media_type == cricket::MEDIA_TYPE_VIDEO) {
5138 auto transceiver = GetAssociatedTransceiver(mid);
5139 RTC_CHECK(transceiver);
5140 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08005141 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005142 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08005143 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08005144 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
5145 RtpTransceiverDirection::kInactive,
5146 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08005147 recycleable_mline_indices.push(i);
5148 } else {
5149 session_options->media_description_options.push_back(
5150 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
5151 // CreateOffer shouldn't really cause any state changes in
5152 // PeerConnection, but we need a way to match new transceivers to new
5153 // media sections in SetLocalDescription and JSEP specifies this is done
5154 // by recording the index of the media section generated for the
5155 // transceiver in the offer.
5156 transceiver->internal()->set_mline_index(i);
5157 }
5158 } else {
5159 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08005160 RTC_CHECK(GetDataMid());
5161 if (had_been_rejected || mid != *GetDataMid()) {
5162 session_options->media_description_options.push_back(
5163 GetMediaDescriptionOptionsForRejectedData(mid));
5164 } else {
5165 session_options->media_description_options.push_back(
5166 GetMediaDescriptionOptionsForActiveData(mid));
5167 }
Steve Antondcc3c022017-12-22 16:02:54 -08005168 }
5169 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08005170
Steve Antondcc3c022017-12-22 16:02:54 -08005171 // Next, look for transceivers that are newly added (that is, are not stopped
5172 // and not associated). Reuse media sections marked as recyclable first,
5173 // otherwise append to the end of the offer. New media sections should be
5174 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005175 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08005176 if (transceiver->mid() || transceiver->stopped()) {
5177 continue;
5178 }
5179 size_t mline_index;
5180 if (!recycleable_mline_indices.empty()) {
5181 mline_index = recycleable_mline_indices.front();
5182 recycleable_mline_indices.pop();
5183 session_options->media_description_options[mline_index] =
5184 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005185 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08005186 } else {
5187 mline_index = session_options->media_description_options.size();
5188 session_options->media_description_options.push_back(
5189 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005190 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08005191 }
5192 // See comment above for why CreateOffer changes the transceiver's state.
5193 transceiver->internal()->set_mline_index(mline_index);
5194 }
Steve Antonfa2260d2017-12-28 16:38:23 -08005195 // Lastly, add a m-section if we have local data channels and an m section
5196 // does not already exist.
5197 if (!GetDataMid() && HasDataChannels()) {
5198 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08005199 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08005200 }
Steve Antondcc3c022017-12-22 16:02:54 -08005201}
5202
5203void PeerConnection::GetOptionsForAnswer(
5204 const RTCOfferAnswerOptions& offer_answer_options,
5205 cricket::MediaSessionOptions* session_options) {
5206 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
5207
5208 if (IsUnifiedPlan()) {
5209 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
5210 } else {
5211 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
5212 }
5213
Steve Antonfa2260d2017-12-28 16:38:23 -08005214 // Intentionally unset the data channel type for RTP data channel. Otherwise
5215 // the RTP data channels would be successfully negotiated by default and the
5216 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
5217 // We want to leave RTP data channels broken, so people won't try to use them.
5218 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
5219 session_options->data_channel_type = data_channel_type();
5220 }
5221
Steve Antondcc3c022017-12-22 16:02:54 -08005222 // Apply ICE renomination flag.
5223 for (auto& options : session_options->media_description_options) {
5224 options.transport_options.enable_ice_renomination =
5225 configuration_.enable_ice_renomination;
5226 }
zhihuang8f65cdf2016-05-06 18:40:30 -07005227
5228 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005229 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02005230 session_options->pooled_ice_credentials =
5231 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
5232 RTC_FROM_HERE,
5233 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
5234 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005235
5236 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005237 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005238 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005239 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005240 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005241 if (!params) {
5242 continue;
5243 }
5244 options.transport_options.opaque_parameters = params;
5245 if ((use_datagram_transport_ &&
5246 (options.type == cricket::MEDIA_TYPE_AUDIO ||
5247 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
5248 (use_datagram_transport_for_data_channels_ &&
5249 options.type == cricket::MEDIA_TYPE_DATA)) {
5250 options.alt_protocol = params->protocol;
5251 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005252 }
5253 }
deadbeefab9b2d12015-10-14 11:33:11 -07005254}
5255
Steve Antondcc3c022017-12-22 16:02:54 -08005256void PeerConnection::GetOptionsForPlanBAnswer(
5257 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07005258 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005259 // Figure out transceiver directional preferences.
5260 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
5261 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
5262
5263 // By default, generate sendrecv/recvonly m= sections. The direction is also
5264 // restricted by the direction in the offer.
5265 bool recv_audio = true;
5266 bool recv_video = true;
5267
5268 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08005269 if (offer_answer_options.offer_to_receive_audio !=
5270 RTCOfferAnswerOptions::kUndefined) {
5271 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08005272 }
Steve Antondcc3c022017-12-22 16:02:54 -08005273 if (offer_answer_options.offer_to_receive_video !=
5274 RTCOfferAnswerOptions::kUndefined) {
5275 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005276 }
5277
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005278 absl::optional<size_t> audio_index;
5279 absl::optional<size_t> video_index;
5280 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08005281
5282 // Generate m= sections that match those in the offer.
5283 // Note that mediasession.cc will handle intersection our preferred
5284 // direction with the offered direction.
5285 GenerateMediaDescriptionOptions(
5286 remote_description(),
5287 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5288 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
5289 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07005290
5291 cricket::MediaDescriptionOptions* audio_media_description_options =
5292 !audio_index ? nullptr
5293 : &session_options->media_description_options[*audio_index];
5294 cricket::MediaDescriptionOptions* video_media_description_options =
5295 !video_index ? nullptr
5296 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005297
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005298 AddPlanBRtpSenderOptions(GetSendersInternal(),
5299 audio_media_description_options,
5300 video_media_description_options,
5301 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005302}
zhihuangaf388472016-11-02 16:49:48 -07005303
Steve Antondcc3c022017-12-22 16:02:54 -08005304void PeerConnection::GetOptionsForUnifiedPlanAnswer(
5305 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
5306 cricket::MediaSessionOptions* session_options) {
5307 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
5308 // Answers) and 5.3.2 (Subsequent Answers).
5309 RTC_DCHECK(remote_description());
5310 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
5311 for (const ContentInfo& content :
5312 remote_description()->description()->contents()) {
5313 cricket::MediaType media_type = content.media_description()->type();
5314 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5315 media_type == cricket::MEDIA_TYPE_VIDEO) {
5316 auto transceiver = GetAssociatedTransceiver(content.name);
5317 RTC_CHECK(transceiver);
5318 session_options->media_description_options.push_back(
5319 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
5320 } else {
5321 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08005322 // Reject all data sections if data channels are disabled.
5323 // Reject a data section if it has already been rejected.
5324 // Reject all data sections except for the first one.
5325 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
5326 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005327 session_options->media_description_options.push_back(
5328 GetMediaDescriptionOptionsForRejectedData(content.name));
5329 } else {
5330 session_options->media_description_options.push_back(
5331 GetMediaDescriptionOptionsForActiveData(content.name));
5332 }
Steve Antondcc3c022017-12-22 16:02:54 -08005333 }
5334 }
htaa2a49d92016-03-04 02:51:39 -08005335}
5336
zhihuang1c378ed2017-08-17 14:10:50 -07005337void PeerConnection::GenerateMediaDescriptionOptions(
5338 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08005339 RtpTransceiverDirection audio_direction,
5340 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005341 absl::optional<size_t>* audio_index,
5342 absl::optional<size_t>* video_index,
5343 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08005344 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005345 for (const cricket::ContentInfo& content :
5346 session_desc->description()->contents()) {
5347 if (IsAudioContent(&content)) {
5348 // If we already have an audio m= section, reject this extra one.
5349 if (*audio_index) {
5350 session_options->media_description_options.push_back(
5351 cricket::MediaDescriptionOptions(
5352 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005353 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005354 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005355 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005356 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005357 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5358 content.name, audio_direction,
5359 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005360 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005361 }
5362 } else if (IsVideoContent(&content)) {
5363 // If we already have an video m= section, reject this extra one.
5364 if (*video_index) {
5365 session_options->media_description_options.push_back(
5366 cricket::MediaDescriptionOptions(
5367 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005368 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005369 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005370 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005371 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005372 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5373 content.name, video_direction,
5374 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005375 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005376 }
5377 } else {
5378 RTC_DCHECK(IsDataContent(&content));
5379 // If we already have an data m= section, reject this extra one.
5380 if (*data_index) {
5381 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005382 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005383 } else {
5384 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005385 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005386 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005387 }
5388 }
htaa2a49d92016-03-04 02:51:39 -08005389 }
deadbeefab9b2d12015-10-14 11:33:11 -07005390}
5391
Steve Antonfa2260d2017-12-28 16:38:23 -08005392cricket::MediaDescriptionOptions
5393PeerConnection::GetMediaDescriptionOptionsForActiveData(
5394 const std::string& mid) const {
5395 // Direction for data sections is meaningless, but legacy endpoints might
5396 // expect sendrecv.
5397 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5398 RtpTransceiverDirection::kSendRecv,
5399 /*stopped=*/false);
5400 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5401 return options;
5402}
5403
5404cricket::MediaDescriptionOptions
5405PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5406 const std::string& mid) const {
5407 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5408 RtpTransceiverDirection::kInactive,
5409 /*stopped=*/true);
5410 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5411 return options;
5412}
5413
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005414absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08005415 switch (data_channel_type_) {
5416 case cricket::DCT_RTP:
5417 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005418 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005419 }
5420 return rtp_data_channel_->content_name();
5421 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005422 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005423 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5424 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5425 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005426 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005427 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005428 }
5429}
5430
Steve Anton4171afb2017-11-20 10:20:22 -08005431void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5432 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5433 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005434 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005435}
5436
Steve Anton4171afb2017-11-20 10:20:22 -08005437void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005438 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005439 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005440 cricket::MediaType media_type,
5441 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005442 RTC_DCHECK(!IsUnifiedPlan());
5443
Steve Anton4171afb2017-11-20 10:20:22 -08005444 std::vector<RtpSenderInfo>* current_senders =
5445 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005446
Steve Anton4171afb2017-11-20 10:20:22 -08005447 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005448 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005449 for (auto sender_it = current_senders->begin();
5450 sender_it != current_senders->end();
5451 /* incremented manually */) {
5452 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005453 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005454 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005455 std::string params_stream_id;
5456 if (params) {
5457 params_stream_id =
5458 (!params->first_stream_id().empty() ? params->first_stream_id()
5459 : kDefaultStreamId);
5460 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005461 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005462 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005463 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005464 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005465 sender_exists) {
5466 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005467 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005468 OnRemoteSenderRemoved(info, media_type);
5469 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005470 }
5471 }
5472
Steve Anton4171afb2017-11-20 10:20:22 -08005473 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005474 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005475 if (!params.has_ssrcs()) {
5476 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5477 // sender, this means it is coming from a Unified Plan endpoint,so we just
5478 // create a default.
5479 default_sender_needed = true;
5480 break;
5481 }
5482
Seth Hampson845e8782018-03-02 11:34:10 -08005483 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005484 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005485 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5486 // not supported in Plan B, we just take the first here and create the
5487 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005488 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005489 (!params.first_stream_id().empty() ? params.first_stream_id()
5490 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005491 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005492 uint32_t ssrc = params.first_ssrc();
5493
5494 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005495 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005496 if (!stream) {
5497 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005498 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005499 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005500 remote_streams_->AddStream(stream);
5501 new_streams->AddStream(stream);
5502 }
5503
Steve Anton4171afb2017-11-20 10:20:22 -08005504 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005505 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005506 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005507 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005508 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005509 }
5510 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005511
Steve Anton4171afb2017-11-20 10:20:22 -08005512 // Add default sender if necessary.
5513 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005514 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005515 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005516 if (!default_stream) {
5517 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005518 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005519 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005520 remote_streams_->AddStream(default_stream);
5521 new_streams->AddStream(default_stream);
5522 }
Steve Anton4171afb2017-11-20 10:20:22 -08005523 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5524 ? kDefaultAudioSenderId
5525 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005526 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005527 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005528 if (!default_sender_info) {
5529 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005530 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005531 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005532 }
5533 }
deadbeefab9b2d12015-10-14 11:33:11 -07005534}
5535
Steve Anton4171afb2017-11-20 10:20:22 -08005536void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5537 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005538 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5539 << " receiver for track_id=" << sender_info.sender_id
5540 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005541
Steve Anton3d954a62018-04-02 11:27:23 -07005542 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005543 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005544 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005545 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005546 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005547 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005548 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005549 }
5550}
5551
Steve Anton4171afb2017-11-20 10:20:22 -08005552void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5553 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005554 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5555 << " receiver for track_id=" << sender_info.sender_id
5556 << " and stream_id=" << sender_info.stream_id;
5557
Seth Hampson845e8782018-03-02 11:34:10 -08005558 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005559
Henrik Boström933d8b02017-10-10 10:05:16 -07005560 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005561 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005562 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5563 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005564 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005565 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005566 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005567 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005568 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005569 }
5570 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005571 // Stopping or destroying a VideoRtpReceiver will end the
5572 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005573 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005574 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005575 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005576 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005577 // There's no guarantee the track is still available, e.g. the track may
5578 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005579 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005580 }
5581 } else {
nisseede5da42017-01-12 05:15:36 -08005582 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005583 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005584 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005585 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005586 }
deadbeefab9b2d12015-10-14 11:33:11 -07005587}
5588
5589void PeerConnection::UpdateEndedRemoteMediaStreams() {
5590 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5591 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5592 MediaStreamInterface* stream = remote_streams_->at(i);
5593 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5594 streams_to_remove.push_back(stream);
5595 }
5596 }
5597
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005598 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005599 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005600 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005601 }
5602}
5603
Steve Anton4171afb2017-11-20 10:20:22 -08005604void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005605 const std::vector<cricket::StreamParams>& streams,
5606 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005607 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005608
Seth Hampson845e8782018-03-02 11:34:10 -08005609 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005610 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005611 for (auto sender_it = current_senders->begin();
5612 sender_it != current_senders->end();
5613 /* incremented manually */) {
5614 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005615 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005616 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5617 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005618 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005619 OnLocalSenderRemoved(info, media_type);
5620 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005621 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005622 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005623 }
5624 }
5625
Steve Anton4171afb2017-11-20 10:20:22 -08005626 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005627 for (const cricket::StreamParams& params : streams) {
5628 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005629 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005630 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005631 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005632 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005633 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005634 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005635 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005636 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005637 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005638 }
5639 }
5640}
5641
Steve Anton4171afb2017-11-20 10:20:22 -08005642void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5643 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005644 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005645 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005646 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005647 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5648 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005649 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005650 return;
5651 }
5652
deadbeeffac06552015-11-25 11:26:01 -08005653 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005654 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005655 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005656 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005657 }
deadbeeffac06552015-11-25 11:26:01 -08005658
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005659 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005660 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005661}
5662
Steve Anton4171afb2017-11-20 10:20:22 -08005663void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5664 cricket::MediaType media_type) {
5665 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005666 if (!sender) {
5667 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005668 // SessionDescriptions has been renegotiated.
5669 return;
5670 }
deadbeeffac06552015-11-25 11:26:01 -08005671
5672 // A sender has been removed from the SessionDescription but it's still
5673 // associated with the PeerConnection. This only occurs if the SDP doesn't
5674 // match with the calls to CreateSender, AddStream and RemoveStream.
5675 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005676 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005677 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005678 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005679 }
deadbeeffac06552015-11-25 11:26:01 -08005680
Steve Anton4171afb2017-11-20 10:20:22 -08005681 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005682}
5683
5684void PeerConnection::UpdateLocalRtpDataChannels(
5685 const cricket::StreamParamsVec& streams) {
5686 std::vector<std::string> existing_channels;
5687
5688 // Find new and active data channels.
5689 for (const cricket::StreamParams& params : streams) {
5690 // |it->sync_label| is actually the data channel label. The reason is that
5691 // we use the same naming of data channels as we do for
5692 // MediaStreams and Tracks.
5693 // For MediaStreams, the sync_label is the MediaStream label and the
5694 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005695 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005696 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005697 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005698 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005699 continue;
5700 }
5701 // Set the SSRC the data channel should use for sending.
5702 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5703 existing_channels.push_back(data_channel_it->first);
5704 }
5705
5706 UpdateClosingRtpDataChannels(existing_channels, true);
5707}
5708
5709void PeerConnection::UpdateRemoteRtpDataChannels(
5710 const cricket::StreamParamsVec& streams) {
5711 std::vector<std::string> existing_channels;
5712
5713 // Find new and active data channels.
5714 for (const cricket::StreamParams& params : streams) {
5715 // The data channel label is either the mslabel or the SSRC if the mslabel
5716 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005717 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005718 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005719 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005720 auto data_channel_it = rtp_data_channels_.find(label);
5721 if (data_channel_it == rtp_data_channels_.end()) {
5722 // This is a new data channel.
5723 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5724 } else {
5725 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5726 }
5727 existing_channels.push_back(label);
5728 }
5729
5730 UpdateClosingRtpDataChannels(existing_channels, false);
5731}
5732
5733void PeerConnection::UpdateClosingRtpDataChannels(
5734 const std::vector<std::string>& active_channels,
5735 bool is_local_update) {
5736 auto it = rtp_data_channels_.begin();
5737 while (it != rtp_data_channels_.end()) {
5738 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005739 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005740 ++it;
5741 continue;
5742 }
5743
5744 if (is_local_update) {
5745 data_channel->SetSendSsrc(0);
5746 } else {
5747 data_channel->RemotePeerRequestClose();
5748 }
5749
5750 if (data_channel->state() == DataChannel::kClosed) {
5751 rtp_data_channels_.erase(it);
5752 it = rtp_data_channels_.begin();
5753 } else {
5754 ++it;
5755 }
5756 }
5757}
5758
5759void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5760 uint32_t remote_ssrc) {
5761 rtc::scoped_refptr<DataChannel> channel(
5762 InternalCreateDataChannel(label, nullptr));
5763 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005764 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005765 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005766 return;
5767 }
5768 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005769 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5770 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005771 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005772}
5773
5774rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5775 const std::string& label,
5776 const InternalDataChannelInit* config) {
5777 if (IsClosed()) {
5778 return nullptr;
5779 }
Steve Anton75737c02017-11-06 10:37:17 -08005780 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005781 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005782 << "InternalCreateDataChannel: Data is not supported in this call.";
5783 return nullptr;
5784 }
5785 InternalDataChannelInit new_config =
5786 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005787 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005788 if (new_config.id < 0) {
5789 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005790 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005791 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005792 RTC_LOG(LS_ERROR)
5793 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005794 return nullptr;
5795 }
5796 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005797 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005798 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005799 return nullptr;
5800 }
5801 }
5802
Steve Anton75737c02017-11-06 10:37:17 -08005803 rtc::scoped_refptr<DataChannel> channel(
5804 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005805 if (!channel) {
5806 sid_allocator_.ReleaseSid(new_config.id);
5807 return nullptr;
5808 }
5809
5810 if (channel->data_channel_type() == cricket::DCT_RTP) {
5811 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005812 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5813 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005814 return nullptr;
5815 }
5816 rtp_data_channels_[channel->label()] = channel;
5817 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005818 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005819 sctp_data_channels_.push_back(channel);
5820 channel->SignalClosed.connect(this,
5821 &PeerConnection::OnSctpDataChannelClosed);
5822 }
5823
Steve Anton2d8609c2018-01-23 16:38:46 -08005824 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005825 return channel;
5826}
5827
5828bool PeerConnection::HasDataChannels() const {
5829 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5830}
5831
5832void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005833 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005834 for (const auto& channel : sctp_data_channels_) {
5835 if (channel->id() < 0) {
5836 int sid;
5837 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005838 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5839 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005840 continue;
5841 }
5842 channel->SetSctpSid(sid);
5843 }
5844 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005845 // Since closing modifies the list of channels, we have to do the actual
5846 // closing outside the loop.
5847 for (const auto& channel : channels_to_close) {
5848 channel->CloseAbruptly();
5849 }
deadbeefab9b2d12015-10-14 11:33:11 -07005850}
5851
5852void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005853 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005854 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5855 ++it) {
5856 if (it->get() == channel) {
5857 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005858 // After the closing procedure is done, it's safe to use this ID for
5859 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005860 sid_allocator_.ReleaseSid(channel->id());
5861 }
deadbeefbd292462015-12-14 18:15:29 -08005862 // Since this method is triggered by a signal from the DataChannel,
5863 // we can't free it directly here; we need to free it asynchronously.
5864 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005865 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005866 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5867 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005868 return;
5869 }
5870 }
5871}
5872
deadbeefab9b2d12015-10-14 11:33:11 -07005873void PeerConnection::OnDataChannelDestroyed() {
5874 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5875 // DataChannel may callback to us and try to modify the list.
5876 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5877 temp_rtp_dcs.swap(rtp_data_channels_);
5878 for (const auto& kv : temp_rtp_dcs) {
5879 kv.second->OnTransportChannelDestroyed();
5880 }
5881
5882 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5883 temp_sctp_dcs.swap(sctp_data_channels_);
5884 for (const auto& channel : temp_sctp_dcs) {
5885 channel->OnTransportChannelDestroyed();
5886 }
5887}
5888
5889void PeerConnection::OnDataChannelOpenMessage(
5890 const std::string& label,
5891 const InternalDataChannelInit& config) {
5892 rtc::scoped_refptr<DataChannel> channel(
5893 InternalCreateDataChannel(label, &config));
5894 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005895 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005896 return;
5897 }
5898
deadbeefa601f5c2016-06-06 14:27:39 -07005899 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5900 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005901 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005902 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005903}
5904
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005905bool PeerConnection::HandleOpenMessage_s(
5906 const cricket::ReceiveDataParams& params,
5907 const rtc::CopyOnWriteBuffer& buffer) {
5908 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5909 // Received OPEN message; parse and signal that a new data channel should
5910 // be created.
5911 std::string label;
5912 InternalDataChannelInit config;
5913 config.id = params.ssrc;
5914 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5915 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5916 << params.ssrc;
5917 return true;
5918 }
5919 config.open_handshake_role = InternalDataChannelInit::kAcker;
5920 OnDataChannelOpenMessage(label, config);
5921 return true;
5922 }
5923 return false;
5924}
5925
Steve Anton4171afb2017-11-20 10:20:22 -08005926rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5927PeerConnection::GetAudioTransceiver() const {
5928 // This method only works with Plan B SDP, where there is a single
5929 // audio/video transceiver.
5930 RTC_DCHECK(!IsUnifiedPlan());
5931 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005932 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005933 return transceiver;
5934 }
5935 }
5936 RTC_NOTREACHED();
5937 return nullptr;
5938}
5939
5940rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5941PeerConnection::GetVideoTransceiver() const {
5942 // This method only works with Plan B SDP, where there is a single
5943 // audio/video transceiver.
5944 RTC_DCHECK(!IsUnifiedPlan());
5945 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005946 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005947 return transceiver;
5948 }
5949 }
5950 RTC_NOTREACHED();
5951 return nullptr;
5952}
5953
5954// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5955// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005956bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005957 switch (type) {
5958 case cricket::MEDIA_TYPE_AUDIO:
5959 return !GetAudioTransceiver()->internal()->senders().empty();
5960 case cricket::MEDIA_TYPE_VIDEO:
5961 return !GetVideoTransceiver()->internal()->senders().empty();
5962 case cricket::MEDIA_TYPE_DATA:
5963 return false;
5964 }
5965 RTC_NOTREACHED();
5966 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005967}
5968
Steve Anton4171afb2017-11-20 10:20:22 -08005969rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5970PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005971 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005972 for (auto sender : transceiver->internal()->senders()) {
5973 if (sender->track() == track) {
5974 return sender;
5975 }
5976 }
5977 }
5978 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005979}
5980
Steve Anton4171afb2017-11-20 10:20:22 -08005981rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5982PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005983 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005984 for (auto sender : transceiver->internal()->senders()) {
5985 if (sender->id() == sender_id) {
5986 return sender;
5987 }
5988 }
5989 }
5990 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005991}
5992
Steve Anton4171afb2017-11-20 10:20:22 -08005993rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5994PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005995 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005996 for (auto receiver : transceiver->internal()->receivers()) {
5997 if (receiver->id() == receiver_id) {
5998 return receiver;
5999 }
6000 }
6001 }
6002 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07006003}
6004
Steve Anton4171afb2017-11-20 10:20:22 -08006005std::vector<PeerConnection::RtpSenderInfo>*
6006PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
6007 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6008 media_type == cricket::MEDIA_TYPE_VIDEO);
6009 return (media_type == cricket::MEDIA_TYPE_AUDIO)
6010 ? &remote_audio_sender_infos_
6011 : &remote_video_sender_infos_;
6012}
6013
6014std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07006015 cricket::MediaType media_type) {
6016 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6017 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08006018 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
6019 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07006020}
6021
Steve Anton4171afb2017-11-20 10:20:22 -08006022const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
6023 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00006024 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08006025 const std::string sender_id) const {
6026 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00006027 if (sender_info.stream_id == stream_id &&
6028 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08006029 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07006030 }
6031 }
6032 return nullptr;
6033}
6034
6035DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
6036 for (const auto& channel : sctp_data_channels_) {
6037 if (channel->id() == sid) {
6038 return channel;
6039 }
6040 }
6041 return nullptr;
6042}
6043
Karl Wibergfb3be392019-03-22 14:13:22 +01006044PeerConnection::InitializePortAllocatorResult
6045PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02006046 const cricket::ServerAddresses& stun_servers,
6047 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006048 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006049 RTC_DCHECK_RUN_ON(network_thread());
6050
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07006051 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006052 // To handle both internal and externally created port allocator, we will
6053 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01006054 int port_allocator_flags = port_allocator_->flags();
6055 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
6056 cricket::PORTALLOCATOR_ENABLE_IPV6 |
6057 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006058 // If the disable-IPv6 flag was specified, we'll not override it
6059 // by experiment.
6060 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006061 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08006062 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
6063 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006064 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006065 }
6066
zhihuangb09b3f92017-03-07 14:40:51 -08006067 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006068 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01006069 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08006070 }
6071
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006072 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006073 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01006074 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006075 }
6076
honghaiz60347052016-05-31 18:29:12 -07006077 if (configuration.candidate_network_policy ==
6078 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006079 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01006080 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07006081 }
6082
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01006083 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006084 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01006085 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
6086 }
6087
Karl Wibergfb3be392019-03-22 14:13:22 +01006088 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006089 // No step delay is used while allocating ports.
6090 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07006091 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006092 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07006093 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006094
Harald Alvestrandb2a74782018-06-28 13:54:07 +02006095 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07006096 for (auto& turn_server : turn_servers_copy) {
6097 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07006098 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006099 // Call this last since it may create pooled allocator sessions using the
6100 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006101 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07006102 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006103 configuration.ice_candidate_pool_size,
6104 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006105 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01006106
6107 InitializePortAllocatorResult res;
6108 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
6109 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006110}
6111
deadbeef91dd5672016-05-18 16:55:30 -07006112bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08006113 const cricket::ServerAddresses& stun_servers,
6114 const std::vector<cricket::RelayServerConfig>& turn_servers,
6115 IceTransportsType type,
6116 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006117 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006118 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02006119 absl::optional<int> stun_candidate_keepalive_interval,
6120 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07006121 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08006122 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07006123 // According to JSEP, after setLocalDescription, changing the candidate pool
6124 // size is not allowed, and changing the set of ICE servers will not result
6125 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02006126 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07006127 port_allocator_->FreezeCandidatePool();
6128 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07006129 // Add the custom tls turn servers if they exist.
6130 auto turn_servers_copy = turn_servers;
6131 for (auto& turn_server : turn_servers_copy) {
6132 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
6133 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006134 // Call this last since it may create pooled allocator sessions using the
6135 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08006136 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07006137 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006138 turn_port_prune_policy, turn_customizer,
6139 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006140}
6141
Steve Antonba818672017-11-06 10:21:57 -08006142cricket::ChannelManager* PeerConnection::channel_manager() const {
6143 return factory_->channel_manager();
6144}
6145
Elad Alon99c3fe52017-10-13 16:29:40 +02006146bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01006147 std::unique_ptr<RtcEventLogOutput> output,
6148 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01006149 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006150 if (!event_log_) {
6151 return false;
6152 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01006153 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07006154}
6155
6156void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01006157 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006158 if (event_log_) {
6159 event_log_->StopLogging();
6160 }
ivoc14d5dbe2016-07-04 07:06:55 -07006161}
nisseeaabdf62017-05-05 02:23:02 -07006162
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006163cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08006164 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006165 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006166 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08006167 if (channel && channel->content_name() == content_name) {
6168 return channel;
6169 }
Steve Anton75737c02017-11-06 10:37:17 -08006170 }
6171 if (rtp_data_channel() &&
6172 rtp_data_channel()->content_name() == content_name) {
6173 return rtp_data_channel();
6174 }
6175 return nullptr;
6176}
6177
6178bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006179 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006180 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006181 RTC_LOG(LS_INFO)
6182 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006183 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006184 return false;
6185 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006186 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006187 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006188 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006189 return false;
6190 }
6191
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006192 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006193 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006194 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006195 if (!dtls_role && is_caller_.has_value()) {
6196 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
6197 }
Zhi Huange830e682018-03-30 10:48:35 -07006198 *role = *dtls_role;
6199 return true;
6200 }
6201 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006202}
6203
6204bool PeerConnection::GetSslRole(const std::string& content_name,
6205 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006206 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006207 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006208 RTC_LOG(LS_INFO)
6209 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006210 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08006211 return false;
6212 }
6213
Zhi Huange830e682018-03-30 10:48:35 -07006214 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
6215 if (dtls_role) {
6216 *role = *dtls_role;
6217 return true;
6218 }
6219 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006220}
6221
Steve Antonf8470812017-12-04 10:46:21 -08006222void PeerConnection::SetSessionError(SessionError error,
6223 const std::string& error_desc) {
6224 RTC_DCHECK_RUN_ON(signaling_thread());
6225 if (error != session_error_) {
6226 session_error_ = error;
6227 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08006228 }
6229}
6230
Zhi Huange830e682018-03-30 10:48:35 -07006231RTCError PeerConnection::UpdateSessionState(
6232 SdpType type,
6233 cricket::ContentSource source,
6234 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08006235 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006236
6237 // If there's already a pending error then no state transition should happen.
6238 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08006239 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006240
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006241 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08006242 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08006243 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006244 }
6245
6246 // Update the signaling state according to the specified state machine (see
6247 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08006248 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006249 ChangeSignalingState(source == cricket::CS_LOCAL
6250 ? PeerConnectionInterface::kHaveLocalOffer
6251 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08006252 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006253 ChangeSignalingState(source == cricket::CS_LOCAL
6254 ? PeerConnectionInterface::kHaveLocalPrAnswer
6255 : PeerConnectionInterface::kHaveRemotePrAnswer);
6256 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006257 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006258 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03006259 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006260 }
6261
6262 // Update internal objects according to the session description's media
6263 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07006264 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006265 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08006266 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006267 }
6268
Steve Anton8a006912017-12-04 15:25:56 -08006269 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006270}
6271
Steve Anton8a006912017-12-04 15:25:56 -08006272RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08006273 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08006274 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08006275 const SessionDescriptionInterface* sdesc =
6276 (source == cricket::CS_LOCAL ? local_description()
6277 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08006278 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08006279
6280 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01006281 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08006282 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08006283 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006284 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006285 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08006286 continue;
6287 }
6288 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006289 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006290 if (!content_desc) {
6291 continue;
6292 }
6293 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02006294 bool success = (source == cricket::CS_LOCAL)
6295 ? channel->SetLocalContent(content_desc, type, &error)
6296 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006297 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006299 }
6300 }
6301
6302 // If using the RtpDataChannel, push down the new SDP section for it too.
6303 if (rtp_data_channel_) {
6304 const ContentInfo* data_content =
6305 cricket::GetFirstDataContent(sdesc->description());
6306 if (data_content && !data_content->rejected) {
6307 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006308 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006309 if (data_desc) {
6310 std::string error;
6311 bool success =
6312 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08006313 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02006314 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006315 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006317 }
Steve Anton75737c02017-11-06 10:37:17 -08006318 }
6319 }
6320 }
Steve Antoned10bd92017-12-05 10:52:59 -08006321
Steve Anton75737c02017-11-06 10:37:17 -08006322 // Need complete offer/answer with an SCTP m= section before starting SCTP,
6323 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006324 if (sctp_mid_ && local_description() && remote_description()) {
6325 rtc::scoped_refptr<SctpTransport> sctp_transport =
6326 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006327 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
6328 local_description()->description());
6329 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
6330 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006331 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02006332 int max_message_size;
6333 // A remote max message size of zero means "any size supported".
6334 // We configure the connection with our own max message size.
6335 if (remote_sctp_description->max_message_size() == 0) {
6336 max_message_size = local_sctp_description->max_message_size();
6337 } else {
6338 max_message_size =
6339 std::min(local_sctp_description->max_message_size(),
6340 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006341 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006342 sctp_transport->Start(local_sctp_description->port(),
6343 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08006344 }
Steve Anton75737c02017-11-06 10:37:17 -08006345 }
Steve Antoned10bd92017-12-05 10:52:59 -08006346
Steve Anton8a006912017-12-04 15:25:56 -08006347 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006348}
6349
Steve Anton8a006912017-12-04 15:25:56 -08006350RTCError PeerConnection::PushdownTransportDescription(
6351 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08006352 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08006353 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006354
Zhi Huange830e682018-03-30 10:48:35 -07006355 if (source == cricket::CS_LOCAL) {
6356 const SessionDescriptionInterface* sdesc = local_description();
6357 RTC_DCHECK(sdesc);
6358 return transport_controller_->SetLocalDescription(type,
6359 sdesc->description());
6360 } else {
6361 const SessionDescriptionInterface* sdesc = remote_description();
6362 RTC_DCHECK(sdesc);
6363 return transport_controller_->SetRemoteDescription(type,
6364 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006365 }
Steve Anton75737c02017-11-06 10:37:17 -08006366}
6367
6368bool PeerConnection::GetTransportDescription(
6369 const SessionDescription* description,
6370 const std::string& content_name,
6371 cricket::TransportDescription* tdesc) {
6372 if (!description || !tdesc) {
6373 return false;
6374 }
6375 const TransportInfo* transport_info =
6376 description->GetTransportInfoByName(content_name);
6377 if (!transport_info) {
6378 return false;
6379 }
6380 *tdesc = transport_info->description;
6381 return true;
6382}
6383
Steve Anton75737c02017-11-06 10:37:17 -08006384cricket::IceConfig PeerConnection::ParseIceConfig(
6385 const PeerConnectionInterface::RTCConfiguration& config) const {
6386 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006387 switch (config.continual_gathering_policy) {
6388 case PeerConnectionInterface::GATHER_ONCE:
6389 gathering_policy = cricket::GATHER_ONCE;
6390 break;
6391 case PeerConnectionInterface::GATHER_CONTINUALLY:
6392 gathering_policy = cricket::GATHER_CONTINUALLY;
6393 break;
6394 default:
6395 RTC_NOTREACHED();
6396 gathering_policy = cricket::GATHER_ONCE;
6397 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006398
Steve Anton75737c02017-11-06 10:37:17 -08006399 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006400 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6401 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006402 ice_config.prioritize_most_likely_candidate_pairs =
6403 config.prioritize_most_likely_ice_candidate_pairs;
6404 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006405 RTCConfigurationToIceConfigOptionalInt(
6406 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006407 ice_config.continual_gathering_policy = gathering_policy;
6408 ice_config.presume_writable_when_fully_relayed =
6409 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006410 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6411 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006412 ice_config.ice_check_interval_strong_connectivity =
6413 config.ice_check_interval_strong_connectivity;
6414 ice_config.ice_check_interval_weak_connectivity =
6415 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006416 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006417 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6418 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006419 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006420 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08006421 ice_config.regather_all_networks_interval_range =
6422 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006423 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006424 return ice_config;
6425}
6426
Steve Anton75737c02017-11-06 10:37:17 -08006427bool PeerConnection::SendData(const cricket::SendDataParams& params,
6428 const rtc::CopyOnWriteBuffer& payload,
6429 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006430 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006431 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006432 SendDataParams send_params;
6433 send_params.type = ToWebrtcDataMessageType(params.type);
6434 send_params.ordered = params.ordered;
6435 if (params.max_rtx_count >= 0) {
6436 send_params.max_rtx_count = params.max_rtx_count;
6437 } else if (params.max_rtx_ms >= 0) {
6438 send_params.max_rtx_ms = params.max_rtx_ms;
6439 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006440
6441 RTCError error = network_thread()->Invoke<RTCError>(
6442 RTC_FROM_HERE, [this, params, send_params, payload] {
6443 return data_channel_transport_->SendData(params.sid, send_params,
6444 payload);
6445 });
6446
6447 if (error.ok()) {
6448 *result = cricket::SendDataResult::SDR_SUCCESS;
6449 return true;
6450 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6451 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6452 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6453 *result = cricket::SendDataResult::SDR_BLOCK;
6454 return false;
6455 }
6456 *result = cricket::SendDataResult::SDR_ERROR;
6457 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006458 } else if (rtp_data_channel_) {
6459 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006460 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006461 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6462 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006463}
6464
6465bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006466 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006467 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006468 // Don't log an error here, because DataChannels are expected to call
6469 // ConnectDataChannel in this state. It's the only way to initially tell
6470 // whether or not the underlying transport is ready.
6471 return false;
6472 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006473 if (data_channel_transport_) {
6474 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6475 &DataChannel::OnChannelReady);
6476 SignalDataChannelTransportReceivedData_s.connect(
6477 webrtc_data_channel, &DataChannel::OnDataReceived);
6478 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006479 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006480 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006481 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006482 }
6483 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006484 rtp_data_channel_->SignalReadyToSendData.connect(
6485 webrtc_data_channel, &DataChannel::OnChannelReady);
6486 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6487 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006488 }
Steve Anton75737c02017-11-06 10:37:17 -08006489 return true;
6490}
6491
6492void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006493 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006494 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006495 RTC_LOG(LS_ERROR)
6496 << "DisconnectDataChannel called when rtp_data_channel_ and "
6497 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006498 return;
6499 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006500 if (data_channel_transport_) {
6501 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6502 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6503 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6504 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6505 }
6506 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006507 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6508 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006509 }
Steve Anton75737c02017-11-06 10:37:17 -08006510}
6511
6512void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006513 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006514 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6515 if (data_channel_transport_) {
6516 data_channel_transport_->OpenChannel(sid);
6517 }
6518 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006519 }
Steve Anton75737c02017-11-06 10:37:17 -08006520}
6521
6522void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006523 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006524 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6525 if (data_channel_transport_) {
6526 data_channel_transport_->CloseChannel(sid);
6527 }
6528 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006529 }
Steve Anton75737c02017-11-06 10:37:17 -08006530}
6531
6532bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006533 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006534 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006535 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006536}
6537
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006538void PeerConnection::OnDataReceived(int channel_id,
6539 DataMessageType type,
6540 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006541 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006542 cricket::ReceiveDataParams params;
6543 params.sid = channel_id;
6544 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006545 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006546 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6547 RTC_DCHECK_RUN_ON(signaling_thread());
6548 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006549 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006550 }
6551 });
6552}
6553
6554void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006555 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006556 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006557 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6558 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006559 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006560 });
6561}
6562
6563void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006564 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006565 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006566 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6567 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006568 SignalDataChannelTransportChannelClosed_s(channel_id);
6569 });
6570}
6571
6572void PeerConnection::OnReadyToSend() {
6573 RTC_DCHECK_RUN_ON(network_thread());
6574 data_channel_transport_invoker_->AsyncInvoke<void>(
6575 RTC_FROM_HERE, signaling_thread(), [this] {
6576 RTC_DCHECK_RUN_ON(signaling_thread());
6577 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006578 SignalDataChannelTransportWritable_s(
6579 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006580 });
6581}
6582
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006583absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006584 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006585 if (sctp_mid_ && transport_controller_) {
6586 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6587 if (dtls_transport) {
6588 return dtls_transport->transport_name();
6589 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006590 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006591 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006592 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006593}
6594
Qingsi Wang72a43a12018-02-20 16:03:18 -08006595cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6596 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006597 network_thread()->Invoke<void>(
6598 RTC_FROM_HERE,
6599 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6600 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006601 return candidate_states_list;
6602}
6603
Steve Anton5dfde182018-02-06 10:34:40 -08006604std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6605 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006606 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006607 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006608 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006609 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006610 if (channel) {
6611 transport_names_by_mid[channel->content_name()] =
6612 channel->transport_name();
6613 }
Steve Anton75737c02017-11-06 10:37:17 -08006614 }
Steve Anton5dfde182018-02-06 10:34:40 -08006615 if (rtp_data_channel_) {
6616 transport_names_by_mid[rtp_data_channel_->content_name()] =
6617 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006618 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006619 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006620 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006621 RTC_DCHECK(transport_name);
6622 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006623 }
Steve Anton5dfde182018-02-06 10:34:40 -08006624 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006625}
6626
Steve Anton5dfde182018-02-06 10:34:40 -08006627std::map<std::string, cricket::TransportStats>
6628PeerConnection::GetTransportStatsByNames(
6629 const std::set<std::string>& transport_names) {
6630 if (!network_thread()->IsCurrent()) {
6631 return network_thread()
6632 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6633 RTC_FROM_HERE,
6634 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006635 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006636 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006637 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6638 for (const std::string& transport_name : transport_names) {
6639 cricket::TransportStats transport_stats;
6640 bool success =
6641 transport_controller_->GetStats(transport_name, &transport_stats);
6642 if (success) {
6643 transport_stats_by_name[transport_name] = std::move(transport_stats);
6644 } else {
6645 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6646 << transport_name;
6647 }
6648 }
6649 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006650}
6651
6652bool PeerConnection::GetLocalCertificate(
6653 const std::string& transport_name,
6654 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006655 if (!certificate) {
6656 return false;
6657 }
6658 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6659 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006660}
6661
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006662std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006663 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006664 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006665}
6666
6667cricket::DataChannelType PeerConnection::data_channel_type() const {
6668 return data_channel_type_;
6669}
6670
6671bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006672 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006673 return pending_ice_restarts_.find(content_name) !=
6674 pending_ice_restarts_.end();
6675}
6676
Steve Anton75737c02017-11-06 10:37:17 -08006677bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6678 return transport_controller_->NeedsIceRestart(content_name);
6679}
6680
6681void PeerConnection::OnCertificateReady(
6682 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6683 transport_controller_->SetLocalCertificate(certificate);
6684}
6685
6686void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006687 SetSessionError(SessionError::kTransport,
6688 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006689}
6690
Alex Loiko9289eda2018-11-23 16:18:59 +00006691void PeerConnection::OnTransportControllerConnectionState(
6692 cricket::IceConnectionState state) {
6693 switch (state) {
6694 case cricket::kIceConnectionConnecting:
6695 // If the current state is Connected or Completed, then there were
6696 // writable channels but now there are not, so the next state must
6697 // be Disconnected.
6698 // kIceConnectionConnecting is currently used as the default,
6699 // un-connected state by the TransportController, so its only use is
6700 // detecting disconnections.
6701 if (ice_connection_state_ ==
6702 PeerConnectionInterface::kIceConnectionConnected ||
6703 ice_connection_state_ ==
6704 PeerConnectionInterface::kIceConnectionCompleted) {
6705 SetIceConnectionState(
6706 PeerConnectionInterface::kIceConnectionDisconnected);
6707 }
6708 break;
6709 case cricket::kIceConnectionFailed:
6710 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6711 break;
6712 case cricket::kIceConnectionConnected:
6713 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6714 "all transports are writable.";
6715 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6716 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6717 break;
6718 case cricket::kIceConnectionCompleted:
6719 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6720 "all transports are complete.";
6721 if (ice_connection_state_ !=
6722 PeerConnectionInterface::kIceConnectionConnected) {
6723 // If jumping directly from "checking" to "connected",
6724 // signal "connected" first.
6725 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6726 }
6727 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6728 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6729 ReportTransportStats();
6730 break;
6731 default:
6732 RTC_NOTREACHED();
6733 }
6734}
6735
Steve Anton75737c02017-11-06 10:37:17 -08006736void PeerConnection::OnTransportControllerCandidatesGathered(
6737 const std::string& transport_name,
6738 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006739 int sdp_mline_index;
6740 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006741 RTC_LOG(LS_ERROR)
6742 << "OnTransportControllerCandidatesGathered: content name "
6743 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006744 return;
6745 }
6746
6747 for (cricket::Candidates::const_iterator citer = candidates.begin();
6748 citer != candidates.end(); ++citer) {
6749 // Use transport_name as the candidate media id.
6750 std::unique_ptr<JsepIceCandidate> candidate(
6751 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6752 if (local_description()) {
6753 mutable_local_description()->AddCandidate(candidate.get());
6754 }
6755 OnIceCandidate(std::move(candidate));
6756 }
6757}
6758
Eldar Relloda13ea22019-06-01 12:23:43 +03006759void PeerConnection::OnTransportControllerCandidateError(
6760 const cricket::IceCandidateErrorEvent& event) {
6761 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6762 event.error_text);
6763}
6764
Steve Anton75737c02017-11-06 10:37:17 -08006765void PeerConnection::OnTransportControllerCandidatesRemoved(
6766 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006767 // Sanity check.
6768 for (const cricket::Candidate& candidate : candidates) {
6769 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006770 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006771 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006772 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006773 return;
6774 }
6775 }
6776
6777 if (local_description()) {
6778 mutable_local_description()->RemoveCandidates(candidates);
6779 }
6780 OnIceCandidatesRemoved(candidates);
6781}
6782
Alex Drake00c7ecf2019-08-06 10:54:47 -07006783void PeerConnection::OnTransportControllerCandidateChanged(
6784 const cricket::CandidatePairChangeEvent& event) {
6785 OnSelectedCandidatePairChanged(event);
6786}
6787
Steve Anton75737c02017-11-06 10:37:17 -08006788void PeerConnection::OnTransportControllerDtlsHandshakeError(
6789 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006790 RTC_HISTOGRAM_ENUMERATION(
6791 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6792 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006793}
6794
Steve Antoned10bd92017-12-05 10:52:59 -08006795void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006796 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006797 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006798 if (channel && !channel->enabled()) {
6799 channel->Enable(true);
6800 }
Steve Anton75737c02017-11-06 10:37:17 -08006801 }
6802
Steve Anton4171afb2017-11-20 10:20:22 -08006803 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006804 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006805 }
Steve Anton75737c02017-11-06 10:37:17 -08006806}
6807
6808// Returns the media index for a local ice candidate given the content name.
6809bool PeerConnection::GetLocalCandidateMediaIndex(
6810 const std::string& content_name,
6811 int* sdp_mline_index) {
6812 if (!local_description() || !sdp_mline_index) {
6813 return false;
6814 }
6815
6816 bool content_found = false;
6817 const ContentInfos& contents = local_description()->description()->contents();
6818 for (size_t index = 0; index < contents.size(); ++index) {
6819 if (contents[index].name == content_name) {
6820 *sdp_mline_index = static_cast<int>(index);
6821 content_found = true;
6822 break;
6823 }
6824 }
6825 return content_found;
6826}
6827
6828bool PeerConnection::UseCandidatesInSessionDescription(
6829 const SessionDescriptionInterface* remote_desc) {
6830 if (!remote_desc) {
6831 return true;
6832 }
6833 bool ret = true;
6834
6835 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6836 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6837 for (size_t n = 0; n < candidates->count(); ++n) {
6838 const IceCandidateInterface* candidate = candidates->at(n);
6839 bool valid = false;
6840 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6841 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006842 RTC_LOG(LS_INFO)
6843 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006844 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006845 }
6846 continue;
6847 }
6848 ret = UseCandidate(candidate);
6849 if (!ret) {
6850 break;
6851 }
6852 }
6853 }
6854 return ret;
6855}
6856
6857bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006858 RTCErrorOr<const cricket::ContentInfo*> result =
6859 FindContentInfo(remote_description(), candidate);
6860 if (!result.ok()) {
6861 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6862 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006863 return false;
6864 }
Steve Anton75737c02017-11-06 10:37:17 -08006865 std::vector<cricket::Candidate> candidates;
6866 candidates.push_back(candidate->candidate());
6867 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006868 RTCError error = transport_controller_->AddRemoteCandidates(
6869 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006870 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006871 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006872 // Candidates successfully submitted for checking.
6873 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6874 ice_connection_state_ ==
6875 PeerConnectionInterface::kIceConnectionDisconnected) {
6876 // If state is New, then the session has just gotten its first remote ICE
6877 // candidates, so go to Checking.
6878 // If state is Disconnected, the session is re-using old candidates or
6879 // receiving additional ones, so go to Checking.
6880 // If state is Connected, stay Connected.
6881 // TODO(bemasc): If state is Connected, and the new candidates are for a
6882 // newly added transport, then the state actually _should_ move to
6883 // checking. Add a way to distinguish that case.
6884 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6885 }
6886 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006887 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006888 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006889 }
6890 return true;
6891}
6892
Guido Urdaneta41633172019-05-23 20:12:29 +02006893RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6894 const SessionDescriptionInterface* description,
6895 const IceCandidateInterface* candidate) {
6896 if (candidate->sdp_mline_index() >= 0) {
6897 size_t mediacontent_index =
6898 static_cast<size_t>(candidate->sdp_mline_index());
6899 size_t content_size = description->description()->contents().size();
6900 if (mediacontent_index < content_size) {
6901 return &description->description()->contents()[mediacontent_index];
6902 } else {
6903 return RTCError(RTCErrorType::INVALID_RANGE,
6904 "Media line index (" +
6905 rtc::ToString(candidate->sdp_mline_index()) +
6906 ") out of range (number of mlines: " +
6907 rtc::ToString(content_size) + ").");
6908 }
6909 } else if (!candidate->sdp_mid().empty()) {
6910 auto& contents = description->description()->contents();
6911 auto it = absl::c_find_if(
6912 contents, [candidate](const cricket::ContentInfo& content_info) {
6913 return content_info.mid() == candidate->sdp_mid();
6914 });
6915 if (it == contents.end()) {
6916 return RTCError(
6917 RTCErrorType::INVALID_PARAMETER,
6918 "Mid " + candidate->sdp_mid() +
6919 " specified but no media section with that mid found.");
6920 } else {
6921 return &*it;
6922 }
6923 }
6924
6925 return RTCError(RTCErrorType::INVALID_PARAMETER,
6926 "Neither sdp_mline_index nor sdp_mid specified.");
6927}
6928
Steve Anton75737c02017-11-06 10:37:17 -08006929void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006930 // Destroy video channel first since it may have a pointer to the
6931 // voice channel.
6932 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006933 if (!video_info || video_info->rejected) {
6934 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006935 }
6936
Steve Anton6fec8802017-12-04 10:37:29 -08006937 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6938 if (!audio_info || audio_info->rejected) {
6939 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006940 }
6941
6942 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6943 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006944 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006945 }
6946}
6947
Steve Antondcc3c022017-12-22 16:02:54 -08006948RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6949 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006950 const cricket::ContentGroup* bundle_group = nullptr;
6951 if (configuration_.bundle_policy ==
6952 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006953 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006954 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006955 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6956 "max-bundle configured but session description "
6957 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006958 }
6959 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006960 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006961}
6962
6963RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006964 // Creating the media channels. Transports should already have been created
6965 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006966 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006967 if (voice && !voice->rejected &&
6968 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006969 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006970 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006971 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6972 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006973 }
6974 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6975 }
6976
Steve Antondcc3c022017-12-22 16:02:54 -08006977 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006978 if (video && !video->rejected &&
6979 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006980 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006981 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006982 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6983 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006984 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006985 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006986 }
6987
Steve Antondcc3c022017-12-22 16:02:54 -08006988 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006989 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006990 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006991 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006992 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6993 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006994 }
6995 }
6996
Steve Anton8a006912017-12-04 15:25:56 -08006997 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006998}
6999
Steve Anton4171afb2017-11-20 10:20:22 -08007000// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08007001cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07007002 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007003 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007004 MediaTransportConfig media_transport_config =
7005 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007006
Steve Anton75737c02017-11-06 10:37:17 -08007007 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007008 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007009 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7010 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08007011 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08007012 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08007013 }
Steve Anton75737c02017-11-06 10:37:17 -08007014 voice_channel->SignalDtlsSrtpSetupFailure.connect(
7015 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08007016 voice_channel->SignalSentPacket.connect(this,
7017 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07007018 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08007019
Steve Antoneda6ccd2017-12-04 10:21:55 -08007020 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08007021}
7022
Steve Anton4171afb2017-11-20 10:20:22 -08007023// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08007024cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07007025 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007026 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007027 MediaTransportConfig media_transport_config =
7028 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007029
Steve Anton75737c02017-11-06 10:37:17 -08007030 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007031 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007032 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7033 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007034 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08007035 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08007036 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08007037 }
Steve Anton75737c02017-11-06 10:37:17 -08007038 video_channel->SignalDtlsSrtpSetupFailure.connect(
7039 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08007040 video_channel->SignalSentPacket.connect(this,
7041 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07007042 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08007043
Steve Antoneda6ccd2017-12-04 10:21:55 -08007044 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08007045}
7046
Zhi Huange830e682018-03-30 10:48:35 -07007047bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007048 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007049 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00007050 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00007051 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
7052 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007053 if (!network_thread()->Invoke<bool>(
7054 RTC_FROM_HERE,
7055 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
7056 mid))) {
Qingsi Wang437077d2019-09-10 17:52:26 +00007057 return false;
7058 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007059
7060 // All non-RTP data channels must initialize |sctp_data_channels_|.
7061 for (const auto& channel : sctp_data_channels_) {
7062 channel->OnTransportChannelCreated();
7063 }
7064 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007065 case cricket::DCT_RTP:
7066 default:
7067 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
7068 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
7069 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08007070 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007071 if (!rtp_data_channel_) {
7072 return false;
7073 }
7074 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
7075 this, &PeerConnection::OnDtlsSrtpSetupFailure);
7076 rtp_data_channel_->SignalSentPacket.connect(
7077 this, &PeerConnection::OnSentPacket_w);
7078 rtp_data_channel_->SetRtpTransport(rtp_transport);
7079 return true;
Steve Anton75737c02017-11-06 10:37:17 -08007080 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007081 return false;
Steve Anton75737c02017-11-06 10:37:17 -08007082}
7083
7084Call::Stats PeerConnection::GetCallStats() {
7085 if (!worker_thread()->IsCurrent()) {
7086 return worker_thread()->Invoke<Call::Stats>(
7087 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
7088 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007089 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007090 if (call_) {
7091 return call_->GetStats();
7092 } else {
7093 return Call::Stats();
7094 }
7095}
7096
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007097bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007098 DataChannelTransportInterface* transport =
7099 transport_controller_->GetDataChannelTransport(mid);
7100 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08007101 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007102 << "Data channel transport is not available for data channels, mid="
7103 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007104 return false;
7105 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007106 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007107
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007108 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02007109 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007110 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007111
7112 // Note: setting the data sink and checking initial state must be done last,
7113 // after setting up the data channel. Setting the data sink may trigger
7114 // callbacks to PeerConnection which require the transport to be completely
7115 // set up (eg. OnReadyToSend()).
7116 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007117 return true;
7118}
7119
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007120void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007121 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007122 return;
7123 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007124 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
7125 << *sctp_mid_;
7126
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007127 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
7128 // it.
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007129 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +00007130 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007131 if (data_channel_transport_) {
7132 data_channel_transport_->SetDataSink(nullptr);
7133 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007134 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007135}
7136
Steve Anton75737c02017-11-06 10:37:17 -08007137// Returns false if bundle is enabled and rtcp_mux is disabled.
7138bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
7139 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
7140 if (!bundle_enabled)
7141 return true;
7142
7143 const cricket::ContentGroup* bundle_group =
7144 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
7145 RTC_DCHECK(bundle_group != NULL);
7146
7147 const cricket::ContentInfos& contents = desc->contents();
7148 for (cricket::ContentInfos::const_iterator citer = contents.begin();
7149 citer != contents.end(); ++citer) {
7150 const cricket::ContentInfo* content = (&*citer);
7151 RTC_DCHECK(content != NULL);
7152 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08007153 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08007154 if (!HasRtcpMuxEnabled(content))
7155 return false;
7156 }
7157 }
7158 // RTCP-MUX is enabled in all the contents.
7159 return true;
7160}
7161
7162bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08007163 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08007164}
7165
Steve Anton06817cd2018-12-18 15:55:30 -08007166static RTCError ValidateMids(const cricket::SessionDescription& description) {
7167 std::set<std::string> mids;
7168 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08007169 if (content.name.empty()) {
7170 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7171 "A media section is missing a MID attribute.");
7172 }
Steve Anton06817cd2018-12-18 15:55:30 -08007173 if (!mids.insert(content.name).second) {
7174 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7175 "Duplicate a=mid value '" + content.name + "'.");
7176 }
7177 }
7178 return RTCError::OK();
7179}
7180
Steve Anton8a006912017-12-04 15:25:56 -08007181RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08007182 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08007183 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08007184 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08007185 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08007186 }
7187
7188 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08007189 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08007190 }
7191
Steve Anton3828c062017-12-06 10:34:51 -08007192 SdpType type = sdesc->GetType();
7193 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
7194 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08007195 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01007196 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08007197 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08007198 }
7199
Steve Anton06817cd2018-12-18 15:55:30 -08007200 RTCError error = ValidateMids(*sdesc->description());
7201 if (!error.ok()) {
7202 return error;
7203 }
7204
Steve Anton75737c02017-11-06 10:37:17 -08007205 // Verify crypto settings.
7206 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08007207 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
7208 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007209 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08007210 if (!crypto_error.ok()) {
7211 return crypto_error;
7212 }
Steve Anton75737c02017-11-06 10:37:17 -08007213 }
7214
7215 // Verify ice-ufrag and ice-pwd.
7216 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7218 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08007219 }
7220
7221 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007222 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7223 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08007224 }
7225
7226 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
7227 // m-lines that do not rtcp-mux enabled.
7228
7229 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08007230 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007231 // With an answer we want to compare the new answer session description with
7232 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08007233 const cricket::SessionDescription* offer_desc =
7234 (source == cricket::CS_LOCAL) ? remote_description()->description()
7235 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007236 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
7237 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
7238 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007239 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7240 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007241 }
7242 } else {
Steve Anton75737c02017-11-06 10:37:17 -08007243 // The re-offers should respect the order of m= sections in current
7244 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007245 // With a re-offer, either the current local or current remote descriptions
7246 // could be the most up to date, so we would like to check against both of
7247 // them if they exist. It could be the case that one of them has a 0 port
7248 // for a media section, but the other does not. This is important to check
7249 // against in the case that we are recycling an m= section.
7250 const cricket::SessionDescription* current_desc = nullptr;
7251 const cricket::SessionDescription* secondary_current_desc = nullptr;
7252 if (local_description()) {
7253 current_desc = local_description()->description();
7254 if (remote_description()) {
7255 secondary_current_desc = remote_description()->description();
7256 }
7257 } else if (remote_description()) {
7258 current_desc = remote_description()->description();
7259 }
Steve Anton75737c02017-11-06 10:37:17 -08007260 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007261 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
7262 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007263 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7264 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08007265 }
7266 }
7267
Steve Antonba42e992018-04-09 14:10:01 -07007268 if (IsUnifiedPlan()) {
7269 // Ensure that each audio and video media section has at most one
7270 // "StreamParams". This will return an error if receiving a session
7271 // description from a "Plan B" endpoint which adds multiple tracks of the
7272 // same type. With Unified Plan, there can only be at most one track per
7273 // media section.
7274 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02007275 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07007276 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
7277 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
7278 desc.streams().size() > 1u) {
7279 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7280 "Media section has more than one track specified "
7281 "with a=ssrc lines which is not supported with "
7282 "Unified Plan.");
7283 }
7284 }
7285 }
7286
Steve Anton8a006912017-12-04 15:25:56 -08007287 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007288}
7289
Steve Anton3828c062017-12-06 10:34:51 -08007290bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007291 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007292 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007293 return (state == PeerConnectionInterface::kStable) ||
7294 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08007295 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007296 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007297 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7298 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7299 }
7300}
7301
Steve Anton3828c062017-12-06 10:34:51 -08007302bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007303 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007304 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007305 return (state == PeerConnectionInterface::kStable) ||
7306 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08007307 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007308 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007309 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7310 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7311 }
7312}
7313
Steve Antonf8470812017-12-04 10:46:21 -08007314const char* PeerConnection::SessionErrorToString(SessionError error) const {
7315 switch (error) {
7316 case SessionError::kNone:
7317 return "ERROR_NONE";
7318 case SessionError::kContent:
7319 return "ERROR_CONTENT";
7320 case SessionError::kTransport:
7321 return "ERROR_TRANSPORT";
7322 }
7323 RTC_NOTREACHED();
7324 return "";
7325}
7326
Steve Anton75737c02017-11-06 10:37:17 -08007327std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02007328 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08007329 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7330 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02007331 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08007332}
7333
Steve Anton8e20f172018-03-06 10:55:04 -08007334void PeerConnection::ReportSdpFormatReceived(
7335 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08007336 int num_audio_mlines = 0;
7337 int num_video_mlines = 0;
7338 int num_audio_tracks = 0;
7339 int num_video_tracks = 0;
7340 for (const ContentInfo& content : remote_offer.description()->contents()) {
7341 cricket::MediaType media_type = content.media_description()->type();
7342 int num_tracks = std::max(
7343 1, static_cast<int>(content.media_description()->streams().size()));
7344 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7345 num_audio_mlines += 1;
7346 num_audio_tracks += num_tracks;
7347 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7348 num_video_mlines += 1;
7349 num_video_tracks += num_tracks;
7350 }
7351 }
7352 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7353 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7354 format = kSdpFormatReceivedComplexUnifiedPlan;
7355 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7356 format = kSdpFormatReceivedComplexPlanB;
7357 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7358 format = kSdpFormatReceivedSimple;
7359 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007360 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7361 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007362}
7363
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007364void PeerConnection::ReportIceCandidateCollected(
7365 const cricket::Candidate& candidate) {
7366 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7367 if (candidate.address().IsPrivateIP()) {
7368 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7369 }
7370 if (candidate.address().IsUnresolvedIP()) {
7371 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7372 }
7373 if (candidate.address().family() == AF_INET6) {
7374 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7375 }
7376}
7377
7378void PeerConnection::ReportRemoteIceCandidateAdded(
7379 const cricket::Candidate& candidate) {
7380 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7381 if (candidate.address().IsPrivateIP()) {
7382 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7383 }
7384 if (candidate.address().IsUnresolvedIP()) {
7385 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7386 }
7387 if (candidate.address().family() == AF_INET6) {
7388 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7389 }
7390}
7391
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007392void PeerConnection::NoteUsageEvent(UsageEvent event) {
7393 RTC_DCHECK_RUN_ON(signaling_thread());
7394 usage_event_accumulator_ |= static_cast<int>(event);
7395}
7396
7397void PeerConnection::ReportUsagePattern() const {
7398 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007399 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7400 usage_event_accumulator_,
7401 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007402 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007403 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007404 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7405 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007406 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007407 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7408 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7409 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7410 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007411 // If called after close(), we can't report, because observer may have
7412 // been deallocated, and therefore pointer is null. Write to log instead.
7413 if (observer_) {
7414 Observer()->OnInterestingUsage(usage_event_accumulator_);
7415 } else {
7416 RTC_LOG(LS_INFO) << "Interesting usage signature "
7417 << usage_event_accumulator_
7418 << " observed after observer shutdown";
7419 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007420 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007421}
7422
Steve Anton0ffaaa22018-02-23 10:31:30 -08007423void PeerConnection::ReportNegotiatedSdpSemantics(
7424 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007425 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007426 switch (answer.description()->msid_signaling()) {
7427 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007428 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007429 break;
7430 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007431 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007432 break;
7433 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007434 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007435 break;
7436 case cricket::kMsidSignalingMediaSection |
7437 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007438 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007439 break;
7440 default:
7441 RTC_NOTREACHED();
7442 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007443 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7444 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007445}
7446
Steve Anton75737c02017-11-06 10:37:17 -08007447// We need to check the local/remote description for the Transport instead of
7448// the session, because a new Transport added during renegotiation may have
7449// them unset while the session has them set from the previous negotiation.
7450// Not doing so may trigger the auto generation of transport description and
7451// mess up DTLS identity information, ICE credential, etc.
7452bool PeerConnection::ReadyToUseRemoteCandidate(
7453 const IceCandidateInterface* candidate,
7454 const SessionDescriptionInterface* remote_desc,
7455 bool* valid) {
7456 *valid = true;
7457
7458 const SessionDescriptionInterface* current_remote_desc =
7459 remote_desc ? remote_desc : remote_description();
7460
7461 if (!current_remote_desc) {
7462 return false;
7463 }
7464
Guido Urdaneta41633172019-05-23 20:12:29 +02007465 RTCErrorOr<const cricket::ContentInfo*> result =
7466 FindContentInfo(current_remote_desc, candidate);
7467 if (!result.ok()) {
7468 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7469 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007470
7471 *valid = false;
7472 return false;
7473 }
7474
Guido Urdaneta41633172019-05-23 20:12:29 +02007475 std::string transport_name = GetTransportName(result.value()->name);
7476 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007477}
7478
7479bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007480 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007481 (dtls_enabled_ ||
7482 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007483}
7484
7485void PeerConnection::OnTransportControllerGatheringState(
7486 cricket::IceGatheringState state) {
7487 RTC_DCHECK(signaling_thread()->IsCurrent());
7488 if (state == cricket::kIceGatheringGathering) {
7489 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7490 } else if (state == cricket::kIceGatheringComplete) {
7491 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7492 }
7493}
7494
7495void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007496 std::map<std::string, std::set<cricket::MediaType>>
7497 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007498 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007499 if (transceiver->internal()->channel()) {
7500 const std::string& transport_name =
7501 transceiver->internal()->channel()->transport_name();
7502 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007503 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007504 }
Steve Anton75737c02017-11-06 10:37:17 -08007505 }
7506 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007507 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7508 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007509 }
Zhi Huange830e682018-03-30 10:48:35 -07007510
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007511 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007512 if (transport_name) {
7513 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007514 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007515 }
Zhi Huange830e682018-03-30 10:48:35 -07007516
Steve Antonc7b964c2018-02-01 14:39:45 -08007517 for (const auto& entry : media_types_by_transport_name) {
7518 const std::string& transport_name = entry.first;
7519 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007520 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007521 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007522 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007523 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007524 }
7525 }
7526}
7527// Walk through the ConnectionInfos to gather best connection usage
7528// for IPv4 and IPv6.
7529void PeerConnection::ReportBestConnectionState(
7530 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007531 for (const cricket::TransportChannelStats& channel_stats :
7532 stats.channel_stats) {
7533 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007534 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007535 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007536 continue;
7537 }
7538
Steve Antonc7b964c2018-02-01 14:39:45 -08007539 const cricket::Candidate& local = connection_info.local_candidate;
7540 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007541
7542 // Increment the counter for IceCandidatePairType.
7543 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7544 (local.type() == RELAY_PORT_TYPE &&
7545 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007546 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7547 GetIceCandidatePairCounter(local, remote),
7548 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007549 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007550 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7551 GetIceCandidatePairCounter(local, remote),
7552 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007553 } else {
7554 RTC_CHECK(0);
7555 }
Steve Anton75737c02017-11-06 10:37:17 -08007556
7557 // Increment the counter for IP type.
7558 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007559 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7560 kBestConnections_IPv4,
7561 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007562 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007563 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7564 kBestConnections_IPv6,
7565 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007566 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007567 RTC_CHECK(!local.address().hostname().empty() &&
7568 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007569 }
7570
7571 return;
7572 }
7573 }
7574}
7575
7576void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007577 const cricket::TransportStats& stats,
7578 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007579 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7580 return;
7581 }
7582
7583 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7584 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7585 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7586 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7587 return;
7588 }
7589
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007590 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7591 for (cricket::MediaType media_type : media_types) {
7592 switch (media_type) {
7593 case cricket::MEDIA_TYPE_AUDIO:
7594 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7595 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7596 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7597 break;
7598 case cricket::MEDIA_TYPE_VIDEO:
7599 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7600 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7601 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7602 break;
7603 case cricket::MEDIA_TYPE_DATA:
7604 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7605 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7606 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7607 break;
7608 default:
7609 RTC_NOTREACHED();
7610 continue;
7611 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007612 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007613 }
7614
7615 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7616 for (cricket::MediaType media_type : media_types) {
7617 switch (media_type) {
7618 case cricket::MEDIA_TYPE_AUDIO:
7619 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7620 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7621 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7622 break;
7623 case cricket::MEDIA_TYPE_VIDEO:
7624 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7625 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7626 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7627 break;
7628 case cricket::MEDIA_TYPE_DATA:
7629 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7630 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7631 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7632 break;
7633 default:
7634 RTC_NOTREACHED();
7635 continue;
7636 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007637 }
Steve Anton75737c02017-11-06 10:37:17 -08007638 }
7639}
7640
7641void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007642 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007643 RTC_DCHECK(call_);
7644 call_->OnSentPacket(sent_packet);
7645}
7646
7647const std::string PeerConnection::GetTransportName(
7648 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007649 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007650 if (channel) {
7651 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007652 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007653 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007654 RTC_DCHECK(sctp_mid_);
7655 if (content_name == *sctp_mid_) {
7656 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007657 }
7658 }
7659 // Return an empty string if failed to retrieve the transport name.
7660 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007661}
7662
Steve Anton6fec8802017-12-04 10:37:29 -08007663void PeerConnection::DestroyTransceiverChannel(
7664 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7665 transceiver) {
7666 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007667
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007668 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007669 if (channel) {
7670 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007671 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007672 }
7673}
7674
7675void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007676 if (rtp_data_channel_) {
7677 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007678 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007679 rtp_data_channel_ = nullptr;
7680 }
7681
7682 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7683 // grab a reference to this PeerConnection. If this is called from the
7684 // PeerConnection destructor, the RefCountedObject vtable will have already
7685 // been destroyed (since it is a subclass of PeerConnection) and using
7686 // rtc::Bind will cause "Pure virtual function called" error to appear.
7687
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007688 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007689 OnDataChannelDestroyed();
7690 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7691 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007692 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007693 });
7694 }
Steve Anton6fec8802017-12-04 10:37:29 -08007695}
7696
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007697void PeerConnection::DestroyChannelInterface(
7698 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007699 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007700 switch (channel->media_type()) {
7701 case cricket::MEDIA_TYPE_AUDIO:
7702 channel_manager()->DestroyVoiceChannel(
7703 static_cast<cricket::VoiceChannel*>(channel));
7704 break;
7705 case cricket::MEDIA_TYPE_VIDEO:
7706 channel_manager()->DestroyVideoChannel(
7707 static_cast<cricket::VideoChannel*>(channel));
7708 break;
7709 case cricket::MEDIA_TYPE_DATA:
7710 channel_manager()->DestroyRtpDataChannel(
7711 static_cast<cricket::RtpDataChannel*>(channel));
7712 break;
7713 default:
7714 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7715 break;
7716 }
Zhi Huange830e682018-03-30 10:48:35 -07007717}
Steve Anton6fec8802017-12-04 10:37:29 -08007718
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007719bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007720 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007721 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007722 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007723 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007724 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007725 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007726 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007727 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007728 auto base_channel = GetChannel(mid);
7729 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007730 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007731 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007732
Karl Wiberg5966c502019-02-21 23:55:09 +01007733 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007734 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007735 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007736
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007737 if (data_channel_transport_ && mid == sctp_mid_ &&
7738 data_channel_transport_ != data_channel_transport) {
7739 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7740 // it's bundled).
7741 data_channel_transport_->SetDataSink(nullptr);
7742 data_channel_transport_ = data_channel_transport;
7743 if (data_channel_transport) {
7744 data_channel_transport->SetDataSink(this);
7745
7746 // There's a new data channel transport. This needs to be signaled to the
7747 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7748 // necessary when bundling is applied.
7749 data_channel_transport_invoker_->AsyncInvoke<void>(
7750 RTC_FROM_HERE, signaling_thread(), [this] {
7751 RTC_DCHECK_RUN_ON(signaling_thread());
7752 for (auto channel : sctp_data_channels_) {
7753 channel->OnTransportChannelCreated();
7754 }
7755 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007756 }
7757 }
7758
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007759 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007760}
7761
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007762void PeerConnection::OnSetStreams() {
7763 RTC_DCHECK_RUN_ON(signaling_thread());
7764 if (IsUnifiedPlan())
7765 UpdateNegotiationNeeded();
7766}
7767
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007768PeerConnectionObserver* PeerConnection::Observer() const {
7769 // In earlier production code, the pointer was not cleared on close,
7770 // which might have led to undefined behavior if the observer was not
7771 // deallocated, or strange crashes if it was.
7772 // We use CHECK in order to catch such behavior if it exists.
7773 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7774 RTC_CHECK(observer_);
7775 return observer_;
7776}
7777
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007778CryptoOptions PeerConnection::GetCryptoOptions() {
7779 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7780 // after it has been removed.
7781 return configuration_.crypto_options.has_value()
7782 ? *configuration_.crypto_options
7783 : factory_->options().crypto_options;
7784}
7785
Harald Alvestrand89061872018-01-02 14:08:34 +01007786void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007787 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007788 if (stats_collector_) {
7789 stats_collector_->ClearCachedStatsReport();
7790 }
7791}
7792
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007793void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007794 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7795 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007796}
7797
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007798void PeerConnection::UpdateNegotiationNeeded() {
7799 RTC_DCHECK_RUN_ON(signaling_thread());
7800 if (!IsUnifiedPlan()) {
7801 Observer()->OnRenegotiationNeeded();
7802 return;
7803 }
7804
7805 // If connection's [[IsClosed]] slot is true, abort these steps.
7806 if (IsClosed())
7807 return;
7808
7809 // If connection's signaling state is not "stable", abort these steps.
7810 if (signaling_state() != kStable)
7811 return;
7812
7813 // NOTE
7814 // The negotiation-needed flag will be updated once the state transitions to
7815 // "stable", as part of the steps for setting an RTCSessionDescription.
7816
7817 // If the result of checking if negotiation is needed is false, clear the
7818 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7819 // to false, and abort these steps.
7820 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7821 if (!is_negotiation_needed) {
7822 is_negotiation_needed_ = false;
7823 return;
7824 }
7825
7826 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7827 // steps.
7828 if (is_negotiation_needed_)
7829 return;
7830
7831 // Set connection's [[NegotiationNeeded]] slot to true.
7832 is_negotiation_needed_ = true;
7833
7834 // Queue a task that runs the following steps:
7835 // If connection's [[IsClosed]] slot is true, abort these steps.
7836 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7837 // Fire an event named negotiationneeded at connection.
7838 Observer()->OnRenegotiationNeeded();
7839}
7840
7841bool PeerConnection::CheckIfNegotiationIsNeeded() {
7842 RTC_DCHECK_RUN_ON(signaling_thread());
7843 // 1. If any implementation-specific negotiation is required, as described at
7844 // the start of this section, return true.
7845
Henrik Boström79b69802019-07-18 11:16:56 +02007846 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7847 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7848 return true;
7849 }
7850
7851 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007852 const SessionDescriptionInterface* description = current_local_description();
7853 if (!description)
7854 return true;
7855
Henrik Boström79b69802019-07-18 11:16:56 +02007856 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007857 // description has been negotiated yet for data, return true.
7858 if (!sctp_data_channels_.empty()) {
7859 if (!cricket::GetFirstDataContent(description->description()->contents()))
7860 return true;
7861 }
7862
Henrik Boström79b69802019-07-18 11:16:56 +02007863 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007864 // following checks:
7865 for (const auto& transceiver : transceivers_) {
7866 const ContentInfo* current_local_msection =
7867 FindTransceiverMSection(transceiver.get(), description);
7868
7869 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7870 transceiver.get(), current_remote_description());
7871
Henrik Boström79b69802019-07-18 11:16:56 +02007872 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007873 // but the associated m= section is not yet rejected in
7874 // connection.[[CurrentLocalDescription]] or
7875 // connection.[[CurrentRemoteDescription]], return true.
7876 if (transceiver->stopped()) {
7877 if (current_local_msection && !current_local_msection->rejected &&
7878 ((current_remote_msection && !current_remote_msection->rejected) ||
7879 !current_remote_msection)) {
7880 return true;
7881 }
7882 continue;
7883 }
7884
Henrik Boström79b69802019-07-18 11:16:56 +02007885 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007886 // section in description, return true.
7887 if (!current_local_msection)
7888 return true;
7889
7890 const MediaContentDescription* current_local_media_description =
7891 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007892 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007893 // in description then perform the following checks:
7894
Henrik Boström79b69802019-07-18 11:16:56 +02007895 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007896 // associated m= section in description either doesn't contain a single
7897 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7898 // m= section, or the MSID values themselves, differ from what is in
7899 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7900 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7901 if (current_local_media_description->streams().size() == 0)
7902 return true;
7903
7904 std::vector<std::string> msection_msids;
7905 for (const auto& stream : current_local_media_description->streams()) {
7906 for (const std::string& msid : stream.stream_ids())
7907 msection_msids.push_back(msid);
7908 }
7909
7910 std::vector<std::string> transceiver_msids =
7911 transceiver->sender()->stream_ids();
7912 if (msection_msids.size() != transceiver_msids.size())
7913 return true;
7914
7915 absl::c_sort(transceiver_msids);
7916 absl::c_sort(msection_msids);
7917 if (transceiver_msids != msection_msids)
7918 return true;
7919 }
7920
Henrik Boström79b69802019-07-18 11:16:56 +02007921 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007922 // associated m= section in neither connection.[[CurrentLocalDescription]]
7923 // nor connection.[[CurrentRemoteDescription]] matches
7924 // transceiver.[[Direction]], return true.
7925 if (description->GetType() == SdpType::kOffer) {
7926 if (!current_remote_description())
7927 return true;
7928
7929 if (!current_remote_msection)
7930 return true;
7931
7932 RtpTransceiverDirection current_local_direction =
7933 current_local_media_description->direction();
7934 RtpTransceiverDirection current_remote_direction =
7935 current_remote_msection->media_description()->direction();
7936 if (transceiver->direction() != current_local_direction &&
7937 transceiver->direction() !=
7938 RtpTransceiverDirectionReversed(current_remote_direction)) {
7939 return true;
7940 }
7941 }
7942
Henrik Boström79b69802019-07-18 11:16:56 +02007943 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007944 // associated m= section in the description does not match
7945 // transceiver.[[Direction]] intersected with the offered direction (as
7946 // described in [JSEP] (section 5.3.1.)), return true.
7947 if (description->GetType() == SdpType::kAnswer) {
7948 if (!remote_description())
7949 return true;
7950
7951 const ContentInfo* offered_remote_msection =
7952 FindTransceiverMSection(transceiver.get(), remote_description());
7953
7954 RtpTransceiverDirection offered_direction =
7955 offered_remote_msection
7956 ? offered_remote_msection->media_description()->direction()
7957 : RtpTransceiverDirection::kInactive;
7958
7959 if (current_local_media_description->direction() !=
7960 (RtpTransceiverDirectionIntersection(
7961 transceiver->direction(),
7962 RtpTransceiverDirectionReversed(offered_direction)))) {
7963 return true;
7964 }
7965 }
7966 }
7967
7968 // If all the preceding checks were performed and true was not returned,
7969 // nothing remains to be negotiated; return false.
7970 return false;
7971}
7972
Eldar Relloead0ec92019-10-21 23:01:31 +03007973RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03007974 auto state = signaling_state();
7975 if (state != PeerConnectionInterface::kHaveLocalOffer &&
7976 state != PeerConnectionInterface::kHaveRemoteOffer) {
7977 return RTCError(RTCErrorType::INVALID_STATE,
7978 "Called in wrong signalingState: " +
7979 GetSignalingStateString(signaling_state()));
7980 }
7981 RTC_DCHECK_RUN_ON(signaling_thread());
7982 RTC_DCHECK(IsUnifiedPlan());
7983
7984 for (auto&& transceivers_stable_state_pair :
7985 transceiver_stable_states_by_transceivers_) {
7986 auto transceiver = transceivers_stable_state_pair.first;
7987 auto state = transceivers_stable_state_pair.second;
7988 RTC_DCHECK(transceiver->internal()->mid().has_value());
7989 std::string mid = transceiver->internal()->mid().value();
7990 transport_controller_->RollbackTransportForMid(mid);
7991 DestroyTransceiverChannel(transceiver);
7992
Eldar Relloead0ec92019-10-21 23:01:31 +03007993 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
7994 transceiver->receiver()) {
7995 Observer()->OnRemoveTrack(transceiver->receiver());
7996 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007997 if (state.newly_created()) {
7998 // Remove added transceivers with no added track.
7999 if (transceiver->internal()->sender()->track()) {
8000 transceiver->internal()->set_created_by_addtrack(true);
8001 } else {
8002 int remaining_transceiver_count = 0;
8003 for (auto&& t : transceivers_) {
8004 if (t != transceiver) {
8005 transceivers_[remaining_transceiver_count++] = t;
8006 }
8007 }
8008 transceivers_.resize(remaining_transceiver_count);
8009 }
8010 }
8011 transceiver->internal()->sender_internal()->set_transport(nullptr);
8012 transceiver->internal()->receiver_internal()->set_transport(nullptr);
8013 transceiver->internal()->set_direction(state.direction());
8014 transceiver->internal()->set_mid(state.mid());
8015 transceiver->internal()->set_mline_index(state.mline_index());
8016 }
8017 transceiver_stable_states_by_transceivers_.clear();
8018 pending_local_description_.reset();
8019 pending_remote_description_.reset();
8020 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 23:01:31 +03008021
8022 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
8023 // gets called in SetRemoteDescription.
8024 if (sdp_type == SdpType::kRollback) {
8025 UpdateNegotiationNeeded();
8026 if (is_negotiation_needed_) {
8027 Observer()->OnRenegotiationNeeded();
8028 }
8029 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03008030 return RTCError::OK();
8031}
8032
henrike@webrtc.org28e20752013-07-10 00:45:36 +00008033} // namespace webrtc