blob: ea3d8e26510194a688a3098a85ebca5abe16353e [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()) {
philipel01294f02019-11-14 13:03:25 +01004150 cricket::VideoMediaChannel* video_channel = video_media_channel();
4151 if (video_channel) {
4152 video_channel->SetVideoCodecSwitchingEnabled(
4153 *modified_config.allow_codec_switching);
4154 }
philipel16cec3b2019-10-25 12:23:02 +02004155 }
4156
deadbeef293e9262017-01-11 12:28:30 -08004157 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01004158 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02004159 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00004160}
4161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004162bool PeerConnection::AddIceCandidate(
4163 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004164 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004165 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07004166 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004167 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004168 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07004169 return false;
4170 }
Steve Antond25da372017-11-06 14:50:29 -08004171
4172 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004173 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004174 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004175 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08004176 return false;
4177 }
4178
4179 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07004180 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004181 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08004182 return false;
4183 }
4184
4185 bool valid = false;
4186 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
4187 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004188 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08004189 return false;
4190 }
4191
4192 // Add this candidate to the remote session description.
4193 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07004194 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004195 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08004196 return false;
4197 }
4198
4199 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004200 bool result = UseCandidate(ice_candidate);
4201 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004202 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02004203 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
4204 } else {
4205 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
4206 }
4207 return result;
Steve Antond25da372017-11-06 14:50:29 -08004208 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07004209 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004210 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08004211 return true;
4212 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004213}
4214
Henrik Boströmee6f4f62019-11-06 12:36:12 +01004215void PeerConnection::AddIceCandidate(
4216 std::unique_ptr<IceCandidateInterface> candidate,
4217 std::function<void(RTCError)> callback) {
4218 RTC_DCHECK_RUN_ON(signaling_thread());
4219 // Chain this operation. If asynchronous operations are pending on the chain,
4220 // this operation will be queued to be invoked, otherwise the contents of the
4221 // lambda will execute immediately.
4222 operations_chain_->ChainOperation(
4223 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
4224 candidate = std::move(candidate), callback = std::move(callback)](
4225 std::function<void()> operations_chain_callback) {
4226 if (!this_weak_ptr) {
4227 operations_chain_callback();
4228 callback(RTCError(
4229 RTCErrorType::INVALID_STATE,
4230 "AddIceCandidate failed because the session was shut down"));
4231 return;
4232 }
4233 if (!this_weak_ptr->AddIceCandidate(candidate.get())) {
4234 operations_chain_callback();
4235 // Fail with an error type and message consistent with Chromium.
4236 // TODO(hbos): Fail with error types according to spec.
4237 callback(RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
4238 "Error processing ICE candidate"));
4239 return;
4240 }
4241 operations_chain_callback();
4242 callback(RTCError::OK());
4243 });
4244}
4245
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004246bool PeerConnection::RemoveIceCandidates(
4247 const std::vector<cricket::Candidate>& candidates) {
4248 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004249 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07004250 if (IsClosed()) {
4251 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
4252 return false;
4253 }
4254
Steve Antond25da372017-11-06 14:50:29 -08004255 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004256 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
4257 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08004258 return false;
4259 }
4260
4261 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004262 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08004263 return false;
4264 }
4265
4266 size_t number_removed =
4267 mutable_remote_description()->RemoveCandidates(candidates);
4268 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004269 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07004270 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004271 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01004272 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08004273 }
4274
4275 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07004276 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
4277 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004278 RTC_LOG(LS_ERROR)
4279 << "RemoveIceCandidates: Error when removing remote candidates: "
4280 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08004281 }
4282 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004283}
4284
Niels Möller0c4f7be2018-05-07 14:01:37 +02004285RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07004286 if (!worker_thread()->IsCurrent()) {
4287 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02004288 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07004289 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01004290 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07004291
Niels Möller0c4f7be2018-05-07 14:01:37 +02004292 const bool has_min = bitrate.min_bitrate_bps.has_value();
4293 const bool has_start = bitrate.start_bitrate_bps.has_value();
4294 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07004295 if (has_min && *bitrate.min_bitrate_bps < 0) {
4296 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4297 "min_bitrate_bps <= 0");
4298 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02004299 if (has_start) {
4300 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004301 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004302 "start_bitrate_bps < min_bitrate_bps");
4303 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07004304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4305 "curent_bitrate_bps < 0");
4306 }
4307 }
4308 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02004309 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004310 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004311 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07004312 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
4313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4314 "max_bitrate_bps < min_bitrate_bps");
4315 } else if (*bitrate.max_bitrate_bps < 0) {
4316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4317 "max_bitrate_bps < 0");
4318 }
4319 }
4320
zstein4b979802017-06-02 14:37:37 -07004321 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07004322 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07004323
4324 return RTCError::OK();
4325}
4326
henrika5f6bf242017-11-01 11:06:56 +01004327void PeerConnection::SetAudioPlayout(bool playout) {
4328 if (!worker_thread()->IsCurrent()) {
4329 worker_thread()->Invoke<void>(
4330 RTC_FROM_HERE,
4331 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
4332 return;
4333 }
4334 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004335 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004336 audio_state->SetPlayout(playout);
4337}
4338
4339void PeerConnection::SetAudioRecording(bool recording) {
4340 if (!worker_thread()->IsCurrent()) {
4341 worker_thread()->Invoke<void>(
4342 RTC_FROM_HERE,
4343 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
4344 return;
4345 }
4346 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004347 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004348 audio_state->SetRecording(recording);
4349}
4350
Steve Anton8c0f7a72017-10-03 10:03:10 -07004351std::unique_ptr<rtc::SSLCertificate>
4352PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004353 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
4354 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07004355 return nullptr;
4356 }
Steve Antonf25303e2018-10-16 15:23:31 -07004357 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07004358}
4359
Zhi Huang70b820f2018-01-27 14:16:15 -08004360std::unique_ptr<rtc::SSLCertChain>
4361PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01004362 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08004363 auto audio_transceiver = GetFirstAudioTransceiver();
4364 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08004365 return nullptr;
4366 }
Zhi Huang70b820f2018-01-27 14:16:15 -08004367 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08004368 audio_transceiver->internal()->channel()->transport_name());
4369}
4370
4371rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4372PeerConnection::GetFirstAudioTransceiver() const {
4373 for (auto transceiver : transceivers_) {
4374 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4375 return transceiver;
4376 }
4377 }
4378 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08004379}
4380
Bjorn Tereliusde939432017-11-20 17:38:14 +01004381bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
4382 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01004383 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02004384 RTC_FROM_HERE,
4385 [this, output = std::move(output), output_period_ms]() mutable {
4386 return StartRtcEventLog_w(std::move(output), output_period_ms);
4387 });
ivoc14d5dbe2016-07-04 07:06:55 -07004388}
4389
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004390bool PeerConnection::StartRtcEventLog(
4391 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02004392 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4393 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4394 output_period_ms = 5000;
4395 }
4396 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004397}
4398
ivoc14d5dbe2016-07-04 07:06:55 -07004399void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004400 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004401 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4402}
4403
Harald Alvestrandad88c882018-11-28 16:47:46 +01004404rtc::scoped_refptr<DtlsTransportInterface>
4405PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004406 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004407 return transport_controller_->LookupDtlsTransportByMid(mid);
4408}
4409
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004410rtc::scoped_refptr<DtlsTransport>
4411PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004412 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004413 return transport_controller_->LookupDtlsTransportByMid(mid);
4414}
4415
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004416rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4417 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004418 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004419 if (!sctp_mid_) {
4420 return nullptr;
4421 }
4422 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004423}
4424
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004425const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004426 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004427 return pending_local_description_ ? pending_local_description_.get()
4428 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004429}
4430
4431const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004432 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004433 return pending_remote_description_ ? pending_remote_description_.get()
4434 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004435}
4436
deadbeeffe4a8a42016-12-20 17:56:17 -08004437const SessionDescriptionInterface* PeerConnection::current_local_description()
4438 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004439 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004440 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004441}
4442
4443const SessionDescriptionInterface* PeerConnection::current_remote_description()
4444 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004445 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004446 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004447}
4448
4449const SessionDescriptionInterface* PeerConnection::pending_local_description()
4450 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004451 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004452 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004453}
4454
4455const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4456 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004457 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004458 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004459}
4460
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004461void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004462 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004463 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004464 // Update stats here so that we have the most recent stats for tracks and
4465 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004466 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004467
Steve Anton75737c02017-11-06 10:37:17 -08004468 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004469 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004470
Mirko Bonadei739baf02019-01-27 17:29:42 +01004471 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004472 transceiver->Stop();
4473 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004474
4475 // Ensure that all asynchronous stats requests are completed before destroying
4476 // the transport controller below.
4477 if (stats_collector_) {
4478 stats_collector_->WaitForPendingRequest();
4479 }
4480
4481 // Don't destroy BaseChannels until after stats has been cleaned up so that
4482 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004483 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004484
Qingsi Wang93a84392018-01-30 17:13:09 -08004485 // The event log is used in the transport controller, which must be outlived
4486 // by the former. CreateOffer by the peer connection is implemented
4487 // asynchronously and if the peer connection is closed without resetting the
4488 // WebRTC session description factory, the session description factory would
4489 // call the transport controller.
4490 webrtc_session_desc_factory_.reset();
4491 transport_controller_.reset();
4492
deadbeef42a42632017-03-10 15:18:00 -08004493 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004494 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4495 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004496
Steve Anton978b8762017-09-29 12:15:02 -07004497 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004498 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004499 call_.reset();
4500 // The event log must outlive call (and any other object that uses it).
4501 event_log_.reset();
4502 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004503 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004504 // The .h file says that observer can be discarded after close() returns.
4505 // Make sure this is true.
4506 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004507}
4508
Steve Antonad182762018-09-05 20:22:40 +00004509void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004510 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004511 switch (msg->message_id) {
4512 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4513 SetSessionDescriptionMsg* param =
4514 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4515 param->observer->OnSuccess();
4516 delete param;
4517 break;
4518 }
4519 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4520 SetSessionDescriptionMsg* param =
4521 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4522 param->observer->OnFailure(std::move(param->error));
4523 delete param;
4524 break;
4525 }
4526 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4527 CreateSessionDescriptionMsg* param =
4528 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4529 param->observer->OnFailure(std::move(param->error));
4530 delete param;
4531 break;
4532 }
4533 case MSG_GETSTATS: {
4534 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4535 StatsReports reports;
4536 stats_->GetStats(param->track, &reports);
4537 param->observer->OnComplete(reports);
4538 delete param;
4539 break;
4540 }
4541 case MSG_FREE_DATACHANNELS: {
4542 sctp_data_channels_to_free_.clear();
4543 break;
4544 }
4545 case MSG_REPORT_USAGE_PATTERN: {
4546 ReportUsagePattern();
4547 break;
4548 }
4549 default:
4550 RTC_NOTREACHED() << "Not implemented";
4551 break;
4552 }
4553}
4554
Steve Antonafb0bb72018-02-20 11:35:37 -08004555cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4556 RTC_DCHECK(!IsUnifiedPlan());
4557 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4558 GetAudioTransceiver()->internal()->channel());
4559 if (voice_channel) {
4560 return voice_channel->media_channel();
4561 } else {
4562 return nullptr;
4563 }
4564}
4565
4566cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4567 RTC_DCHECK(!IsUnifiedPlan());
4568 auto* video_channel = static_cast<cricket::VideoChannel*>(
4569 GetVideoTransceiver()->internal()->channel());
4570 if (video_channel) {
4571 return video_channel->media_channel();
4572 } else {
4573 return nullptr;
4574 }
4575}
4576
Steve Anton4171afb2017-11-20 10:20:22 -08004577void PeerConnection::CreateAudioReceiver(
4578 MediaStreamInterface* stream,
4579 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004580 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4581 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004582 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4583 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004584 auto* audio_receiver = new AudioRtpReceiver(
4585 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004586 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004587 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4588 audio_receiver->SetupUnsignaledMediaChannel();
4589 } else {
4590 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4591 }
Steve Antond3679212018-01-17 17:41:02 -08004592 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4593 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004594 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004595 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004596 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004597}
4598
Steve Anton4171afb2017-11-20 10:20:22 -08004599void PeerConnection::CreateVideoReceiver(
4600 MediaStreamInterface* stream,
4601 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004602 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4603 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004604 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4605 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004606 auto* video_receiver = new VideoRtpReceiver(
4607 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004608 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004609 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4610 video_receiver->SetupUnsignaledMediaChannel();
4611 } else {
4612 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4613 }
Steve Antond3679212018-01-17 17:41:02 -08004614 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4615 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004616 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004617 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004618 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004619}
4620
deadbeef70ab1a12015-09-28 16:53:55 -07004621// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4622// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004623rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004624 const RtpSenderInfo& remote_sender_info) {
4625 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4626 if (!receiver) {
4627 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4628 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004629 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004630 }
Steve Anton4171afb2017-11-20 10:20:22 -08004631 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4632 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4633 } else {
4634 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4635 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004636 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004637}
4638
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004639void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4640 MediaStreamInterface* stream) {
4641 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004642 RTC_DCHECK(track);
4643 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004644 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004645 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004646 // We already have a sender for this track, so just change the stream_id
4647 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004648 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004649 return;
4650 }
4651
4652 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004653 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004654 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004655 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004656 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004657 // If the sender has already been configured in SDP, we call SetSsrc,
4658 // which will connect the sender to the underlying transport. This can
4659 // occur if a local session description that contains the ID of the sender
4660 // is set before AddStream is called. It can also occur if the local
4661 // session description is not changed and RemoveStream is called, and
4662 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004663 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004664 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004665 if (sender_info) {
4666 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004667 }
4668}
4669
4670// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4671// indefinitely, when we have unified plan SDP.
4672void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4673 MediaStreamInterface* stream) {
4674 RTC_DCHECK(!IsClosed());
4675 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004676 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004677 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4678 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004679 return;
4680 }
Steve Anton4171afb2017-11-20 10:20:22 -08004681 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004682}
4683
4684void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4685 MediaStreamInterface* stream) {
4686 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004687 RTC_DCHECK(track);
4688 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004689 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004690 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004691 // We already have a sender for this track, so just change the stream_id
4692 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004693 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004694 return;
4695 }
4696
4697 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004698 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004699 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004700 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004701 GetVideoTransceiver()->internal()->AddSender(new_sender);
4702 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004703 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004704 if (sender_info) {
4705 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004706 }
4707}
4708
4709void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4710 MediaStreamInterface* stream) {
4711 RTC_DCHECK(!IsClosed());
4712 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004713 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004714 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4715 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004716 return;
4717 }
Steve Anton4171afb2017-11-20 10:20:22 -08004718 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004719}
4720
Steve Antonba818672017-11-06 10:21:57 -08004721void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004722 if (ice_connection_state_ == new_state) {
4723 return;
4724 }
4725
deadbeefcbecd352015-09-23 11:50:27 -07004726 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004727 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004728 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004729 return;
4730 }
Steve Antonba818672017-11-06 10:21:57 -08004731
Mirko Bonadei675513b2017-11-09 11:09:25 +01004732 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4733 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004734 RTC_DCHECK(ice_connection_state_ !=
4735 PeerConnectionInterface::kIceConnectionClosed);
4736
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004737 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004738 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004739}
4740
Alex Loiko9289eda2018-11-23 16:18:59 +00004741void PeerConnection::SetStandardizedIceConnectionState(
4742 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004743 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004744 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004745 }
4746
4747 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004748 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004749 }
4750
4751 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4752 << standardized_ice_connection_state_ << " => " << new_state;
4753
Alex Loiko9289eda2018-11-23 16:18:59 +00004754 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004755 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004756}
4757
Jonas Olsson635474e2018-10-18 15:58:17 +02004758void PeerConnection::SetConnectionState(
4759 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004760 if (connection_state_ == new_state)
4761 return;
4762 if (IsClosed())
4763 return;
4764 connection_state_ = new_state;
4765 Observer()->OnConnectionChange(new_state);
4766}
4767
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004768void PeerConnection::OnIceGatheringChange(
4769 PeerConnectionInterface::IceGatheringState new_state) {
4770 if (IsClosed()) {
4771 return;
4772 }
4773 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004774 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004775}
4776
jbauch81bf7b02017-03-25 08:31:12 -07004777void PeerConnection::OnIceCandidate(
4778 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004779 if (IsClosed()) {
4780 return;
4781 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004782 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004783 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004784}
4785
Eldar Relloda13ea22019-06-01 12:23:43 +03004786void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4787 const std::string& url,
4788 int error_code,
4789 const std::string& error_text) {
4790 if (IsClosed()) {
4791 return;
4792 }
4793 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4794}
4795
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004796void PeerConnection::OnIceCandidatesRemoved(
4797 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004798 if (IsClosed()) {
4799 return;
4800 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004801 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004802}
4803
Alex Drake00c7ecf2019-08-06 10:54:47 -07004804void PeerConnection::OnSelectedCandidatePairChanged(
4805 const cricket::CandidatePairChangeEvent& event) {
4806 if (IsClosed()) {
4807 return;
4808 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004809
Qingsi Wangcc46b102019-09-12 11:19:01 -07004810 if (event.selected_candidate_pair.local_candidate().type() ==
4811 LOCAL_PORT_TYPE &&
4812 event.selected_candidate_pair.remote_candidate().type() ==
4813 LOCAL_PORT_TYPE) {
4814 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4815 }
4816
Alex Drake00c7ecf2019-08-06 10:54:47 -07004817 Observer()->OnIceSelectedCandidatePairChanged(event);
4818}
4819
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004820void PeerConnection::ChangeSignalingState(
4821 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004822 if (signaling_state_ == signaling_state) {
4823 return;
4824 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004825 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4826 << GetSignalingStateString(signaling_state_)
4827 << " New state: "
4828 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004829 signaling_state_ = signaling_state;
4830 if (signaling_state == kClosed) {
4831 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004832 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004833 standardized_ice_connection_state_ =
4834 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004835 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4836 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004837 if (ice_gathering_state_ != kIceGatheringComplete) {
4838 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004839 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004840 }
4841 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004842 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004843}
4844
deadbeefeb459812015-12-15 19:24:43 -08004845void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4846 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004847 if (IsClosed()) {
4848 return;
4849 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004850 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004851 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004852}
4853
deadbeefeb459812015-12-15 19:24:43 -08004854void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4855 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004856 if (IsClosed()) {
4857 return;
4858 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004859 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004860 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004861}
4862
4863void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4864 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004865 if (IsClosed()) {
4866 return;
4867 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004868 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004869 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004870}
4871
4872void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4873 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004874 if (IsClosed()) {
4875 return;
4876 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004877 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004878 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004879}
4880
Henrik Boström31638672017-11-23 17:48:32 +01004881void PeerConnection::PostSetSessionDescriptionSuccess(
4882 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004883 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4884 signaling_thread()->Post(RTC_FROM_HERE, this,
4885 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004886}
4887
deadbeefab9b2d12015-10-14 11:33:11 -07004888void PeerConnection::PostSetSessionDescriptionFailure(
4889 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004890 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004891 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004892 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4893 msg->error = std::move(error);
4894 signaling_thread()->Post(RTC_FROM_HERE, this,
4895 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004896}
4897
4898void PeerConnection::PostCreateSessionDescriptionFailure(
4899 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004900 RTCError error) {
4901 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004902 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4903 msg->error = std::move(error);
4904 signaling_thread()->Post(RTC_FROM_HERE, this,
4905 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004906}
4907
zhihuang1c378ed2017-08-17 14:10:50 -07004908void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004909 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004910 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004911 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004912
Steve Antondcc3c022017-12-22 16:02:54 -08004913 if (IsUnifiedPlan()) {
4914 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4915 } else {
4916 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4917 }
4918
Steve Antonfa2260d2017-12-28 16:38:23 -08004919 // Intentionally unset the data channel type for RTP data channel with the
4920 // second condition. Otherwise the RTP data channels would be successfully
4921 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4922 // when building with chromium. We want to leave RTP data channels broken, so
4923 // people won't try to use them.
4924 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4925 session_options->data_channel_type = data_channel_type();
4926 }
4927
Steve Antondcc3c022017-12-22 16:02:54 -08004928 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004929 bool ice_restart = offer_answer_options.ice_restart ||
4930 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004931 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004932 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004933 options.transport_options.enable_ice_renomination =
4934 configuration_.enable_ice_renomination;
4935 }
4936
4937 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004938 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004939 session_options->pooled_ice_credentials =
4940 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4941 RTC_FROM_HERE,
4942 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4943 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004944 session_options->offer_extmap_allow_mixed =
4945 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004946
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004947 if (configuration_.use_media_transport ||
4948 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004949 session_options->media_transport_settings =
4950 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4951 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004952
4953 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004954 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004955 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004956 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004957 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004958 if (!params) {
4959 continue;
4960 }
4961 options.transport_options.opaque_parameters = params;
4962 if ((use_datagram_transport_ &&
4963 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4964 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4965 (use_datagram_transport_for_data_channels_ &&
4966 options.type == cricket::MEDIA_TYPE_DATA)) {
4967 options.alt_protocol = params->protocol;
4968 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004969 }
4970 }
4971
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004972 // Allow fallback for using obsolete SCTP syntax.
4973 // Note that the default in |session_options| is true, while
4974 // the default in |options| is false.
4975 session_options->use_obsolete_sctp_sdp =
4976 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004977}
4978
4979void PeerConnection::GetOptionsForPlanBOffer(
4980 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4981 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004982 // Figure out transceiver directional preferences.
4983 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4984 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4985
4986 // By default, generate sendrecv/recvonly m= sections.
4987 bool recv_audio = true;
4988 bool recv_video = true;
4989
4990 // By default, only offer a new m= section if we have media to send with it.
4991 bool offer_new_audio_description = send_audio;
4992 bool offer_new_video_description = send_video;
4993 bool offer_new_data_description = HasDataChannels();
4994
4995 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004996 if (offer_answer_options.offer_to_receive_audio !=
4997 RTCOfferAnswerOptions::kUndefined) {
4998 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004999 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08005000 offer_new_audio_description ||
5001 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005002 }
Steve Antondcc3c022017-12-22 16:02:54 -08005003 if (offer_answer_options.offer_to_receive_video !=
5004 RTCOfferAnswerOptions::kUndefined) {
5005 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005006 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08005007 offer_new_video_description ||
5008 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005009 }
5010
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005011 absl::optional<size_t> audio_index;
5012 absl::optional<size_t> video_index;
5013 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07005014 // If a current description exists, generate m= sections in the same order,
5015 // using the first audio/video/data section that appears and rejecting
5016 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08005017 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07005018 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08005019 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08005020 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5021 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5022 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07005023 }
5024
zhihuang1c378ed2017-08-17 14:10:50 -07005025 // Add audio/video/data m= sections to the end if needed.
5026 if (!audio_index && offer_new_audio_description) {
5027 session_options->media_description_options.push_back(
5028 cricket::MediaDescriptionOptions(
5029 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08005030 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5031 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005032 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07005033 }
zhihuang1c378ed2017-08-17 14:10:50 -07005034 if (!video_index && offer_new_video_description) {
5035 session_options->media_description_options.push_back(
5036 cricket::MediaDescriptionOptions(
5037 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08005038 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5039 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005040 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07005041 }
zhihuang1c378ed2017-08-17 14:10:50 -07005042 if (!data_index && offer_new_data_description) {
5043 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005044 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005045 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005046 }
5047
5048 cricket::MediaDescriptionOptions* audio_media_description_options =
5049 !audio_index ? nullptr
5050 : &session_options->media_description_options[*audio_index];
5051 cricket::MediaDescriptionOptions* video_media_description_options =
5052 !video_index ? nullptr
5053 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005054
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005055 AddPlanBRtpSenderOptions(GetSendersInternal(),
5056 audio_media_description_options,
5057 video_media_description_options,
5058 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005059}
5060
Steve Antondcc3c022017-12-22 16:02:54 -08005061static cricket::MediaDescriptionOptions
5062GetMediaDescriptionOptionsForTransceiver(
5063 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5064 transceiver,
5065 const std::string& mid) {
5066 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08005067 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08005068 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02005069 media_description_options.codec_preferences =
5070 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08005071 // This behavior is specified in JSEP. The gist is that:
5072 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
5073 // sendrecv.
5074 // 2. If the MSID is included, then it must be included in any subsequent
5075 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005076 if (transceiver->stopped() ||
5077 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
5078 !transceiver->internal()->has_ever_been_used_to_send())) {
5079 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08005080 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005081
5082 cricket::SenderOptions sender_options;
5083 sender_options.track_id = transceiver->sender()->id();
5084 sender_options.stream_ids = transceiver->sender()->stream_ids();
5085
5086 // The following sets up RIDs and Simulcast.
5087 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08005088 RtpParameters send_parameters =
5089 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005090 bool has_rids = std::any_of(send_parameters.encodings.begin(),
5091 send_parameters.encodings.end(),
5092 [](const RtpEncodingParameters& encoding) {
5093 return !encoding.rid.empty();
5094 });
5095
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08005096 std::vector<RidDescription> send_rids;
5097 SimulcastLayerList send_layers;
5098 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
5099 if (encoding.rid.empty()) {
5100 continue;
5101 }
5102 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
5103 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
5104 }
5105
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005106 if (has_rids) {
5107 sender_options.rids = send_rids;
5108 }
5109
5110 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005111 // When RIDs are configured, we must set num_sim_layers to 0 to.
5112 // Otherwise, num_sim_layers must be 1 because either there is no
5113 // simulcast, or simulcast is acheived by munging the SDP.
5114 sender_options.num_sim_layers = has_rids ? 0 : 1;
5115 media_description_options.sender_options.push_back(sender_options);
5116
Steve Antondcc3c022017-12-22 16:02:54 -08005117 return media_description_options;
5118}
5119
Steve Anton5c72e712018-12-10 14:25:30 -08005120// Returns the ContentInfo at mline index |i|, or null if none exists.
5121static const ContentInfo* GetContentByIndex(
5122 const SessionDescriptionInterface* sdesc,
5123 size_t i) {
5124 if (!sdesc) {
5125 return nullptr;
5126 }
5127 const ContentInfos& contents = sdesc->description()->contents();
5128 return (i < contents.size() ? &contents[i] : nullptr);
5129}
5130
Steve Antondcc3c022017-12-22 16:02:54 -08005131void PeerConnection::GetOptionsForUnifiedPlanOffer(
5132 const RTCOfferAnswerOptions& offer_answer_options,
5133 cricket::MediaSessionOptions* session_options) {
5134 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
5135 // Offers) and 5.2.2 (Subsequent Offers).
5136 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02005137 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08005138 const ContentInfos& local_contents =
5139 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005140 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005141 const ContentInfos& remote_contents =
5142 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005143 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005144 // The mline indices that can be recycled. New transceivers should reuse these
5145 // slots first.
5146 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08005147 // First, go through each media section that exists in either the local or
5148 // remote description and generate a media section in this offer for the
5149 // associated transceiver. If a media section can be recycled, generate a
5150 // default, rejected media section here that can be later overwritten.
5151 for (size_t i = 0;
5152 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
5153 // Either |local_content| or |remote_content| is non-null.
5154 const ContentInfo* local_content =
5155 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005156 const ContentInfo* current_local_content =
5157 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08005158 const ContentInfo* remote_content =
5159 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005160 const ContentInfo* current_remote_content =
5161 GetContentByIndex(current_remote_description(), i);
5162 bool had_been_rejected =
5163 (current_local_content && current_local_content->rejected) ||
5164 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08005165 const std::string& mid =
5166 (local_content ? local_content->name : remote_content->name);
5167 cricket::MediaType media_type =
5168 (local_content ? local_content->media_description()->type()
5169 : remote_content->media_description()->type());
5170 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5171 media_type == cricket::MEDIA_TYPE_VIDEO) {
5172 auto transceiver = GetAssociatedTransceiver(mid);
5173 RTC_CHECK(transceiver);
5174 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08005175 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005176 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08005177 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08005178 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
5179 RtpTransceiverDirection::kInactive,
5180 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08005181 recycleable_mline_indices.push(i);
5182 } else {
5183 session_options->media_description_options.push_back(
5184 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
5185 // CreateOffer shouldn't really cause any state changes in
5186 // PeerConnection, but we need a way to match new transceivers to new
5187 // media sections in SetLocalDescription and JSEP specifies this is done
5188 // by recording the index of the media section generated for the
5189 // transceiver in the offer.
5190 transceiver->internal()->set_mline_index(i);
5191 }
5192 } else {
5193 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08005194 RTC_CHECK(GetDataMid());
5195 if (had_been_rejected || mid != *GetDataMid()) {
5196 session_options->media_description_options.push_back(
5197 GetMediaDescriptionOptionsForRejectedData(mid));
5198 } else {
5199 session_options->media_description_options.push_back(
5200 GetMediaDescriptionOptionsForActiveData(mid));
5201 }
Steve Antondcc3c022017-12-22 16:02:54 -08005202 }
5203 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08005204
Steve Antondcc3c022017-12-22 16:02:54 -08005205 // Next, look for transceivers that are newly added (that is, are not stopped
5206 // and not associated). Reuse media sections marked as recyclable first,
5207 // otherwise append to the end of the offer. New media sections should be
5208 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005209 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08005210 if (transceiver->mid() || transceiver->stopped()) {
5211 continue;
5212 }
5213 size_t mline_index;
5214 if (!recycleable_mline_indices.empty()) {
5215 mline_index = recycleable_mline_indices.front();
5216 recycleable_mline_indices.pop();
5217 session_options->media_description_options[mline_index] =
5218 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005219 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08005220 } else {
5221 mline_index = session_options->media_description_options.size();
5222 session_options->media_description_options.push_back(
5223 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005224 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08005225 }
5226 // See comment above for why CreateOffer changes the transceiver's state.
5227 transceiver->internal()->set_mline_index(mline_index);
5228 }
Steve Antonfa2260d2017-12-28 16:38:23 -08005229 // Lastly, add a m-section if we have local data channels and an m section
5230 // does not already exist.
5231 if (!GetDataMid() && HasDataChannels()) {
5232 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08005233 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08005234 }
Steve Antondcc3c022017-12-22 16:02:54 -08005235}
5236
5237void PeerConnection::GetOptionsForAnswer(
5238 const RTCOfferAnswerOptions& offer_answer_options,
5239 cricket::MediaSessionOptions* session_options) {
5240 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
5241
5242 if (IsUnifiedPlan()) {
5243 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
5244 } else {
5245 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
5246 }
5247
Steve Antonfa2260d2017-12-28 16:38:23 -08005248 // Intentionally unset the data channel type for RTP data channel. Otherwise
5249 // the RTP data channels would be successfully negotiated by default and the
5250 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
5251 // We want to leave RTP data channels broken, so people won't try to use them.
5252 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
5253 session_options->data_channel_type = data_channel_type();
5254 }
5255
Steve Antondcc3c022017-12-22 16:02:54 -08005256 // Apply ICE renomination flag.
5257 for (auto& options : session_options->media_description_options) {
5258 options.transport_options.enable_ice_renomination =
5259 configuration_.enable_ice_renomination;
5260 }
zhihuang8f65cdf2016-05-06 18:40:30 -07005261
5262 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005263 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02005264 session_options->pooled_ice_credentials =
5265 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
5266 RTC_FROM_HERE,
5267 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
5268 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005269
5270 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005271 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005272 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005273 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005274 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005275 if (!params) {
5276 continue;
5277 }
5278 options.transport_options.opaque_parameters = params;
5279 if ((use_datagram_transport_ &&
5280 (options.type == cricket::MEDIA_TYPE_AUDIO ||
5281 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
5282 (use_datagram_transport_for_data_channels_ &&
5283 options.type == cricket::MEDIA_TYPE_DATA)) {
5284 options.alt_protocol = params->protocol;
5285 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005286 }
5287 }
deadbeefab9b2d12015-10-14 11:33:11 -07005288}
5289
Steve Antondcc3c022017-12-22 16:02:54 -08005290void PeerConnection::GetOptionsForPlanBAnswer(
5291 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07005292 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005293 // Figure out transceiver directional preferences.
5294 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
5295 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
5296
5297 // By default, generate sendrecv/recvonly m= sections. The direction is also
5298 // restricted by the direction in the offer.
5299 bool recv_audio = true;
5300 bool recv_video = true;
5301
5302 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08005303 if (offer_answer_options.offer_to_receive_audio !=
5304 RTCOfferAnswerOptions::kUndefined) {
5305 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08005306 }
Steve Antondcc3c022017-12-22 16:02:54 -08005307 if (offer_answer_options.offer_to_receive_video !=
5308 RTCOfferAnswerOptions::kUndefined) {
5309 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005310 }
5311
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005312 absl::optional<size_t> audio_index;
5313 absl::optional<size_t> video_index;
5314 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08005315
5316 // Generate m= sections that match those in the offer.
5317 // Note that mediasession.cc will handle intersection our preferred
5318 // direction with the offered direction.
5319 GenerateMediaDescriptionOptions(
5320 remote_description(),
5321 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5322 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
5323 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07005324
5325 cricket::MediaDescriptionOptions* audio_media_description_options =
5326 !audio_index ? nullptr
5327 : &session_options->media_description_options[*audio_index];
5328 cricket::MediaDescriptionOptions* video_media_description_options =
5329 !video_index ? nullptr
5330 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005331
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005332 AddPlanBRtpSenderOptions(GetSendersInternal(),
5333 audio_media_description_options,
5334 video_media_description_options,
5335 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005336}
zhihuangaf388472016-11-02 16:49:48 -07005337
Steve Antondcc3c022017-12-22 16:02:54 -08005338void PeerConnection::GetOptionsForUnifiedPlanAnswer(
5339 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
5340 cricket::MediaSessionOptions* session_options) {
5341 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
5342 // Answers) and 5.3.2 (Subsequent Answers).
5343 RTC_DCHECK(remote_description());
5344 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
5345 for (const ContentInfo& content :
5346 remote_description()->description()->contents()) {
5347 cricket::MediaType media_type = content.media_description()->type();
5348 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5349 media_type == cricket::MEDIA_TYPE_VIDEO) {
5350 auto transceiver = GetAssociatedTransceiver(content.name);
5351 RTC_CHECK(transceiver);
5352 session_options->media_description_options.push_back(
5353 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
5354 } else {
5355 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08005356 // Reject all data sections if data channels are disabled.
5357 // Reject a data section if it has already been rejected.
5358 // Reject all data sections except for the first one.
5359 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
5360 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005361 session_options->media_description_options.push_back(
5362 GetMediaDescriptionOptionsForRejectedData(content.name));
5363 } else {
5364 session_options->media_description_options.push_back(
5365 GetMediaDescriptionOptionsForActiveData(content.name));
5366 }
Steve Antondcc3c022017-12-22 16:02:54 -08005367 }
5368 }
htaa2a49d92016-03-04 02:51:39 -08005369}
5370
zhihuang1c378ed2017-08-17 14:10:50 -07005371void PeerConnection::GenerateMediaDescriptionOptions(
5372 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08005373 RtpTransceiverDirection audio_direction,
5374 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005375 absl::optional<size_t>* audio_index,
5376 absl::optional<size_t>* video_index,
5377 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08005378 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005379 for (const cricket::ContentInfo& content :
5380 session_desc->description()->contents()) {
5381 if (IsAudioContent(&content)) {
5382 // If we already have an audio m= section, reject this extra one.
5383 if (*audio_index) {
5384 session_options->media_description_options.push_back(
5385 cricket::MediaDescriptionOptions(
5386 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005387 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005388 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005389 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005390 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005391 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5392 content.name, audio_direction,
5393 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005394 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005395 }
5396 } else if (IsVideoContent(&content)) {
5397 // If we already have an video m= section, reject this extra one.
5398 if (*video_index) {
5399 session_options->media_description_options.push_back(
5400 cricket::MediaDescriptionOptions(
5401 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005402 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005403 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005404 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005405 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005406 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5407 content.name, video_direction,
5408 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005409 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005410 }
5411 } else {
5412 RTC_DCHECK(IsDataContent(&content));
5413 // If we already have an data m= section, reject this extra one.
5414 if (*data_index) {
5415 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005416 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005417 } else {
5418 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005419 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005420 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005421 }
5422 }
htaa2a49d92016-03-04 02:51:39 -08005423 }
deadbeefab9b2d12015-10-14 11:33:11 -07005424}
5425
Steve Antonfa2260d2017-12-28 16:38:23 -08005426cricket::MediaDescriptionOptions
5427PeerConnection::GetMediaDescriptionOptionsForActiveData(
5428 const std::string& mid) const {
5429 // Direction for data sections is meaningless, but legacy endpoints might
5430 // expect sendrecv.
5431 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5432 RtpTransceiverDirection::kSendRecv,
5433 /*stopped=*/false);
5434 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5435 return options;
5436}
5437
5438cricket::MediaDescriptionOptions
5439PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5440 const std::string& mid) const {
5441 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5442 RtpTransceiverDirection::kInactive,
5443 /*stopped=*/true);
5444 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5445 return options;
5446}
5447
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005448absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08005449 switch (data_channel_type_) {
5450 case cricket::DCT_RTP:
5451 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005452 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005453 }
5454 return rtp_data_channel_->content_name();
5455 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005456 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005457 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5458 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5459 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005460 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005461 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005462 }
5463}
5464
Steve Anton4171afb2017-11-20 10:20:22 -08005465void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5466 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5467 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005468 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005469}
5470
Steve Anton4171afb2017-11-20 10:20:22 -08005471void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005472 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005473 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005474 cricket::MediaType media_type,
5475 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005476 RTC_DCHECK(!IsUnifiedPlan());
5477
Steve Anton4171afb2017-11-20 10:20:22 -08005478 std::vector<RtpSenderInfo>* current_senders =
5479 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005480
Steve Anton4171afb2017-11-20 10:20:22 -08005481 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005482 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005483 for (auto sender_it = current_senders->begin();
5484 sender_it != current_senders->end();
5485 /* incremented manually */) {
5486 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005487 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005488 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005489 std::string params_stream_id;
5490 if (params) {
5491 params_stream_id =
5492 (!params->first_stream_id().empty() ? params->first_stream_id()
5493 : kDefaultStreamId);
5494 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005495 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005496 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005497 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005498 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005499 sender_exists) {
5500 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005501 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005502 OnRemoteSenderRemoved(info, media_type);
5503 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005504 }
5505 }
5506
Steve Anton4171afb2017-11-20 10:20:22 -08005507 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005508 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005509 if (!params.has_ssrcs()) {
5510 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5511 // sender, this means it is coming from a Unified Plan endpoint,so we just
5512 // create a default.
5513 default_sender_needed = true;
5514 break;
5515 }
5516
Seth Hampson845e8782018-03-02 11:34:10 -08005517 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005518 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005519 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5520 // not supported in Plan B, we just take the first here and create the
5521 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005522 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005523 (!params.first_stream_id().empty() ? params.first_stream_id()
5524 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005525 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005526 uint32_t ssrc = params.first_ssrc();
5527
5528 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005529 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005530 if (!stream) {
5531 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005532 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005533 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005534 remote_streams_->AddStream(stream);
5535 new_streams->AddStream(stream);
5536 }
5537
Steve Anton4171afb2017-11-20 10:20:22 -08005538 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005539 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005540 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005541 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005542 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005543 }
5544 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005545
Steve Anton4171afb2017-11-20 10:20:22 -08005546 // Add default sender if necessary.
5547 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005548 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005549 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005550 if (!default_stream) {
5551 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005552 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005553 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005554 remote_streams_->AddStream(default_stream);
5555 new_streams->AddStream(default_stream);
5556 }
Steve Anton4171afb2017-11-20 10:20:22 -08005557 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5558 ? kDefaultAudioSenderId
5559 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005560 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005561 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005562 if (!default_sender_info) {
5563 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005564 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005565 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005566 }
5567 }
deadbeefab9b2d12015-10-14 11:33:11 -07005568}
5569
Steve Anton4171afb2017-11-20 10:20:22 -08005570void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5571 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005572 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5573 << " receiver for track_id=" << sender_info.sender_id
5574 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005575
Steve Anton3d954a62018-04-02 11:27:23 -07005576 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005577 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005578 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005579 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005580 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005581 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005582 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005583 }
5584}
5585
Steve Anton4171afb2017-11-20 10:20:22 -08005586void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5587 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005588 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5589 << " receiver for track_id=" << sender_info.sender_id
5590 << " and stream_id=" << sender_info.stream_id;
5591
Seth Hampson845e8782018-03-02 11:34:10 -08005592 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005593
Henrik Boström933d8b02017-10-10 10:05:16 -07005594 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005595 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005596 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5597 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005598 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005599 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005600 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005601 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005602 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005603 }
5604 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005605 // Stopping or destroying a VideoRtpReceiver will end the
5606 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005607 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005608 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005609 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005610 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005611 // There's no guarantee the track is still available, e.g. the track may
5612 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005613 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005614 }
5615 } else {
nisseede5da42017-01-12 05:15:36 -08005616 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005617 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005618 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005619 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005620 }
deadbeefab9b2d12015-10-14 11:33:11 -07005621}
5622
5623void PeerConnection::UpdateEndedRemoteMediaStreams() {
5624 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5625 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5626 MediaStreamInterface* stream = remote_streams_->at(i);
5627 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5628 streams_to_remove.push_back(stream);
5629 }
5630 }
5631
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005632 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005633 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005634 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005635 }
5636}
5637
Steve Anton4171afb2017-11-20 10:20:22 -08005638void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005639 const std::vector<cricket::StreamParams>& streams,
5640 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005641 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005642
Seth Hampson845e8782018-03-02 11:34:10 -08005643 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005644 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005645 for (auto sender_it = current_senders->begin();
5646 sender_it != current_senders->end();
5647 /* incremented manually */) {
5648 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005649 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005650 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5651 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005652 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005653 OnLocalSenderRemoved(info, media_type);
5654 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005655 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005656 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005657 }
5658 }
5659
Steve Anton4171afb2017-11-20 10:20:22 -08005660 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005661 for (const cricket::StreamParams& params : streams) {
5662 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005663 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005664 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005665 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005666 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005667 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005668 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005669 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005670 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005671 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005672 }
5673 }
5674}
5675
Steve Anton4171afb2017-11-20 10:20:22 -08005676void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5677 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005678 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005679 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005680 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005681 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5682 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005683 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005684 return;
5685 }
5686
deadbeeffac06552015-11-25 11:26:01 -08005687 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005688 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005689 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005690 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005691 }
deadbeeffac06552015-11-25 11:26:01 -08005692
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005693 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005694 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005695}
5696
Steve Anton4171afb2017-11-20 10:20:22 -08005697void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5698 cricket::MediaType media_type) {
5699 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005700 if (!sender) {
5701 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005702 // SessionDescriptions has been renegotiated.
5703 return;
5704 }
deadbeeffac06552015-11-25 11:26:01 -08005705
5706 // A sender has been removed from the SessionDescription but it's still
5707 // associated with the PeerConnection. This only occurs if the SDP doesn't
5708 // match with the calls to CreateSender, AddStream and RemoveStream.
5709 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005710 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005711 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005712 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005713 }
deadbeeffac06552015-11-25 11:26:01 -08005714
Steve Anton4171afb2017-11-20 10:20:22 -08005715 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005716}
5717
5718void PeerConnection::UpdateLocalRtpDataChannels(
5719 const cricket::StreamParamsVec& streams) {
5720 std::vector<std::string> existing_channels;
5721
5722 // Find new and active data channels.
5723 for (const cricket::StreamParams& params : streams) {
5724 // |it->sync_label| is actually the data channel label. The reason is that
5725 // we use the same naming of data channels as we do for
5726 // MediaStreams and Tracks.
5727 // For MediaStreams, the sync_label is the MediaStream label and the
5728 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005729 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005730 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005731 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005732 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005733 continue;
5734 }
5735 // Set the SSRC the data channel should use for sending.
5736 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5737 existing_channels.push_back(data_channel_it->first);
5738 }
5739
5740 UpdateClosingRtpDataChannels(existing_channels, true);
5741}
5742
5743void PeerConnection::UpdateRemoteRtpDataChannels(
5744 const cricket::StreamParamsVec& streams) {
5745 std::vector<std::string> existing_channels;
5746
5747 // Find new and active data channels.
5748 for (const cricket::StreamParams& params : streams) {
5749 // The data channel label is either the mslabel or the SSRC if the mslabel
5750 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005751 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005752 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005753 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005754 auto data_channel_it = rtp_data_channels_.find(label);
5755 if (data_channel_it == rtp_data_channels_.end()) {
5756 // This is a new data channel.
5757 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5758 } else {
5759 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5760 }
5761 existing_channels.push_back(label);
5762 }
5763
5764 UpdateClosingRtpDataChannels(existing_channels, false);
5765}
5766
5767void PeerConnection::UpdateClosingRtpDataChannels(
5768 const std::vector<std::string>& active_channels,
5769 bool is_local_update) {
5770 auto it = rtp_data_channels_.begin();
5771 while (it != rtp_data_channels_.end()) {
5772 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005773 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005774 ++it;
5775 continue;
5776 }
5777
5778 if (is_local_update) {
5779 data_channel->SetSendSsrc(0);
5780 } else {
5781 data_channel->RemotePeerRequestClose();
5782 }
5783
5784 if (data_channel->state() == DataChannel::kClosed) {
5785 rtp_data_channels_.erase(it);
5786 it = rtp_data_channels_.begin();
5787 } else {
5788 ++it;
5789 }
5790 }
5791}
5792
5793void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5794 uint32_t remote_ssrc) {
5795 rtc::scoped_refptr<DataChannel> channel(
5796 InternalCreateDataChannel(label, nullptr));
5797 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005798 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005799 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005800 return;
5801 }
5802 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005803 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5804 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005805 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005806}
5807
5808rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5809 const std::string& label,
5810 const InternalDataChannelInit* config) {
5811 if (IsClosed()) {
5812 return nullptr;
5813 }
Steve Anton75737c02017-11-06 10:37:17 -08005814 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005815 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005816 << "InternalCreateDataChannel: Data is not supported in this call.";
5817 return nullptr;
5818 }
5819 InternalDataChannelInit new_config =
5820 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005821 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005822 if (new_config.id < 0) {
5823 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005824 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005825 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005826 RTC_LOG(LS_ERROR)
5827 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005828 return nullptr;
5829 }
5830 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005831 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005832 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005833 return nullptr;
5834 }
5835 }
5836
Steve Anton75737c02017-11-06 10:37:17 -08005837 rtc::scoped_refptr<DataChannel> channel(
5838 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005839 if (!channel) {
5840 sid_allocator_.ReleaseSid(new_config.id);
5841 return nullptr;
5842 }
5843
5844 if (channel->data_channel_type() == cricket::DCT_RTP) {
5845 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005846 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5847 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005848 return nullptr;
5849 }
5850 rtp_data_channels_[channel->label()] = channel;
5851 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005852 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005853 sctp_data_channels_.push_back(channel);
5854 channel->SignalClosed.connect(this,
5855 &PeerConnection::OnSctpDataChannelClosed);
5856 }
5857
Steve Anton2d8609c2018-01-23 16:38:46 -08005858 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005859 return channel;
5860}
5861
5862bool PeerConnection::HasDataChannels() const {
5863 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5864}
5865
5866void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005867 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005868 for (const auto& channel : sctp_data_channels_) {
5869 if (channel->id() < 0) {
5870 int sid;
5871 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005872 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5873 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005874 continue;
5875 }
5876 channel->SetSctpSid(sid);
5877 }
5878 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005879 // Since closing modifies the list of channels, we have to do the actual
5880 // closing outside the loop.
5881 for (const auto& channel : channels_to_close) {
5882 channel->CloseAbruptly();
5883 }
deadbeefab9b2d12015-10-14 11:33:11 -07005884}
5885
5886void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005887 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005888 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5889 ++it) {
5890 if (it->get() == channel) {
5891 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005892 // After the closing procedure is done, it's safe to use this ID for
5893 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005894 sid_allocator_.ReleaseSid(channel->id());
5895 }
deadbeefbd292462015-12-14 18:15:29 -08005896 // Since this method is triggered by a signal from the DataChannel,
5897 // we can't free it directly here; we need to free it asynchronously.
5898 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005899 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005900 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5901 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005902 return;
5903 }
5904 }
5905}
5906
deadbeefab9b2d12015-10-14 11:33:11 -07005907void PeerConnection::OnDataChannelDestroyed() {
5908 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5909 // DataChannel may callback to us and try to modify the list.
5910 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5911 temp_rtp_dcs.swap(rtp_data_channels_);
5912 for (const auto& kv : temp_rtp_dcs) {
5913 kv.second->OnTransportChannelDestroyed();
5914 }
5915
5916 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5917 temp_sctp_dcs.swap(sctp_data_channels_);
5918 for (const auto& channel : temp_sctp_dcs) {
5919 channel->OnTransportChannelDestroyed();
5920 }
5921}
5922
5923void PeerConnection::OnDataChannelOpenMessage(
5924 const std::string& label,
5925 const InternalDataChannelInit& config) {
5926 rtc::scoped_refptr<DataChannel> channel(
5927 InternalCreateDataChannel(label, &config));
5928 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005929 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005930 return;
5931 }
5932
deadbeefa601f5c2016-06-06 14:27:39 -07005933 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5934 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005935 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005936 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005937}
5938
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005939bool PeerConnection::HandleOpenMessage_s(
5940 const cricket::ReceiveDataParams& params,
5941 const rtc::CopyOnWriteBuffer& buffer) {
5942 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5943 // Received OPEN message; parse and signal that a new data channel should
5944 // be created.
5945 std::string label;
5946 InternalDataChannelInit config;
5947 config.id = params.ssrc;
5948 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5949 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5950 << params.ssrc;
5951 return true;
5952 }
5953 config.open_handshake_role = InternalDataChannelInit::kAcker;
5954 OnDataChannelOpenMessage(label, config);
5955 return true;
5956 }
5957 return false;
5958}
5959
Steve Anton4171afb2017-11-20 10:20:22 -08005960rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5961PeerConnection::GetAudioTransceiver() const {
5962 // This method only works with Plan B SDP, where there is a single
5963 // audio/video transceiver.
5964 RTC_DCHECK(!IsUnifiedPlan());
5965 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005966 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005967 return transceiver;
5968 }
5969 }
5970 RTC_NOTREACHED();
5971 return nullptr;
5972}
5973
5974rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5975PeerConnection::GetVideoTransceiver() const {
5976 // This method only works with Plan B SDP, where there is a single
5977 // audio/video transceiver.
5978 RTC_DCHECK(!IsUnifiedPlan());
5979 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005980 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005981 return transceiver;
5982 }
5983 }
5984 RTC_NOTREACHED();
5985 return nullptr;
5986}
5987
5988// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5989// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005990bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005991 switch (type) {
5992 case cricket::MEDIA_TYPE_AUDIO:
5993 return !GetAudioTransceiver()->internal()->senders().empty();
5994 case cricket::MEDIA_TYPE_VIDEO:
5995 return !GetVideoTransceiver()->internal()->senders().empty();
5996 case cricket::MEDIA_TYPE_DATA:
5997 return false;
5998 }
5999 RTC_NOTREACHED();
6000 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07006001}
6002
Steve Anton4171afb2017-11-20 10:20:22 -08006003rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
6004PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006005 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08006006 for (auto sender : transceiver->internal()->senders()) {
6007 if (sender->track() == track) {
6008 return sender;
6009 }
6010 }
6011 }
6012 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08006013}
6014
Steve Anton4171afb2017-11-20 10:20:22 -08006015rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
6016PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006017 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08006018 for (auto sender : transceiver->internal()->senders()) {
6019 if (sender->id() == sender_id) {
6020 return sender;
6021 }
6022 }
6023 }
6024 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07006025}
6026
Steve Anton4171afb2017-11-20 10:20:22 -08006027rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
6028PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006029 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08006030 for (auto receiver : transceiver->internal()->receivers()) {
6031 if (receiver->id() == receiver_id) {
6032 return receiver;
6033 }
6034 }
6035 }
6036 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07006037}
6038
Steve Anton4171afb2017-11-20 10:20:22 -08006039std::vector<PeerConnection::RtpSenderInfo>*
6040PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
6041 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6042 media_type == cricket::MEDIA_TYPE_VIDEO);
6043 return (media_type == cricket::MEDIA_TYPE_AUDIO)
6044 ? &remote_audio_sender_infos_
6045 : &remote_video_sender_infos_;
6046}
6047
6048std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07006049 cricket::MediaType media_type) {
6050 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6051 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08006052 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
6053 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07006054}
6055
Steve Anton4171afb2017-11-20 10:20:22 -08006056const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
6057 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00006058 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08006059 const std::string sender_id) const {
6060 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00006061 if (sender_info.stream_id == stream_id &&
6062 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08006063 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07006064 }
6065 }
6066 return nullptr;
6067}
6068
6069DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
6070 for (const auto& channel : sctp_data_channels_) {
6071 if (channel->id() == sid) {
6072 return channel;
6073 }
6074 }
6075 return nullptr;
6076}
6077
Karl Wibergfb3be392019-03-22 14:13:22 +01006078PeerConnection::InitializePortAllocatorResult
6079PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02006080 const cricket::ServerAddresses& stun_servers,
6081 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006082 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006083 RTC_DCHECK_RUN_ON(network_thread());
6084
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07006085 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006086 // To handle both internal and externally created port allocator, we will
6087 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01006088 int port_allocator_flags = port_allocator_->flags();
6089 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
6090 cricket::PORTALLOCATOR_ENABLE_IPV6 |
6091 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006092 // If the disable-IPv6 flag was specified, we'll not override it
6093 // by experiment.
6094 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006095 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08006096 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
6097 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006098 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006099 }
6100
zhihuangb09b3f92017-03-07 14:40:51 -08006101 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006102 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01006103 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08006104 }
6105
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006106 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006107 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01006108 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006109 }
6110
honghaiz60347052016-05-31 18:29:12 -07006111 if (configuration.candidate_network_policy ==
6112 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006113 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01006114 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07006115 }
6116
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01006117 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01006118 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01006119 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
6120 }
6121
Karl Wibergfb3be392019-03-22 14:13:22 +01006122 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006123 // No step delay is used while allocating ports.
6124 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07006125 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006126 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07006127 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006128
Harald Alvestrandb2a74782018-06-28 13:54:07 +02006129 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07006130 for (auto& turn_server : turn_servers_copy) {
6131 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07006132 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006133 // Call this last since it may create pooled allocator sessions using the
6134 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006135 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07006136 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006137 configuration.ice_candidate_pool_size,
6138 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006139 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01006140
6141 InitializePortAllocatorResult res;
6142 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
6143 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006144}
6145
deadbeef91dd5672016-05-18 16:55:30 -07006146bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08006147 const cricket::ServerAddresses& stun_servers,
6148 const std::vector<cricket::RelayServerConfig>& turn_servers,
6149 IceTransportsType type,
6150 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006151 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006152 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02006153 absl::optional<int> stun_candidate_keepalive_interval,
6154 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07006155 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08006156 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07006157 // According to JSEP, after setLocalDescription, changing the candidate pool
6158 // size is not allowed, and changing the set of ICE servers will not result
6159 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02006160 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07006161 port_allocator_->FreezeCandidatePool();
6162 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07006163 // Add the custom tls turn servers if they exist.
6164 auto turn_servers_copy = turn_servers;
6165 for (auto& turn_server : turn_servers_copy) {
6166 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
6167 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006168 // Call this last since it may create pooled allocator sessions using the
6169 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08006170 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07006171 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006172 turn_port_prune_policy, turn_customizer,
6173 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006174}
6175
Steve Antonba818672017-11-06 10:21:57 -08006176cricket::ChannelManager* PeerConnection::channel_manager() const {
6177 return factory_->channel_manager();
6178}
6179
Elad Alon99c3fe52017-10-13 16:29:40 +02006180bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01006181 std::unique_ptr<RtcEventLogOutput> output,
6182 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01006183 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006184 if (!event_log_) {
6185 return false;
6186 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01006187 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07006188}
6189
6190void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01006191 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006192 if (event_log_) {
6193 event_log_->StopLogging();
6194 }
ivoc14d5dbe2016-07-04 07:06:55 -07006195}
nisseeaabdf62017-05-05 02:23:02 -07006196
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006197cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08006198 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006199 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006200 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08006201 if (channel && channel->content_name() == content_name) {
6202 return channel;
6203 }
Steve Anton75737c02017-11-06 10:37:17 -08006204 }
6205 if (rtp_data_channel() &&
6206 rtp_data_channel()->content_name() == content_name) {
6207 return rtp_data_channel();
6208 }
6209 return nullptr;
6210}
6211
6212bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006213 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006214 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006215 RTC_LOG(LS_INFO)
6216 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006217 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006218 return false;
6219 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006220 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006221 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006222 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006223 return false;
6224 }
6225
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006226 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006227 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006228 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006229 if (!dtls_role && is_caller_.has_value()) {
6230 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
6231 }
Zhi Huange830e682018-03-30 10:48:35 -07006232 *role = *dtls_role;
6233 return true;
6234 }
6235 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006236}
6237
6238bool PeerConnection::GetSslRole(const std::string& content_name,
6239 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006240 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006241 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006242 RTC_LOG(LS_INFO)
6243 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006244 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08006245 return false;
6246 }
6247
Zhi Huange830e682018-03-30 10:48:35 -07006248 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
6249 if (dtls_role) {
6250 *role = *dtls_role;
6251 return true;
6252 }
6253 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006254}
6255
Steve Antonf8470812017-12-04 10:46:21 -08006256void PeerConnection::SetSessionError(SessionError error,
6257 const std::string& error_desc) {
6258 RTC_DCHECK_RUN_ON(signaling_thread());
6259 if (error != session_error_) {
6260 session_error_ = error;
6261 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08006262 }
6263}
6264
Zhi Huange830e682018-03-30 10:48:35 -07006265RTCError PeerConnection::UpdateSessionState(
6266 SdpType type,
6267 cricket::ContentSource source,
6268 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08006269 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006270
6271 // If there's already a pending error then no state transition should happen.
6272 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08006273 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006274
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006275 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08006276 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08006277 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006278 }
6279
6280 // Update the signaling state according to the specified state machine (see
6281 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08006282 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006283 ChangeSignalingState(source == cricket::CS_LOCAL
6284 ? PeerConnectionInterface::kHaveLocalOffer
6285 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08006286 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006287 ChangeSignalingState(source == cricket::CS_LOCAL
6288 ? PeerConnectionInterface::kHaveLocalPrAnswer
6289 : PeerConnectionInterface::kHaveRemotePrAnswer);
6290 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006291 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006292 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03006293 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006294 }
6295
6296 // Update internal objects according to the session description's media
6297 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07006298 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006299 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08006300 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006301 }
6302
Steve Anton8a006912017-12-04 15:25:56 -08006303 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006304}
6305
Steve Anton8a006912017-12-04 15:25:56 -08006306RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08006307 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08006308 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08006309 const SessionDescriptionInterface* sdesc =
6310 (source == cricket::CS_LOCAL ? local_description()
6311 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08006312 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08006313
6314 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01006315 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08006316 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08006317 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006318 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006319 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08006320 continue;
6321 }
6322 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006323 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006324 if (!content_desc) {
6325 continue;
6326 }
6327 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02006328 bool success = (source == cricket::CS_LOCAL)
6329 ? channel->SetLocalContent(content_desc, type, &error)
6330 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006331 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006332 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006333 }
6334 }
6335
6336 // If using the RtpDataChannel, push down the new SDP section for it too.
6337 if (rtp_data_channel_) {
6338 const ContentInfo* data_content =
6339 cricket::GetFirstDataContent(sdesc->description());
6340 if (data_content && !data_content->rejected) {
6341 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006342 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006343 if (data_desc) {
6344 std::string error;
6345 bool success =
6346 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08006347 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02006348 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006349 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006350 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006351 }
Steve Anton75737c02017-11-06 10:37:17 -08006352 }
6353 }
6354 }
Steve Antoned10bd92017-12-05 10:52:59 -08006355
Steve Anton75737c02017-11-06 10:37:17 -08006356 // Need complete offer/answer with an SCTP m= section before starting SCTP,
6357 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006358 if (sctp_mid_ && local_description() && remote_description()) {
6359 rtc::scoped_refptr<SctpTransport> sctp_transport =
6360 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006361 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
6362 local_description()->description());
6363 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
6364 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006365 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02006366 int max_message_size;
6367 // A remote max message size of zero means "any size supported".
6368 // We configure the connection with our own max message size.
6369 if (remote_sctp_description->max_message_size() == 0) {
6370 max_message_size = local_sctp_description->max_message_size();
6371 } else {
6372 max_message_size =
6373 std::min(local_sctp_description->max_message_size(),
6374 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006375 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006376 sctp_transport->Start(local_sctp_description->port(),
6377 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08006378 }
Steve Anton75737c02017-11-06 10:37:17 -08006379 }
Steve Antoned10bd92017-12-05 10:52:59 -08006380
Steve Anton8a006912017-12-04 15:25:56 -08006381 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006382}
6383
Steve Anton8a006912017-12-04 15:25:56 -08006384RTCError PeerConnection::PushdownTransportDescription(
6385 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08006386 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08006387 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006388
Zhi Huange830e682018-03-30 10:48:35 -07006389 if (source == cricket::CS_LOCAL) {
6390 const SessionDescriptionInterface* sdesc = local_description();
6391 RTC_DCHECK(sdesc);
6392 return transport_controller_->SetLocalDescription(type,
6393 sdesc->description());
6394 } else {
6395 const SessionDescriptionInterface* sdesc = remote_description();
6396 RTC_DCHECK(sdesc);
6397 return transport_controller_->SetRemoteDescription(type,
6398 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006399 }
Steve Anton75737c02017-11-06 10:37:17 -08006400}
6401
6402bool PeerConnection::GetTransportDescription(
6403 const SessionDescription* description,
6404 const std::string& content_name,
6405 cricket::TransportDescription* tdesc) {
6406 if (!description || !tdesc) {
6407 return false;
6408 }
6409 const TransportInfo* transport_info =
6410 description->GetTransportInfoByName(content_name);
6411 if (!transport_info) {
6412 return false;
6413 }
6414 *tdesc = transport_info->description;
6415 return true;
6416}
6417
Steve Anton75737c02017-11-06 10:37:17 -08006418cricket::IceConfig PeerConnection::ParseIceConfig(
6419 const PeerConnectionInterface::RTCConfiguration& config) const {
6420 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006421 switch (config.continual_gathering_policy) {
6422 case PeerConnectionInterface::GATHER_ONCE:
6423 gathering_policy = cricket::GATHER_ONCE;
6424 break;
6425 case PeerConnectionInterface::GATHER_CONTINUALLY:
6426 gathering_policy = cricket::GATHER_CONTINUALLY;
6427 break;
6428 default:
6429 RTC_NOTREACHED();
6430 gathering_policy = cricket::GATHER_ONCE;
6431 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006432
Steve Anton75737c02017-11-06 10:37:17 -08006433 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006434 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6435 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006436 ice_config.prioritize_most_likely_candidate_pairs =
6437 config.prioritize_most_likely_ice_candidate_pairs;
6438 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006439 RTCConfigurationToIceConfigOptionalInt(
6440 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006441 ice_config.continual_gathering_policy = gathering_policy;
6442 ice_config.presume_writable_when_fully_relayed =
6443 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006444 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6445 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006446 ice_config.ice_check_interval_strong_connectivity =
6447 config.ice_check_interval_strong_connectivity;
6448 ice_config.ice_check_interval_weak_connectivity =
6449 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006450 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006451 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6452 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006453 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006454 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08006455 ice_config.regather_all_networks_interval_range =
6456 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006457 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006458 return ice_config;
6459}
6460
Steve Anton75737c02017-11-06 10:37:17 -08006461bool PeerConnection::SendData(const cricket::SendDataParams& params,
6462 const rtc::CopyOnWriteBuffer& payload,
6463 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006464 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006465 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006466 SendDataParams send_params;
6467 send_params.type = ToWebrtcDataMessageType(params.type);
6468 send_params.ordered = params.ordered;
6469 if (params.max_rtx_count >= 0) {
6470 send_params.max_rtx_count = params.max_rtx_count;
6471 } else if (params.max_rtx_ms >= 0) {
6472 send_params.max_rtx_ms = params.max_rtx_ms;
6473 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006474
6475 RTCError error = network_thread()->Invoke<RTCError>(
6476 RTC_FROM_HERE, [this, params, send_params, payload] {
6477 return data_channel_transport_->SendData(params.sid, send_params,
6478 payload);
6479 });
6480
6481 if (error.ok()) {
6482 *result = cricket::SendDataResult::SDR_SUCCESS;
6483 return true;
6484 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6485 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6486 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6487 *result = cricket::SendDataResult::SDR_BLOCK;
6488 return false;
6489 }
6490 *result = cricket::SendDataResult::SDR_ERROR;
6491 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006492 } else if (rtp_data_channel_) {
6493 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006494 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006495 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6496 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006497}
6498
6499bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006500 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006501 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006502 // Don't log an error here, because DataChannels are expected to call
6503 // ConnectDataChannel in this state. It's the only way to initially tell
6504 // whether or not the underlying transport is ready.
6505 return false;
6506 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006507 if (data_channel_transport_) {
6508 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6509 &DataChannel::OnChannelReady);
6510 SignalDataChannelTransportReceivedData_s.connect(
6511 webrtc_data_channel, &DataChannel::OnDataReceived);
6512 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006513 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006514 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006515 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006516 }
6517 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006518 rtp_data_channel_->SignalReadyToSendData.connect(
6519 webrtc_data_channel, &DataChannel::OnChannelReady);
6520 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6521 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006522 }
Steve Anton75737c02017-11-06 10:37:17 -08006523 return true;
6524}
6525
6526void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006527 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006528 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006529 RTC_LOG(LS_ERROR)
6530 << "DisconnectDataChannel called when rtp_data_channel_ and "
6531 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006532 return;
6533 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006534 if (data_channel_transport_) {
6535 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6536 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6537 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6538 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6539 }
6540 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006541 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6542 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006543 }
Steve Anton75737c02017-11-06 10:37:17 -08006544}
6545
6546void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006547 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006548 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6549 if (data_channel_transport_) {
6550 data_channel_transport_->OpenChannel(sid);
6551 }
6552 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006553 }
Steve Anton75737c02017-11-06 10:37:17 -08006554}
6555
6556void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006557 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006558 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6559 if (data_channel_transport_) {
6560 data_channel_transport_->CloseChannel(sid);
6561 }
6562 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006563 }
Steve Anton75737c02017-11-06 10:37:17 -08006564}
6565
6566bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006567 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006568 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006569 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006570}
6571
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006572void PeerConnection::OnDataReceived(int channel_id,
6573 DataMessageType type,
6574 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006575 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006576 cricket::ReceiveDataParams params;
6577 params.sid = channel_id;
6578 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006579 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006580 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6581 RTC_DCHECK_RUN_ON(signaling_thread());
6582 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006583 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006584 }
6585 });
6586}
6587
6588void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006589 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006590 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006591 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6592 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006593 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006594 });
6595}
6596
6597void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006598 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006599 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006600 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6601 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006602 SignalDataChannelTransportChannelClosed_s(channel_id);
6603 });
6604}
6605
6606void PeerConnection::OnReadyToSend() {
6607 RTC_DCHECK_RUN_ON(network_thread());
6608 data_channel_transport_invoker_->AsyncInvoke<void>(
6609 RTC_FROM_HERE, signaling_thread(), [this] {
6610 RTC_DCHECK_RUN_ON(signaling_thread());
6611 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006612 SignalDataChannelTransportWritable_s(
6613 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006614 });
6615}
6616
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006617absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006618 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006619 if (sctp_mid_ && transport_controller_) {
6620 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6621 if (dtls_transport) {
6622 return dtls_transport->transport_name();
6623 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006624 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006625 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006626 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006627}
6628
Qingsi Wang72a43a12018-02-20 16:03:18 -08006629cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6630 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006631 network_thread()->Invoke<void>(
6632 RTC_FROM_HERE,
6633 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6634 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006635 return candidate_states_list;
6636}
6637
Steve Anton5dfde182018-02-06 10:34:40 -08006638std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6639 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006640 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006641 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006642 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006643 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006644 if (channel) {
6645 transport_names_by_mid[channel->content_name()] =
6646 channel->transport_name();
6647 }
Steve Anton75737c02017-11-06 10:37:17 -08006648 }
Steve Anton5dfde182018-02-06 10:34:40 -08006649 if (rtp_data_channel_) {
6650 transport_names_by_mid[rtp_data_channel_->content_name()] =
6651 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006652 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006653 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006654 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006655 RTC_DCHECK(transport_name);
6656 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006657 }
Steve Anton5dfde182018-02-06 10:34:40 -08006658 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006659}
6660
Steve Anton5dfde182018-02-06 10:34:40 -08006661std::map<std::string, cricket::TransportStats>
6662PeerConnection::GetTransportStatsByNames(
6663 const std::set<std::string>& transport_names) {
6664 if (!network_thread()->IsCurrent()) {
6665 return network_thread()
6666 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6667 RTC_FROM_HERE,
6668 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006669 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006670 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006671 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6672 for (const std::string& transport_name : transport_names) {
6673 cricket::TransportStats transport_stats;
6674 bool success =
6675 transport_controller_->GetStats(transport_name, &transport_stats);
6676 if (success) {
6677 transport_stats_by_name[transport_name] = std::move(transport_stats);
6678 } else {
6679 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6680 << transport_name;
6681 }
6682 }
6683 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006684}
6685
6686bool PeerConnection::GetLocalCertificate(
6687 const std::string& transport_name,
6688 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006689 if (!certificate) {
6690 return false;
6691 }
6692 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6693 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006694}
6695
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006696std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006697 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006698 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006699}
6700
6701cricket::DataChannelType PeerConnection::data_channel_type() const {
6702 return data_channel_type_;
6703}
6704
6705bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006706 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006707 return pending_ice_restarts_.find(content_name) !=
6708 pending_ice_restarts_.end();
6709}
6710
Steve Anton75737c02017-11-06 10:37:17 -08006711bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6712 return transport_controller_->NeedsIceRestart(content_name);
6713}
6714
6715void PeerConnection::OnCertificateReady(
6716 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6717 transport_controller_->SetLocalCertificate(certificate);
6718}
6719
6720void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006721 SetSessionError(SessionError::kTransport,
6722 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006723}
6724
Alex Loiko9289eda2018-11-23 16:18:59 +00006725void PeerConnection::OnTransportControllerConnectionState(
6726 cricket::IceConnectionState state) {
6727 switch (state) {
6728 case cricket::kIceConnectionConnecting:
6729 // If the current state is Connected or Completed, then there were
6730 // writable channels but now there are not, so the next state must
6731 // be Disconnected.
6732 // kIceConnectionConnecting is currently used as the default,
6733 // un-connected state by the TransportController, so its only use is
6734 // detecting disconnections.
6735 if (ice_connection_state_ ==
6736 PeerConnectionInterface::kIceConnectionConnected ||
6737 ice_connection_state_ ==
6738 PeerConnectionInterface::kIceConnectionCompleted) {
6739 SetIceConnectionState(
6740 PeerConnectionInterface::kIceConnectionDisconnected);
6741 }
6742 break;
6743 case cricket::kIceConnectionFailed:
6744 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6745 break;
6746 case cricket::kIceConnectionConnected:
6747 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6748 "all transports are writable.";
6749 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6750 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6751 break;
6752 case cricket::kIceConnectionCompleted:
6753 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6754 "all transports are complete.";
6755 if (ice_connection_state_ !=
6756 PeerConnectionInterface::kIceConnectionConnected) {
6757 // If jumping directly from "checking" to "connected",
6758 // signal "connected" first.
6759 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6760 }
6761 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6762 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6763 ReportTransportStats();
6764 break;
6765 default:
6766 RTC_NOTREACHED();
6767 }
6768}
6769
Steve Anton75737c02017-11-06 10:37:17 -08006770void PeerConnection::OnTransportControllerCandidatesGathered(
6771 const std::string& transport_name,
6772 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006773 int sdp_mline_index;
6774 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006775 RTC_LOG(LS_ERROR)
6776 << "OnTransportControllerCandidatesGathered: content name "
6777 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006778 return;
6779 }
6780
6781 for (cricket::Candidates::const_iterator citer = candidates.begin();
6782 citer != candidates.end(); ++citer) {
6783 // Use transport_name as the candidate media id.
6784 std::unique_ptr<JsepIceCandidate> candidate(
6785 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6786 if (local_description()) {
6787 mutable_local_description()->AddCandidate(candidate.get());
6788 }
6789 OnIceCandidate(std::move(candidate));
6790 }
6791}
6792
Eldar Relloda13ea22019-06-01 12:23:43 +03006793void PeerConnection::OnTransportControllerCandidateError(
6794 const cricket::IceCandidateErrorEvent& event) {
6795 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6796 event.error_text);
6797}
6798
Steve Anton75737c02017-11-06 10:37:17 -08006799void PeerConnection::OnTransportControllerCandidatesRemoved(
6800 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006801 // Sanity check.
6802 for (const cricket::Candidate& candidate : candidates) {
6803 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006804 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006805 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006806 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006807 return;
6808 }
6809 }
6810
6811 if (local_description()) {
6812 mutable_local_description()->RemoveCandidates(candidates);
6813 }
6814 OnIceCandidatesRemoved(candidates);
6815}
6816
Alex Drake00c7ecf2019-08-06 10:54:47 -07006817void PeerConnection::OnTransportControllerCandidateChanged(
6818 const cricket::CandidatePairChangeEvent& event) {
6819 OnSelectedCandidatePairChanged(event);
6820}
6821
Steve Anton75737c02017-11-06 10:37:17 -08006822void PeerConnection::OnTransportControllerDtlsHandshakeError(
6823 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006824 RTC_HISTOGRAM_ENUMERATION(
6825 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6826 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006827}
6828
Steve Antoned10bd92017-12-05 10:52:59 -08006829void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006830 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006831 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006832 if (channel && !channel->enabled()) {
6833 channel->Enable(true);
6834 }
Steve Anton75737c02017-11-06 10:37:17 -08006835 }
6836
Steve Anton4171afb2017-11-20 10:20:22 -08006837 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006838 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006839 }
Steve Anton75737c02017-11-06 10:37:17 -08006840}
6841
6842// Returns the media index for a local ice candidate given the content name.
6843bool PeerConnection::GetLocalCandidateMediaIndex(
6844 const std::string& content_name,
6845 int* sdp_mline_index) {
6846 if (!local_description() || !sdp_mline_index) {
6847 return false;
6848 }
6849
6850 bool content_found = false;
6851 const ContentInfos& contents = local_description()->description()->contents();
6852 for (size_t index = 0; index < contents.size(); ++index) {
6853 if (contents[index].name == content_name) {
6854 *sdp_mline_index = static_cast<int>(index);
6855 content_found = true;
6856 break;
6857 }
6858 }
6859 return content_found;
6860}
6861
6862bool PeerConnection::UseCandidatesInSessionDescription(
6863 const SessionDescriptionInterface* remote_desc) {
6864 if (!remote_desc) {
6865 return true;
6866 }
6867 bool ret = true;
6868
6869 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6870 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6871 for (size_t n = 0; n < candidates->count(); ++n) {
6872 const IceCandidateInterface* candidate = candidates->at(n);
6873 bool valid = false;
6874 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6875 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006876 RTC_LOG(LS_INFO)
6877 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006878 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006879 }
6880 continue;
6881 }
6882 ret = UseCandidate(candidate);
6883 if (!ret) {
6884 break;
6885 }
6886 }
6887 }
6888 return ret;
6889}
6890
6891bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006892 RTCErrorOr<const cricket::ContentInfo*> result =
6893 FindContentInfo(remote_description(), candidate);
6894 if (!result.ok()) {
6895 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6896 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006897 return false;
6898 }
Steve Anton75737c02017-11-06 10:37:17 -08006899 std::vector<cricket::Candidate> candidates;
6900 candidates.push_back(candidate->candidate());
6901 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006902 RTCError error = transport_controller_->AddRemoteCandidates(
6903 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006904 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006905 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006906 // Candidates successfully submitted for checking.
6907 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6908 ice_connection_state_ ==
6909 PeerConnectionInterface::kIceConnectionDisconnected) {
6910 // If state is New, then the session has just gotten its first remote ICE
6911 // candidates, so go to Checking.
6912 // If state is Disconnected, the session is re-using old candidates or
6913 // receiving additional ones, so go to Checking.
6914 // If state is Connected, stay Connected.
6915 // TODO(bemasc): If state is Connected, and the new candidates are for a
6916 // newly added transport, then the state actually _should_ move to
6917 // checking. Add a way to distinguish that case.
6918 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6919 }
6920 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006921 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006922 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006923 }
6924 return true;
6925}
6926
Guido Urdaneta41633172019-05-23 20:12:29 +02006927RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6928 const SessionDescriptionInterface* description,
6929 const IceCandidateInterface* candidate) {
6930 if (candidate->sdp_mline_index() >= 0) {
6931 size_t mediacontent_index =
6932 static_cast<size_t>(candidate->sdp_mline_index());
6933 size_t content_size = description->description()->contents().size();
6934 if (mediacontent_index < content_size) {
6935 return &description->description()->contents()[mediacontent_index];
6936 } else {
6937 return RTCError(RTCErrorType::INVALID_RANGE,
6938 "Media line index (" +
6939 rtc::ToString(candidate->sdp_mline_index()) +
6940 ") out of range (number of mlines: " +
6941 rtc::ToString(content_size) + ").");
6942 }
6943 } else if (!candidate->sdp_mid().empty()) {
6944 auto& contents = description->description()->contents();
6945 auto it = absl::c_find_if(
6946 contents, [candidate](const cricket::ContentInfo& content_info) {
6947 return content_info.mid() == candidate->sdp_mid();
6948 });
6949 if (it == contents.end()) {
6950 return RTCError(
6951 RTCErrorType::INVALID_PARAMETER,
6952 "Mid " + candidate->sdp_mid() +
6953 " specified but no media section with that mid found.");
6954 } else {
6955 return &*it;
6956 }
6957 }
6958
6959 return RTCError(RTCErrorType::INVALID_PARAMETER,
6960 "Neither sdp_mline_index nor sdp_mid specified.");
6961}
6962
Steve Anton75737c02017-11-06 10:37:17 -08006963void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006964 // Destroy video channel first since it may have a pointer to the
6965 // voice channel.
6966 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006967 if (!video_info || video_info->rejected) {
6968 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006969 }
6970
Steve Anton6fec8802017-12-04 10:37:29 -08006971 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6972 if (!audio_info || audio_info->rejected) {
6973 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006974 }
6975
6976 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6977 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006978 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006979 }
6980}
6981
Steve Antondcc3c022017-12-22 16:02:54 -08006982RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6983 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006984 const cricket::ContentGroup* bundle_group = nullptr;
6985 if (configuration_.bundle_policy ==
6986 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006987 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006988 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006989 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6990 "max-bundle configured but session description "
6991 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006992 }
6993 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006994 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006995}
6996
6997RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006998 // Creating the media channels. Transports should already have been created
6999 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08007000 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007001 if (voice && !voice->rejected &&
7002 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07007003 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007004 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08007005 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7006 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08007007 }
7008 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
7009 }
7010
Steve Antondcc3c022017-12-22 16:02:54 -08007011 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007012 if (video && !video->rejected &&
7013 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07007014 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08007015 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08007016 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7017 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08007018 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08007019 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08007020 }
7021
Steve Antondcc3c022017-12-22 16:02:54 -08007022 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08007023 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007024 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007025 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08007026 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7027 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08007028 }
7029 }
7030
Steve Anton8a006912017-12-04 15:25:56 -08007031 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007032}
7033
Steve Anton4171afb2017-11-20 10:20:22 -08007034// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08007035cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07007036 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007037 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007038 MediaTransportConfig media_transport_config =
7039 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007040
Steve Anton75737c02017-11-06 10:37:17 -08007041 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007042 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007043 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7044 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08007045 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08007046 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08007047 }
Steve Anton75737c02017-11-06 10:37:17 -08007048 voice_channel->SignalDtlsSrtpSetupFailure.connect(
7049 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08007050 voice_channel->SignalSentPacket.connect(this,
7051 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07007052 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08007053
Steve Antoneda6ccd2017-12-04 10:21:55 -08007054 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08007055}
7056
Steve Anton4171afb2017-11-20 10:20:22 -08007057// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08007058cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07007059 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007060 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007061 MediaTransportConfig media_transport_config =
7062 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07007063
Steve Anton75737c02017-11-06 10:37:17 -08007064 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007065 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007066 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7067 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07007068 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08007069 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08007070 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08007071 }
Steve Anton75737c02017-11-06 10:37:17 -08007072 video_channel->SignalDtlsSrtpSetupFailure.connect(
7073 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08007074 video_channel->SignalSentPacket.connect(this,
7075 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07007076 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08007077
Steve Antoneda6ccd2017-12-04 10:21:55 -08007078 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08007079}
7080
Zhi Huange830e682018-03-30 10:48:35 -07007081bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007082 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007083 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00007084 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00007085 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
7086 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007087 if (!network_thread()->Invoke<bool>(
7088 RTC_FROM_HERE,
7089 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
7090 mid))) {
Qingsi Wang437077d2019-09-10 17:52:26 +00007091 return false;
7092 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007093
7094 // All non-RTP data channels must initialize |sctp_data_channels_|.
7095 for (const auto& channel : sctp_data_channels_) {
7096 channel->OnTransportChannelCreated();
7097 }
7098 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007099 case cricket::DCT_RTP:
7100 default:
7101 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
7102 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
7103 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08007104 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007105 if (!rtp_data_channel_) {
7106 return false;
7107 }
7108 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
7109 this, &PeerConnection::OnDtlsSrtpSetupFailure);
7110 rtp_data_channel_->SignalSentPacket.connect(
7111 this, &PeerConnection::OnSentPacket_w);
7112 rtp_data_channel_->SetRtpTransport(rtp_transport);
7113 return true;
Steve Anton75737c02017-11-06 10:37:17 -08007114 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007115 return false;
Steve Anton75737c02017-11-06 10:37:17 -08007116}
7117
7118Call::Stats PeerConnection::GetCallStats() {
7119 if (!worker_thread()->IsCurrent()) {
7120 return worker_thread()->Invoke<Call::Stats>(
7121 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
7122 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007123 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007124 if (call_) {
7125 return call_->GetStats();
7126 } else {
7127 return Call::Stats();
7128 }
7129}
7130
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007131bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007132 DataChannelTransportInterface* transport =
7133 transport_controller_->GetDataChannelTransport(mid);
7134 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08007135 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007136 << "Data channel transport is not available for data channels, mid="
7137 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007138 return false;
7139 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007140 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007141
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007142 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02007143 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007144 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007145
7146 // Note: setting the data sink and checking initial state must be done last,
7147 // after setting up the data channel. Setting the data sink may trigger
7148 // callbacks to PeerConnection which require the transport to be completely
7149 // set up (eg. OnReadyToSend()).
7150 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007151 return true;
7152}
7153
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007154void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007155 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007156 return;
7157 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007158 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
7159 << *sctp_mid_;
7160
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007161 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
7162 // it.
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007163 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +00007164 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007165 if (data_channel_transport_) {
7166 data_channel_transport_->SetDataSink(nullptr);
7167 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007168 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007169}
7170
Steve Anton75737c02017-11-06 10:37:17 -08007171// Returns false if bundle is enabled and rtcp_mux is disabled.
7172bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
7173 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
7174 if (!bundle_enabled)
7175 return true;
7176
7177 const cricket::ContentGroup* bundle_group =
7178 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
7179 RTC_DCHECK(bundle_group != NULL);
7180
7181 const cricket::ContentInfos& contents = desc->contents();
7182 for (cricket::ContentInfos::const_iterator citer = contents.begin();
7183 citer != contents.end(); ++citer) {
7184 const cricket::ContentInfo* content = (&*citer);
7185 RTC_DCHECK(content != NULL);
7186 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08007187 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08007188 if (!HasRtcpMuxEnabled(content))
7189 return false;
7190 }
7191 }
7192 // RTCP-MUX is enabled in all the contents.
7193 return true;
7194}
7195
7196bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08007197 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08007198}
7199
Steve Anton06817cd2018-12-18 15:55:30 -08007200static RTCError ValidateMids(const cricket::SessionDescription& description) {
7201 std::set<std::string> mids;
7202 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08007203 if (content.name.empty()) {
7204 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7205 "A media section is missing a MID attribute.");
7206 }
Steve Anton06817cd2018-12-18 15:55:30 -08007207 if (!mids.insert(content.name).second) {
7208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7209 "Duplicate a=mid value '" + content.name + "'.");
7210 }
7211 }
7212 return RTCError::OK();
7213}
7214
Steve Anton8a006912017-12-04 15:25:56 -08007215RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08007216 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08007217 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08007218 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08007219 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08007220 }
7221
7222 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08007223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08007224 }
7225
Steve Anton3828c062017-12-06 10:34:51 -08007226 SdpType type = sdesc->GetType();
7227 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
7228 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08007229 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01007230 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08007231 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08007232 }
7233
Steve Anton06817cd2018-12-18 15:55:30 -08007234 RTCError error = ValidateMids(*sdesc->description());
7235 if (!error.ok()) {
7236 return error;
7237 }
7238
Steve Anton75737c02017-11-06 10:37:17 -08007239 // Verify crypto settings.
7240 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08007241 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
7242 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007243 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08007244 if (!crypto_error.ok()) {
7245 return crypto_error;
7246 }
Steve Anton75737c02017-11-06 10:37:17 -08007247 }
7248
7249 // Verify ice-ufrag and ice-pwd.
7250 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7252 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08007253 }
7254
7255 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7257 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08007258 }
7259
7260 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
7261 // m-lines that do not rtcp-mux enabled.
7262
7263 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08007264 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007265 // With an answer we want to compare the new answer session description with
7266 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08007267 const cricket::SessionDescription* offer_desc =
7268 (source == cricket::CS_LOCAL) ? remote_description()->description()
7269 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007270 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
7271 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
7272 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7274 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007275 }
7276 } else {
Steve Anton75737c02017-11-06 10:37:17 -08007277 // The re-offers should respect the order of m= sections in current
7278 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007279 // With a re-offer, either the current local or current remote descriptions
7280 // could be the most up to date, so we would like to check against both of
7281 // them if they exist. It could be the case that one of them has a 0 port
7282 // for a media section, but the other does not. This is important to check
7283 // against in the case that we are recycling an m= section.
7284 const cricket::SessionDescription* current_desc = nullptr;
7285 const cricket::SessionDescription* secondary_current_desc = nullptr;
7286 if (local_description()) {
7287 current_desc = local_description()->description();
7288 if (remote_description()) {
7289 secondary_current_desc = remote_description()->description();
7290 }
7291 } else if (remote_description()) {
7292 current_desc = remote_description()->description();
7293 }
Steve Anton75737c02017-11-06 10:37:17 -08007294 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007295 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
7296 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7298 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08007299 }
7300 }
7301
Steve Antonba42e992018-04-09 14:10:01 -07007302 if (IsUnifiedPlan()) {
7303 // Ensure that each audio and video media section has at most one
7304 // "StreamParams". This will return an error if receiving a session
7305 // description from a "Plan B" endpoint which adds multiple tracks of the
7306 // same type. With Unified Plan, there can only be at most one track per
7307 // media section.
7308 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02007309 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07007310 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
7311 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
7312 desc.streams().size() > 1u) {
7313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7314 "Media section has more than one track specified "
7315 "with a=ssrc lines which is not supported with "
7316 "Unified Plan.");
7317 }
7318 }
7319 }
7320
Steve Anton8a006912017-12-04 15:25:56 -08007321 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007322}
7323
Steve Anton3828c062017-12-06 10:34:51 -08007324bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007325 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007326 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007327 return (state == PeerConnectionInterface::kStable) ||
7328 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08007329 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007330 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007331 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7332 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7333 }
7334}
7335
Steve Anton3828c062017-12-06 10:34:51 -08007336bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007337 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007338 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007339 return (state == PeerConnectionInterface::kStable) ||
7340 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08007341 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007342 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007343 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7344 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7345 }
7346}
7347
Steve Antonf8470812017-12-04 10:46:21 -08007348const char* PeerConnection::SessionErrorToString(SessionError error) const {
7349 switch (error) {
7350 case SessionError::kNone:
7351 return "ERROR_NONE";
7352 case SessionError::kContent:
7353 return "ERROR_CONTENT";
7354 case SessionError::kTransport:
7355 return "ERROR_TRANSPORT";
7356 }
7357 RTC_NOTREACHED();
7358 return "";
7359}
7360
Steve Anton75737c02017-11-06 10:37:17 -08007361std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02007362 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08007363 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7364 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02007365 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08007366}
7367
Steve Anton8e20f172018-03-06 10:55:04 -08007368void PeerConnection::ReportSdpFormatReceived(
7369 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08007370 int num_audio_mlines = 0;
7371 int num_video_mlines = 0;
7372 int num_audio_tracks = 0;
7373 int num_video_tracks = 0;
7374 for (const ContentInfo& content : remote_offer.description()->contents()) {
7375 cricket::MediaType media_type = content.media_description()->type();
7376 int num_tracks = std::max(
7377 1, static_cast<int>(content.media_description()->streams().size()));
7378 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7379 num_audio_mlines += 1;
7380 num_audio_tracks += num_tracks;
7381 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7382 num_video_mlines += 1;
7383 num_video_tracks += num_tracks;
7384 }
7385 }
7386 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7387 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7388 format = kSdpFormatReceivedComplexUnifiedPlan;
7389 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7390 format = kSdpFormatReceivedComplexPlanB;
7391 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7392 format = kSdpFormatReceivedSimple;
7393 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007394 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7395 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007396}
7397
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007398void PeerConnection::ReportIceCandidateCollected(
7399 const cricket::Candidate& candidate) {
7400 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7401 if (candidate.address().IsPrivateIP()) {
7402 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7403 }
7404 if (candidate.address().IsUnresolvedIP()) {
7405 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7406 }
7407 if (candidate.address().family() == AF_INET6) {
7408 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7409 }
7410}
7411
7412void PeerConnection::ReportRemoteIceCandidateAdded(
7413 const cricket::Candidate& candidate) {
7414 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7415 if (candidate.address().IsPrivateIP()) {
7416 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7417 }
7418 if (candidate.address().IsUnresolvedIP()) {
7419 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7420 }
7421 if (candidate.address().family() == AF_INET6) {
7422 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7423 }
7424}
7425
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007426void PeerConnection::NoteUsageEvent(UsageEvent event) {
7427 RTC_DCHECK_RUN_ON(signaling_thread());
7428 usage_event_accumulator_ |= static_cast<int>(event);
7429}
7430
7431void PeerConnection::ReportUsagePattern() const {
7432 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007433 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7434 usage_event_accumulator_,
7435 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007436 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007437 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007438 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7439 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007440 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007441 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7442 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7443 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7444 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007445 // If called after close(), we can't report, because observer may have
7446 // been deallocated, and therefore pointer is null. Write to log instead.
7447 if (observer_) {
7448 Observer()->OnInterestingUsage(usage_event_accumulator_);
7449 } else {
7450 RTC_LOG(LS_INFO) << "Interesting usage signature "
7451 << usage_event_accumulator_
7452 << " observed after observer shutdown";
7453 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007454 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007455}
7456
Steve Anton0ffaaa22018-02-23 10:31:30 -08007457void PeerConnection::ReportNegotiatedSdpSemantics(
7458 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007459 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007460 switch (answer.description()->msid_signaling()) {
7461 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007462 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007463 break;
7464 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007465 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007466 break;
7467 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007468 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007469 break;
7470 case cricket::kMsidSignalingMediaSection |
7471 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007472 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007473 break;
7474 default:
7475 RTC_NOTREACHED();
7476 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007477 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7478 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007479}
7480
Steve Anton75737c02017-11-06 10:37:17 -08007481// We need to check the local/remote description for the Transport instead of
7482// the session, because a new Transport added during renegotiation may have
7483// them unset while the session has them set from the previous negotiation.
7484// Not doing so may trigger the auto generation of transport description and
7485// mess up DTLS identity information, ICE credential, etc.
7486bool PeerConnection::ReadyToUseRemoteCandidate(
7487 const IceCandidateInterface* candidate,
7488 const SessionDescriptionInterface* remote_desc,
7489 bool* valid) {
7490 *valid = true;
7491
7492 const SessionDescriptionInterface* current_remote_desc =
7493 remote_desc ? remote_desc : remote_description();
7494
7495 if (!current_remote_desc) {
7496 return false;
7497 }
7498
Guido Urdaneta41633172019-05-23 20:12:29 +02007499 RTCErrorOr<const cricket::ContentInfo*> result =
7500 FindContentInfo(current_remote_desc, candidate);
7501 if (!result.ok()) {
7502 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7503 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007504
7505 *valid = false;
7506 return false;
7507 }
7508
Guido Urdaneta41633172019-05-23 20:12:29 +02007509 std::string transport_name = GetTransportName(result.value()->name);
7510 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007511}
7512
7513bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007514 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007515 (dtls_enabled_ ||
7516 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007517}
7518
7519void PeerConnection::OnTransportControllerGatheringState(
7520 cricket::IceGatheringState state) {
7521 RTC_DCHECK(signaling_thread()->IsCurrent());
7522 if (state == cricket::kIceGatheringGathering) {
7523 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7524 } else if (state == cricket::kIceGatheringComplete) {
7525 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7526 }
7527}
7528
7529void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007530 std::map<std::string, std::set<cricket::MediaType>>
7531 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007532 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007533 if (transceiver->internal()->channel()) {
7534 const std::string& transport_name =
7535 transceiver->internal()->channel()->transport_name();
7536 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007537 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007538 }
Steve Anton75737c02017-11-06 10:37:17 -08007539 }
7540 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007541 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7542 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007543 }
Zhi Huange830e682018-03-30 10:48:35 -07007544
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007545 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007546 if (transport_name) {
7547 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007548 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007549 }
Zhi Huange830e682018-03-30 10:48:35 -07007550
Steve Antonc7b964c2018-02-01 14:39:45 -08007551 for (const auto& entry : media_types_by_transport_name) {
7552 const std::string& transport_name = entry.first;
7553 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007554 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007555 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007556 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007557 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007558 }
7559 }
7560}
7561// Walk through the ConnectionInfos to gather best connection usage
7562// for IPv4 and IPv6.
7563void PeerConnection::ReportBestConnectionState(
7564 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007565 for (const cricket::TransportChannelStats& channel_stats :
7566 stats.channel_stats) {
7567 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007568 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007569 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007570 continue;
7571 }
7572
Steve Antonc7b964c2018-02-01 14:39:45 -08007573 const cricket::Candidate& local = connection_info.local_candidate;
7574 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007575
7576 // Increment the counter for IceCandidatePairType.
7577 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7578 (local.type() == RELAY_PORT_TYPE &&
7579 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007580 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7581 GetIceCandidatePairCounter(local, remote),
7582 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007583 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007584 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7585 GetIceCandidatePairCounter(local, remote),
7586 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007587 } else {
7588 RTC_CHECK(0);
7589 }
Steve Anton75737c02017-11-06 10:37:17 -08007590
7591 // Increment the counter for IP type.
7592 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007593 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7594 kBestConnections_IPv4,
7595 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007596 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007597 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7598 kBestConnections_IPv6,
7599 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007600 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007601 RTC_CHECK(!local.address().hostname().empty() &&
7602 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007603 }
7604
7605 return;
7606 }
7607 }
7608}
7609
7610void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007611 const cricket::TransportStats& stats,
7612 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007613 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7614 return;
7615 }
7616
7617 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7618 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7619 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7620 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7621 return;
7622 }
7623
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007624 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7625 for (cricket::MediaType media_type : media_types) {
7626 switch (media_type) {
7627 case cricket::MEDIA_TYPE_AUDIO:
7628 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7629 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7630 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7631 break;
7632 case cricket::MEDIA_TYPE_VIDEO:
7633 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7634 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7635 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7636 break;
7637 case cricket::MEDIA_TYPE_DATA:
7638 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7639 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7640 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7641 break;
7642 default:
7643 RTC_NOTREACHED();
7644 continue;
7645 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007646 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007647 }
7648
7649 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7650 for (cricket::MediaType media_type : media_types) {
7651 switch (media_type) {
7652 case cricket::MEDIA_TYPE_AUDIO:
7653 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7654 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7655 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7656 break;
7657 case cricket::MEDIA_TYPE_VIDEO:
7658 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7659 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7660 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7661 break;
7662 case cricket::MEDIA_TYPE_DATA:
7663 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7664 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7665 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7666 break;
7667 default:
7668 RTC_NOTREACHED();
7669 continue;
7670 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007671 }
Steve Anton75737c02017-11-06 10:37:17 -08007672 }
7673}
7674
7675void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007676 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007677 RTC_DCHECK(call_);
7678 call_->OnSentPacket(sent_packet);
7679}
7680
7681const std::string PeerConnection::GetTransportName(
7682 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007683 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007684 if (channel) {
7685 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007686 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007687 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007688 RTC_DCHECK(sctp_mid_);
7689 if (content_name == *sctp_mid_) {
7690 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007691 }
7692 }
7693 // Return an empty string if failed to retrieve the transport name.
7694 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007695}
7696
Steve Anton6fec8802017-12-04 10:37:29 -08007697void PeerConnection::DestroyTransceiverChannel(
7698 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7699 transceiver) {
7700 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007701
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007702 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007703 if (channel) {
7704 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007705 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007706 }
7707}
7708
7709void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007710 if (rtp_data_channel_) {
7711 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007712 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007713 rtp_data_channel_ = nullptr;
7714 }
7715
7716 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7717 // grab a reference to this PeerConnection. If this is called from the
7718 // PeerConnection destructor, the RefCountedObject vtable will have already
7719 // been destroyed (since it is a subclass of PeerConnection) and using
7720 // rtc::Bind will cause "Pure virtual function called" error to appear.
7721
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007722 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007723 OnDataChannelDestroyed();
7724 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7725 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007726 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007727 });
7728 }
Steve Anton6fec8802017-12-04 10:37:29 -08007729}
7730
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007731void PeerConnection::DestroyChannelInterface(
7732 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007733 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007734 switch (channel->media_type()) {
7735 case cricket::MEDIA_TYPE_AUDIO:
7736 channel_manager()->DestroyVoiceChannel(
7737 static_cast<cricket::VoiceChannel*>(channel));
7738 break;
7739 case cricket::MEDIA_TYPE_VIDEO:
7740 channel_manager()->DestroyVideoChannel(
7741 static_cast<cricket::VideoChannel*>(channel));
7742 break;
7743 case cricket::MEDIA_TYPE_DATA:
7744 channel_manager()->DestroyRtpDataChannel(
7745 static_cast<cricket::RtpDataChannel*>(channel));
7746 break;
7747 default:
7748 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7749 break;
7750 }
Zhi Huange830e682018-03-30 10:48:35 -07007751}
Steve Anton6fec8802017-12-04 10:37:29 -08007752
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007753bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007754 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007755 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007756 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007757 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007758 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007759 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007760 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007761 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007762 auto base_channel = GetChannel(mid);
7763 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007764 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007765 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007766
Karl Wiberg5966c502019-02-21 23:55:09 +01007767 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007768 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007769 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007770
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007771 if (data_channel_transport_ && mid == sctp_mid_ &&
7772 data_channel_transport_ != data_channel_transport) {
7773 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7774 // it's bundled).
7775 data_channel_transport_->SetDataSink(nullptr);
7776 data_channel_transport_ = data_channel_transport;
7777 if (data_channel_transport) {
7778 data_channel_transport->SetDataSink(this);
7779
7780 // There's a new data channel transport. This needs to be signaled to the
7781 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7782 // necessary when bundling is applied.
7783 data_channel_transport_invoker_->AsyncInvoke<void>(
7784 RTC_FROM_HERE, signaling_thread(), [this] {
7785 RTC_DCHECK_RUN_ON(signaling_thread());
7786 for (auto channel : sctp_data_channels_) {
7787 channel->OnTransportChannelCreated();
7788 }
7789 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007790 }
7791 }
7792
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007793 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007794}
7795
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007796void PeerConnection::OnSetStreams() {
7797 RTC_DCHECK_RUN_ON(signaling_thread());
7798 if (IsUnifiedPlan())
7799 UpdateNegotiationNeeded();
7800}
7801
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007802PeerConnectionObserver* PeerConnection::Observer() const {
7803 // In earlier production code, the pointer was not cleared on close,
7804 // which might have led to undefined behavior if the observer was not
7805 // deallocated, or strange crashes if it was.
7806 // We use CHECK in order to catch such behavior if it exists.
7807 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7808 RTC_CHECK(observer_);
7809 return observer_;
7810}
7811
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007812CryptoOptions PeerConnection::GetCryptoOptions() {
7813 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7814 // after it has been removed.
7815 return configuration_.crypto_options.has_value()
7816 ? *configuration_.crypto_options
7817 : factory_->options().crypto_options;
7818}
7819
Harald Alvestrand89061872018-01-02 14:08:34 +01007820void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007821 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007822 if (stats_collector_) {
7823 stats_collector_->ClearCachedStatsReport();
7824 }
7825}
7826
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007827void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007828 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7829 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007830}
7831
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007832void PeerConnection::UpdateNegotiationNeeded() {
7833 RTC_DCHECK_RUN_ON(signaling_thread());
7834 if (!IsUnifiedPlan()) {
7835 Observer()->OnRenegotiationNeeded();
7836 return;
7837 }
7838
7839 // If connection's [[IsClosed]] slot is true, abort these steps.
7840 if (IsClosed())
7841 return;
7842
7843 // If connection's signaling state is not "stable", abort these steps.
7844 if (signaling_state() != kStable)
7845 return;
7846
7847 // NOTE
7848 // The negotiation-needed flag will be updated once the state transitions to
7849 // "stable", as part of the steps for setting an RTCSessionDescription.
7850
7851 // If the result of checking if negotiation is needed is false, clear the
7852 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7853 // to false, and abort these steps.
7854 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7855 if (!is_negotiation_needed) {
7856 is_negotiation_needed_ = false;
7857 return;
7858 }
7859
7860 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7861 // steps.
7862 if (is_negotiation_needed_)
7863 return;
7864
7865 // Set connection's [[NegotiationNeeded]] slot to true.
7866 is_negotiation_needed_ = true;
7867
7868 // Queue a task that runs the following steps:
7869 // If connection's [[IsClosed]] slot is true, abort these steps.
7870 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7871 // Fire an event named negotiationneeded at connection.
7872 Observer()->OnRenegotiationNeeded();
7873}
7874
7875bool PeerConnection::CheckIfNegotiationIsNeeded() {
7876 RTC_DCHECK_RUN_ON(signaling_thread());
7877 // 1. If any implementation-specific negotiation is required, as described at
7878 // the start of this section, return true.
7879
Henrik Boström79b69802019-07-18 11:16:56 +02007880 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7881 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7882 return true;
7883 }
7884
7885 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007886 const SessionDescriptionInterface* description = current_local_description();
7887 if (!description)
7888 return true;
7889
Henrik Boström79b69802019-07-18 11:16:56 +02007890 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007891 // description has been negotiated yet for data, return true.
7892 if (!sctp_data_channels_.empty()) {
7893 if (!cricket::GetFirstDataContent(description->description()->contents()))
7894 return true;
7895 }
7896
Henrik Boström79b69802019-07-18 11:16:56 +02007897 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007898 // following checks:
7899 for (const auto& transceiver : transceivers_) {
7900 const ContentInfo* current_local_msection =
7901 FindTransceiverMSection(transceiver.get(), description);
7902
7903 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7904 transceiver.get(), current_remote_description());
7905
Henrik Boström79b69802019-07-18 11:16:56 +02007906 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007907 // but the associated m= section is not yet rejected in
7908 // connection.[[CurrentLocalDescription]] or
7909 // connection.[[CurrentRemoteDescription]], return true.
7910 if (transceiver->stopped()) {
7911 if (current_local_msection && !current_local_msection->rejected &&
7912 ((current_remote_msection && !current_remote_msection->rejected) ||
7913 !current_remote_msection)) {
7914 return true;
7915 }
7916 continue;
7917 }
7918
Henrik Boström79b69802019-07-18 11:16:56 +02007919 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007920 // section in description, return true.
7921 if (!current_local_msection)
7922 return true;
7923
7924 const MediaContentDescription* current_local_media_description =
7925 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007926 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007927 // in description then perform the following checks:
7928
Henrik Boström79b69802019-07-18 11:16:56 +02007929 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007930 // associated m= section in description either doesn't contain a single
7931 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7932 // m= section, or the MSID values themselves, differ from what is in
7933 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7934 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7935 if (current_local_media_description->streams().size() == 0)
7936 return true;
7937
7938 std::vector<std::string> msection_msids;
7939 for (const auto& stream : current_local_media_description->streams()) {
7940 for (const std::string& msid : stream.stream_ids())
7941 msection_msids.push_back(msid);
7942 }
7943
7944 std::vector<std::string> transceiver_msids =
7945 transceiver->sender()->stream_ids();
7946 if (msection_msids.size() != transceiver_msids.size())
7947 return true;
7948
7949 absl::c_sort(transceiver_msids);
7950 absl::c_sort(msection_msids);
7951 if (transceiver_msids != msection_msids)
7952 return true;
7953 }
7954
Henrik Boström79b69802019-07-18 11:16:56 +02007955 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007956 // associated m= section in neither connection.[[CurrentLocalDescription]]
7957 // nor connection.[[CurrentRemoteDescription]] matches
7958 // transceiver.[[Direction]], return true.
7959 if (description->GetType() == SdpType::kOffer) {
7960 if (!current_remote_description())
7961 return true;
7962
7963 if (!current_remote_msection)
7964 return true;
7965
7966 RtpTransceiverDirection current_local_direction =
7967 current_local_media_description->direction();
7968 RtpTransceiverDirection current_remote_direction =
7969 current_remote_msection->media_description()->direction();
7970 if (transceiver->direction() != current_local_direction &&
7971 transceiver->direction() !=
7972 RtpTransceiverDirectionReversed(current_remote_direction)) {
7973 return true;
7974 }
7975 }
7976
Henrik Boström79b69802019-07-18 11:16:56 +02007977 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007978 // associated m= section in the description does not match
7979 // transceiver.[[Direction]] intersected with the offered direction (as
7980 // described in [JSEP] (section 5.3.1.)), return true.
7981 if (description->GetType() == SdpType::kAnswer) {
7982 if (!remote_description())
7983 return true;
7984
7985 const ContentInfo* offered_remote_msection =
7986 FindTransceiverMSection(transceiver.get(), remote_description());
7987
7988 RtpTransceiverDirection offered_direction =
7989 offered_remote_msection
7990 ? offered_remote_msection->media_description()->direction()
7991 : RtpTransceiverDirection::kInactive;
7992
7993 if (current_local_media_description->direction() !=
7994 (RtpTransceiverDirectionIntersection(
7995 transceiver->direction(),
7996 RtpTransceiverDirectionReversed(offered_direction)))) {
7997 return true;
7998 }
7999 }
8000 }
8001
8002 // If all the preceding checks were performed and true was not returned,
8003 // nothing remains to be negotiated; return false.
8004 return false;
8005}
8006
Eldar Relloead0ec92019-10-21 23:01:31 +03008007RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03008008 auto state = signaling_state();
8009 if (state != PeerConnectionInterface::kHaveLocalOffer &&
8010 state != PeerConnectionInterface::kHaveRemoteOffer) {
8011 return RTCError(RTCErrorType::INVALID_STATE,
8012 "Called in wrong signalingState: " +
8013 GetSignalingStateString(signaling_state()));
8014 }
8015 RTC_DCHECK_RUN_ON(signaling_thread());
8016 RTC_DCHECK(IsUnifiedPlan());
8017
8018 for (auto&& transceivers_stable_state_pair :
8019 transceiver_stable_states_by_transceivers_) {
8020 auto transceiver = transceivers_stable_state_pair.first;
8021 auto state = transceivers_stable_state_pair.second;
8022 RTC_DCHECK(transceiver->internal()->mid().has_value());
8023 std::string mid = transceiver->internal()->mid().value();
8024 transport_controller_->RollbackTransportForMid(mid);
8025 DestroyTransceiverChannel(transceiver);
8026
Eldar Relloead0ec92019-10-21 23:01:31 +03008027 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
8028 transceiver->receiver()) {
8029 Observer()->OnRemoveTrack(transceiver->receiver());
8030 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03008031 if (state.newly_created()) {
8032 // Remove added transceivers with no added track.
8033 if (transceiver->internal()->sender()->track()) {
8034 transceiver->internal()->set_created_by_addtrack(true);
8035 } else {
8036 int remaining_transceiver_count = 0;
8037 for (auto&& t : transceivers_) {
8038 if (t != transceiver) {
8039 transceivers_[remaining_transceiver_count++] = t;
8040 }
8041 }
8042 transceivers_.resize(remaining_transceiver_count);
8043 }
8044 }
8045 transceiver->internal()->sender_internal()->set_transport(nullptr);
8046 transceiver->internal()->receiver_internal()->set_transport(nullptr);
8047 transceiver->internal()->set_direction(state.direction());
8048 transceiver->internal()->set_mid(state.mid());
8049 transceiver->internal()->set_mline_index(state.mline_index());
8050 }
8051 transceiver_stable_states_by_transceivers_.clear();
8052 pending_local_description_.reset();
8053 pending_remote_description_.reset();
8054 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 23:01:31 +03008055
8056 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
8057 // gets called in SetRemoteDescription.
8058 if (sdp_type == SdpType::kRollback) {
8059 UpdateNegotiationNeeded();
8060 if (is_negotiation_needed_) {
8061 Observer()->OnRenegotiationNeeded();
8062 }
8063 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03008064 return RTCError::OK();
8065}
8066
henrike@webrtc.org28e20752013-07-10 00:45:36 +00008067} // namespace webrtc