blob: 465c092f88ec49c7851a2c6d7efb7fd2c33d28bd [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020028#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020029#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070030#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "logging/rtc_event_log/ice_logger.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Bjorn A Mellemb689af42019-08-21 10:44:59 -070059#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/trace_event.h"
61#include "system_wrappers/include/clock.h"
62#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070063#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080071using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080072using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080074using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080075using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080076using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080079using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070080using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080082
Steve Antonba818672017-11-06 10:21:57 -080083namespace webrtc {
84
Steve Anton75737c02017-11-06 10:37:17 -080085// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080089const char kInvalidCandidates[] = "Description contains invalid candidates.";
90const char kInvalidSdp[] = "Invalid session description.";
91const char kMlineMismatchInAnswer[] =
92 "The order of m-lines in answer doesn't match order in offer. Rejecting "
93 "answer.";
94const char kMlineMismatchInSubsequentOffer[] =
95 "The order of m-lines in subsequent offer doesn't match order from "
96 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080097const char kSdpWithoutDtlsFingerprint[] =
98 "Called with SDP without DTLS fingerprint.";
99const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
100const char kSdpWithoutIceUfragPwd[] =
101 "Called with SDP without ice-ufrag and ice-pwd.";
102const char kSessionError[] = "Session error code: ";
103const char kSessionErrorDesc[] = "Session error description: ";
104const char kDtlsSrtpSetupFailureRtp[] =
105 "Couldn't set up DTLS-SRTP on RTP channel.";
106const char kDtlsSrtpSetupFailureRtcp[] =
107 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108
Steve Anton75737c02017-11-06 10:37:17 -0800109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700111// Field trials.
112// Controls datagram transport support.
113const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700114// Controls datagram transport data channel support.
115const char kDatagramTransportDataChannelFieldTrial[] =
116 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700117
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800118// UMA metric names.
119const char kSimulcastVersionApplyLocalDescription[] =
120 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
121const char kSimulcastVersionApplyRemoteDescription[] =
122 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
123const char kSimulcastNumberOfEncodings[] =
124 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
125const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
126
Seth Hampson845e8782018-03-02 11:34:10 -0800127static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800128static const char kDefaultAudioSenderId[] = "defaulta0";
129static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700130
zhihuang8f65cdf2016-05-06 18:40:30 -0700131// The length of RTCP CNAMEs.
132static const int kRtcpCnameLength = 16;
133
Steve Antonad182762018-09-05 20:22:40 +0000134enum {
135 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
136 MSG_SET_SESSIONDESCRIPTION_FAILED,
137 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
138 MSG_GETSTATS,
139 MSG_FREE_DATACHANNELS,
140 MSG_REPORT_USAGE_PATTERN,
141};
142
Harald Alvestrand19793842018-06-25 12:03:50 +0200143static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
144
Steve Antonad182762018-09-05 20:22:40 +0000145struct SetSessionDescriptionMsg : public rtc::MessageData {
146 explicit SetSessionDescriptionMsg(
147 webrtc::SetSessionDescriptionObserver* observer)
148 : observer(observer) {}
149
150 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
151 RTCError error;
152};
153
154struct CreateSessionDescriptionMsg : public rtc::MessageData {
155 explicit CreateSessionDescriptionMsg(
156 webrtc::CreateSessionDescriptionObserver* observer)
157 : observer(observer) {}
158
159 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
160 RTCError error;
161};
162
163struct GetStatsMsg : public rtc::MessageData {
164 GetStatsMsg(webrtc::StatsObserver* observer,
165 webrtc::MediaStreamTrackInterface* track)
166 : observer(observer), track(track) {}
167 rtc::scoped_refptr<webrtc::StatsObserver> observer;
168 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
169};
170
deadbeefab9b2d12015-10-14 11:33:11 -0700171// Check if we can send |new_stream| on a PeerConnection.
172bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
173 webrtc::MediaStreamInterface* new_stream) {
174 if (!new_stream || !current_streams) {
175 return false;
176 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700177 if (current_streams->find(new_stream->id()) != nullptr) {
178 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700180 return false;
181 }
182 return true;
183}
184
deadbeef5e97fb52015-10-15 12:49:08 -0700185// If the direction is "recvonly" or "inactive", treat the description
186// as containing no streams.
187// See: https://code.google.com/p/webrtc/issues/detail?id=5054
188std::vector<cricket::StreamParams> GetActiveStreams(
189 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800190 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700191 ? desc->streams()
192 : std::vector<cricket::StreamParams>();
193}
194
deadbeefab9b2d12015-10-14 11:33:11 -0700195bool IsValidOfferToReceiveMedia(int value) {
196 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
197 return (value >= Options::kUndefined) &&
198 (value <= Options::kMaxOfferToReceiveMedia);
199}
200
zhihuang1c378ed2017-08-17 14:10:50 -0700201// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800202void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700203 const std::vector<rtc::scoped_refptr<
204 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700205 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200206 cricket::MediaDescriptionOptions* video_media_description_options,
207 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700208 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
210 if (audio_media_description_options) {
211 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700212 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 } else {
215 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
216 if (video_media_description_options) {
217 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800218 sender->id(), sender->internal()->stream_ids(), {},
219 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700220 }
221 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700222 }
zhihuang1c378ed2017-08-17 14:10:50 -0700223}
olka3c747662017-08-17 06:50:32 -0700224
zhihuang1c378ed2017-08-17 14:10:50 -0700225// Add options to |session_options| from |rtp_data_channels|.
226void AddRtpDataChannelOptions(
227 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
228 rtp_data_channels,
229 cricket::MediaDescriptionOptions* data_media_description_options) {
230 if (!data_media_description_options) {
231 return;
232 }
deadbeefab9b2d12015-10-14 11:33:11 -0700233 // Check for data channels.
234 for (const auto& kv : rtp_data_channels) {
235 const DataChannel* channel = kv.second;
236 if (channel->state() == DataChannel::kConnecting ||
237 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700238 // Legacy RTP data channels are signaled with the track/stream ID set to
239 // the data channel's label.
240 data_media_description_options->AddRtpDataChannel(channel->label(),
241 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700242 }
243 }
244}
245
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246uint32_t ConvertIceTransportTypeToCandidateFilter(
247 PeerConnectionInterface::IceTransportsType type) {
248 switch (type) {
249 case PeerConnectionInterface::kNone:
250 return cricket::CF_NONE;
251 case PeerConnectionInterface::kRelay:
252 return cricket::CF_RELAY;
253 case PeerConnectionInterface::kNoHost:
254 return (cricket::CF_ALL & ~cricket::CF_HOST);
255 case PeerConnectionInterface::kAll:
256 return cricket::CF_ALL;
257 default:
nissec80e7412017-01-11 05:56:46 -0800258 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700259 }
260 return cricket::CF_NONE;
261}
262
Steve Antonba818672017-11-06 10:21:57 -0800263std::string GetSignalingStateString(
264 PeerConnectionInterface::SignalingState state) {
265 switch (state) {
266 case PeerConnectionInterface::kStable:
267 return "kStable";
268 case PeerConnectionInterface::kHaveLocalOffer:
269 return "kHaveLocalOffer";
270 case PeerConnectionInterface::kHaveLocalPrAnswer:
271 return "kHavePrAnswer";
272 case PeerConnectionInterface::kHaveRemoteOffer:
273 return "kHaveRemoteOffer";
274 case PeerConnectionInterface::kHaveRemotePrAnswer:
275 return "kHaveRemotePrAnswer";
276 case PeerConnectionInterface::kClosed:
277 return "kClosed";
278 }
279 RTC_NOTREACHED();
280 return "";
281}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282
Steve Anton75737c02017-11-06 10:37:17 -0800283IceCandidatePairType GetIceCandidatePairCounter(
284 const cricket::Candidate& local,
285 const cricket::Candidate& remote) {
286 const auto& l = local.type();
287 const auto& r = remote.type();
288 const auto& host = LOCAL_PORT_TYPE;
289 const auto& srflx = STUN_PORT_TYPE;
290 const auto& relay = RELAY_PORT_TYPE;
291 const auto& prflx = PRFLX_PORT_TYPE;
292 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 bool local_hostname =
294 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
295 bool remote_hostname = !remote.address().hostname().empty() &&
296 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800297 bool local_private = IPIsPrivate(local.address().ipaddr());
298 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800299 if (local_hostname) {
300 if (remote_hostname) {
301 return kIceCandidatePairHostNameHostName;
302 } else if (remote_private) {
303 return kIceCandidatePairHostNameHostPrivate;
304 } else {
305 return kIceCandidatePairHostNameHostPublic;
306 }
307 } else if (local_private) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostPrivateHostName;
310 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800311 return kIceCandidatePairHostPrivateHostPrivate;
312 } else {
313 return kIceCandidatePairHostPrivateHostPublic;
314 }
315 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800316 if (remote_hostname) {
317 return kIceCandidatePairHostPublicHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPublicHostPrivate;
320 } else {
321 return kIceCandidatePairHostPublicHostPublic;
322 }
323 }
324 }
325 if (l == host && r == srflx)
326 return kIceCandidatePairHostSrflx;
327 if (l == host && r == relay)
328 return kIceCandidatePairHostRelay;
329 if (l == host && r == prflx)
330 return kIceCandidatePairHostPrflx;
331 if (l == srflx && r == host)
332 return kIceCandidatePairSrflxHost;
333 if (l == srflx && r == srflx)
334 return kIceCandidatePairSrflxSrflx;
335 if (l == srflx && r == relay)
336 return kIceCandidatePairSrflxRelay;
337 if (l == srflx && r == prflx)
338 return kIceCandidatePairSrflxPrflx;
339 if (l == relay && r == host)
340 return kIceCandidatePairRelayHost;
341 if (l == relay && r == srflx)
342 return kIceCandidatePairRelaySrflx;
343 if (l == relay && r == relay)
344 return kIceCandidatePairRelayRelay;
345 if (l == relay && r == prflx)
346 return kIceCandidatePairRelayPrflx;
347 if (l == prflx && r == host)
348 return kIceCandidatePairPrflxHost;
349 if (l == prflx && r == srflx)
350 return kIceCandidatePairPrflxSrflx;
351 if (l == prflx && r == relay)
352 return kIceCandidatePairPrflxRelay;
353 return kIceCandidatePairMax;
354}
355
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800356// Logic to decide if an m= section can be recycled. This means that the new
357// m= section is not rejected, but the old local or remote m= section is
358// rejected. |old_content_one| and |old_content_two| refer to the m= section
359// of the old remote and old local descriptions in no particular order.
360// We need to check both the old local and remote because either
361// could be the most current from the latest negotation.
362bool IsMediaSectionBeingRecycled(SdpType type,
363 const ContentInfo& content,
364 const ContentInfo* old_content_one,
365 const ContentInfo* old_content_two) {
366 return type == SdpType::kOffer && !content.rejected &&
367 ((old_content_one && old_content_one->rejected) ||
368 (old_content_two && old_content_two->rejected));
369}
370
Steve Anton75737c02017-11-06 10:37:17 -0800371// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372// |current_desc|. The number of m= sections in |new_desc| should be no
373// less than |current_desc|. In the case of checking an answer's
374// |new_desc|, the |current_desc| is the last offer that was set as the
375// local or remote. In the case of checking an offer's |new_desc| we
376// check against the local and remote descriptions stored from the last
377// negotiation, because either of these could be the most up to date for
378// possible rejected m sections. These are the |current_desc| and
379// |secondary_current_desc|.
380bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
381 const SessionDescription* secondary_current_desc,
382 const SessionDescription& new_desc,
383 const SdpType type) {
384 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800385 return false;
386 }
387
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
389 const cricket::ContentInfo* secondary_content_info = nullptr;
390 if (secondary_current_desc &&
391 i < secondary_current_desc->contents().size()) {
392 secondary_content_info = &secondary_current_desc->contents()[i];
393 }
394 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
395 &current_desc.contents()[i],
396 secondary_content_info)) {
397 // For new offer descriptions, if the media section can be recycled, it's
398 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800399 continue;
400 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800402 return false;
403 }
404 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800405 new_desc.contents()[i].media_description();
406 const MediaContentDescription* current_desc_mdesc =
407 current_desc.contents()[i].media_description();
408 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800409 return false;
410 }
411 }
412 return true;
413}
414
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800415bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
416 const SessionDescription& desc2) {
417 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800418}
419
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700420void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
421 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200422 // Array of structs needed to map {KeyExchangeProtocolType,
423 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
424 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
425 static constexpr struct {
426 KeyExchangeProtocolType protocol_type;
427 cricket::MediaType media_type;
428 KeyExchangeProtocolMedia protocol_media;
429 } kEnumCounterKeyProtocolMediaMap[] = {
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
434 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeDtlsData},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
437 kEnumCounterKeyProtocolMediaTypeSdesAudio},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
439 kEnumCounterKeyProtocolMediaTypeSdesVideo},
440 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
441 kEnumCounterKeyProtocolMediaTypeSdesData},
442 };
443
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
445 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100446
Mirko Bonadeiab499822018-09-11 10:43:20 +0200447 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
448 if (i.protocol_type == protocol_type && i.media_type == media_type) {
449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
450 i.protocol_media,
451 kEnumCounterKeyProtocolMediaTypeMax);
452 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100453 }
454}
455
Harald Alvestrand76829d72018-07-18 23:24:36 +0200456void NoteAddIceCandidateResult(int result) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
458 kAddIceCandidateMax);
459}
460
Steve Anton75737c02017-11-06 10:37:17 -0800461// Checks that each non-rejected content has SDES crypto keys or a DTLS
462// fingerprint, unless it's in a BUNDLE group, in which case only the
463// BUNDLE-tag section (first media section/description in the BUNDLE group)
464// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
465// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
466// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700467RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 const cricket::ContentGroup* bundle =
469 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800470 for (const cricket::ContentInfo& content_info : desc->contents()) {
471 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800472 continue;
473 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100474 // Note what media is used with each crypto protocol, for all sections.
475 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
476 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700477 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800478 const std::string& mid = content_info.name;
479 if (bundle && bundle->HasContentName(mid) &&
480 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 // This isn't the first media section in the BUNDLE group, so it's not
482 // required to have crypto attributes, since only the crypto attributes
483 // from the first section actually get used.
484 continue;
485 }
486
487 // If the content isn't rejected or bundled into another m= section, crypto
488 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800489 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800490 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (!media || !tinfo) {
492 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800494 }
495 if (dtls_enabled) {
496 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_WARNING)
498 << "Session description must have DTLS fingerprint if "
499 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError(RTCErrorType::INVALID_PARAMETER,
501 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 } else {
504 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800506 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800507 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800508 }
509 }
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800512}
513
514// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
515// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
516// media section/description in the BUNDLE group) needs a ufrag and pwd.
517bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
518 const cricket::ContentGroup* bundle =
519 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800520 for (const cricket::ContentInfo& content_info : desc->contents()) {
521 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 continue;
523 }
Steve Anton8a006912017-12-04 15:25:56 -0800524 const std::string& mid = content_info.name;
525 if (bundle && bundle->HasContentName(mid) &&
526 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 // This isn't the first media section in the BUNDLE group, so it's not
528 // required to have ufrag/password, since only the ufrag/password from
529 // the first section actually get used.
530 continue;
531 }
532
533 // If the content isn't rejected or bundled into another m= section,
534 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800535 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800536 if (!tinfo) {
537 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 if (tinfo->description.ice_ufrag.empty() ||
542 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 }
547 return true;
548}
549
Steve Anton75737c02017-11-06 10:37:17 -0800550// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
551bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
552 const SessionDescriptionInterface* new_desc,
553 const std::string& content_name) {
554 if (!old_desc) {
555 return false;
556 }
557 const SessionDescription* new_sd = new_desc->description();
558 const SessionDescription* old_sd = old_desc->description();
559 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
560 if (!cinfo || cinfo->rejected) {
561 return false;
562 }
563 // If the content isn't rejected, check if ufrag and password has changed.
564 const cricket::TransportDescription* new_transport_desc =
565 new_sd->GetTransportDescriptionByName(content_name);
566 const cricket::TransportDescription* old_transport_desc =
567 old_sd->GetTransportDescriptionByName(content_name);
568 if (!new_transport_desc || !old_transport_desc) {
569 // No transport description exists. This is not an ICE restart.
570 return false;
571 }
572 if (cricket::IceCredentialsChanged(
573 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
574 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
576 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800577 return true;
578 }
579 return false;
580}
581
Steve Anton80dd7b52018-02-16 17:08:42 -0800582// Generates a string error message for SetLocalDescription/SetRemoteDescription
583// from an RTCError.
584std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
585 SdpType type,
586 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200587 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800588 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
589 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200590 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800591}
592
Seth Hampson5b4f0752018-04-02 16:31:36 -0700593std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
594 std::string output = "streams=[";
595 const char* separator = "";
596 for (const auto& stream_id : stream_ids) {
597 output.append(separator).append(stream_id);
598 separator = ", ";
599 }
600 output.append("]");
601 return output;
602}
603
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200604absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700605 int rtc_configuration_parameter) {
606 if (rtc_configuration_parameter ==
607 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200608 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700609 }
610 return rtc_configuration_parameter;
611}
612
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
Steve Anton75737c02017-11-06 10:37:17 -0800650} // namespace
651
Henrik Boström79b69802019-07-18 11:16:56 +0200652class PeerConnection::LocalIceCredentialsToReplace {
653 public:
654 // Sets the ICE credentials that need restarting to the ICE credentials of
655 // the current and pending descriptions.
656 void SetIceCredentialsFromLocalDescriptions(
657 const SessionDescriptionInterface* current_local_description,
658 const SessionDescriptionInterface* pending_local_description) {
659 ice_credentials_.clear();
660 if (current_local_description) {
661 AppendIceCredentialsFromSessionDescription(*current_local_description);
662 }
663 if (pending_local_description) {
664 AppendIceCredentialsFromSessionDescription(*pending_local_description);
665 }
666 }
667
668 void ClearIceCredentials() { ice_credentials_.clear(); }
669
670 // Returns true if we have ICE credentials that need restarting.
671 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
672
673 // Returns true if |local_description| shares no ICE credentials with the
674 // ICE credentials that need restarting.
675 bool SatisfiesIceRestart(
676 const SessionDescriptionInterface& local_description) const {
677 for (const auto& transport_info :
678 local_description.description()->transport_infos()) {
679 if (ice_credentials_.find(std::make_pair(
680 transport_info.description.ice_ufrag,
681 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
682 return false;
683 }
684 }
685 return true;
686 }
687
688 private:
689 void AppendIceCredentialsFromSessionDescription(
690 const SessionDescriptionInterface& desc) {
691 for (const auto& transport_info : desc.description()->transport_infos()) {
692 ice_credentials_.insert(
693 std::make_pair(transport_info.description.ice_ufrag,
694 transport_info.description.ice_pwd));
695 }
696 }
697
698 std::set<std::pair<std::string, std::string>> ice_credentials_;
699};
700
Henrik Boström31638672017-11-23 17:48:32 +0100701// Upon completion, posts a task to execute the callback of the
702// SetSessionDescriptionObserver asynchronously on the same thread. At this
703// point, the state of the peer connection might no longer reflect the effects
704// of the SetRemoteDescription operation, as the peer connection could have been
705// modified during the post.
706// TODO(hbos): Remove this class once we remove the version of
707// PeerConnectionInterface::SetRemoteDescription() that takes a
708// SetSessionDescriptionObserver as an argument.
709class PeerConnection::SetRemoteDescriptionObserverAdapter
710 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
711 public:
712 SetRemoteDescriptionObserverAdapter(
713 rtc::scoped_refptr<PeerConnection> pc,
714 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
715 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
716
717 // SetRemoteDescriptionObserverInterface implementation.
718 void OnSetRemoteDescriptionComplete(RTCError error) override {
719 if (error.ok())
720 pc_->PostSetSessionDescriptionSuccess(wrapper_);
721 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100722 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100723 }
724
725 private:
726 rtc::scoped_refptr<PeerConnection> pc_;
727 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
728};
729
deadbeef293e9262017-01-11 12:28:30 -0800730bool PeerConnectionInterface::RTCConfiguration::operator==(
731 const PeerConnectionInterface::RTCConfiguration& o) const {
732 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800734 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000735 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700736 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800737 BundlePolicy bundle_policy;
738 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700739 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
740 int ice_candidate_pool_size;
741 bool disable_ipv6;
742 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700743 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100744 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700745 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200746 absl::optional<int> screencast_min_bitrate;
747 absl::optional<bool> combined_audio_video_bwe;
748 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800749 TcpCandidatePolicy tcp_candidate_policy;
750 CandidateNetworkPolicy candidate_network_policy;
751 int audio_jitter_buffer_max_packets;
752 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100753 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100754 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800755 int ice_connection_receiving_timeout;
756 int ice_backup_candidate_pair_ping_interval;
757 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800758 bool prioritize_most_likely_ice_candidate_pairs;
759 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800760 bool prune_turn_ports;
761 bool presume_writable_when_fully_relayed;
762 bool enable_ice_renomination;
763 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700764 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200765 absl::optional<int> ice_check_interval_strong_connectivity;
766 absl::optional<int> ice_check_interval_weak_connectivity;
767 absl::optional<int> ice_check_min_interval;
768 absl::optional<int> ice_unwritable_timeout;
769 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800770 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200771 absl::optional<int> stun_candidate_keepalive_interval;
772 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200773 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800774 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200775 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700776 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700777 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700778 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700779 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700780 absl::optional<bool> use_datagram_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700781 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100782 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200783 std::string turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -0800784 };
785 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
786 "Did you add something to RTCConfiguration and forget to "
787 "update operator==?");
788 return type == o.type && servers == o.servers &&
789 bundle_policy == o.bundle_policy &&
790 rtcp_mux_policy == o.rtcp_mux_policy &&
791 tcp_candidate_policy == o.tcp_candidate_policy &&
792 candidate_network_policy == o.candidate_network_policy &&
793 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
794 audio_jitter_buffer_fast_accelerate ==
795 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100796 audio_jitter_buffer_min_delay_ms ==
797 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100798 audio_jitter_buffer_enable_rtx_handling ==
799 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800800 ice_connection_receiving_timeout ==
801 o.ice_connection_receiving_timeout &&
802 ice_backup_candidate_pair_ping_interval ==
803 o.ice_backup_candidate_pair_ping_interval &&
804 continual_gathering_policy == o.continual_gathering_policy &&
805 certificates == o.certificates &&
806 prioritize_most_likely_ice_candidate_pairs ==
807 o.prioritize_most_likely_ice_candidate_pairs &&
808 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800809 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700810 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100811 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800812 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800813 screencast_min_bitrate == o.screencast_min_bitrate &&
814 combined_audio_video_bwe == o.combined_audio_video_bwe &&
815 enable_dtls_srtp == o.enable_dtls_srtp &&
816 ice_candidate_pool_size == o.ice_candidate_pool_size &&
817 prune_turn_ports == o.prune_turn_ports &&
818 presume_writable_when_fully_relayed ==
819 o.presume_writable_when_fully_relayed &&
820 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800821 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700822 surface_ice_candidates_on_ice_transport_type_changed ==
823 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800824 ice_check_interval_strong_connectivity ==
825 o.ice_check_interval_strong_connectivity &&
826 ice_check_interval_weak_connectivity ==
827 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700828 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700829 ice_unwritable_timeout == o.ice_unwritable_timeout &&
830 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800831 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800832 stun_candidate_keepalive_interval ==
833 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200834 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800835 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800836 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700837 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700838 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700839 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700840 use_media_transport_for_data_channels ==
841 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700842 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700843 use_datagram_transport_for_data_channels ==
844 o.use_datagram_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100845 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200846 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
847 turn_logging_id == o.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -0800848}
849
850bool PeerConnectionInterface::RTCConfiguration::operator!=(
851 const PeerConnectionInterface::RTCConfiguration& o) const {
852 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800853}
854
zhihuang8f65cdf2016-05-06 18:40:30 -0700855// Generate a RTCP CNAME when a PeerConnection is created.
856std::string GenerateRtcpCname() {
857 std::string cname;
858 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100859 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800860 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700861 }
862 return cname;
863}
864
zhihuang1c378ed2017-08-17 14:10:50 -0700865bool ValidateOfferAnswerOptions(
866 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
867 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
868 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700869}
870
zhihuang1c378ed2017-08-17 14:10:50 -0700871// From |rtc_options|, fill parts of |session_options| shared by all generated
872// m= sections (in other words, nothing that involves a map/array).
873void ExtractSharedMediaSessionOptions(
874 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
875 cricket::MediaSessionOptions* session_options) {
876 session_options->vad_enabled = rtc_options.voice_activity_detection;
877 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200878 session_options->raw_packetization_for_video =
879 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700880}
zhihuanga77e6bb2017-08-14 18:17:48 -0700881
zhihuang38ede132017-06-15 12:52:32 -0700882PeerConnection::PeerConnection(PeerConnectionFactory* factory,
883 std::unique_ptr<RtcEventLog> event_log,
884 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000885 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700886 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100887 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700888 datagram_transport_config_(
889 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700890 datagram_transport_data_channel_config_(
891 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700892 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700893 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700894 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100895 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200896 call_ptr_(call_.get()),
Bjorn A Mellem487f9a12019-09-09 13:11:49 -0700897 data_channel_transport_(nullptr),
Henrik Boström79b69802019-07-18 11:16:56 +0200898 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899
900PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100901 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800902 RTC_DCHECK_RUN_ON(signaling_thread());
903
Steve Anton8af21862017-12-15 11:20:13 -0800904 // Need to stop transceivers before destroying the stats collector because
905 // AudioRtpSender has a reference to the StatsCollector it will update when
906 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100907 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800908 transceiver->Stop();
909 }
Steve Anton4171afb2017-11-20 10:20:22 -0800910
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700911 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800912 if (stats_collector_) {
913 stats_collector_->WaitForPendingRequest();
914 stats_collector_ = nullptr;
915 }
Steve Anton75737c02017-11-06 10:37:17 -0800916
Steve Anton8af21862017-12-15 11:20:13 -0800917 // Don't destroy BaseChannels until after stats has been cleaned up so that
918 // the last stats request can still read from the channels.
919 DestroyAllChannels();
920
Mirko Bonadei675513b2017-11-09 11:09:25 +0100921 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800922
923 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800924 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700925 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800926 transport_controller_.reset();
927
deadbeef91dd5672016-05-18 16:55:30 -0700928 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100929 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
930 RTC_DCHECK_RUN_ON(network_thread());
931 port_allocator_.reset();
932 });
eladalon248fd4f2017-09-06 05:18:15 -0700933 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700934 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100935 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700936 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800937 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700938 event_log_.reset();
939 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940}
941
Steve Anton8af21862017-12-15 11:20:13 -0800942void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800943 // Destroy video channels first since they may have a pointer to a voice
944 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100945 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800946 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800947 DestroyTransceiverChannel(transceiver);
948 }
949 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100950 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800951 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800952 DestroyTransceiverChannel(transceiver);
953 }
954 }
955 DestroyDataChannel();
956}
957
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000959 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700960 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100961 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100962 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100963 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700964
965 RTCError config_error = ValidateConfiguration(configuration);
966 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100967 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700968 return false;
969 }
970
Benjamin Wrightcab58882018-05-02 15:12:47 -0700971 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100972 RTC_LOG(LS_ERROR)
973 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100974 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800975 return false;
976 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200977
Benjamin Wrightcab58882018-05-02 15:12:47 -0700978 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800979 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100980 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100981 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800982 return false;
983 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700984
Benjamin Wrightcab58882018-05-02 15:12:47 -0700985 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700986 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700987 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700988 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800989
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200990 cricket::ServerAddresses stun_servers;
991 std::vector<cricket::RelayServerConfig> turn_servers;
992
993 RTCErrorType parse_error =
994 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
995 if (parse_error != RTCErrorType::NONE) {
996 return false;
997 }
998
Jonas Oreland3c028422019-08-22 16:16:35 +0200999 // Add the turn logging id to all turn servers
1000 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1001 turn_server.turn_logging_id = configuration.turn_logging_id;
1002 }
1003
deadbeef91dd5672016-05-18 16:55:30 -07001004 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001005 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001006 const auto pa_result =
1007 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001008 RTC_FROM_HERE,
1009 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001010 stun_servers, turn_servers, configuration));
1011
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001012 // If initialization was successful, note if STUN or TURN servers
1013 // were supplied.
1014 if (!stun_servers.empty()) {
1015 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1016 }
1017 if (!turn_servers.empty()) {
1018 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1019 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001021 // Send information about IPv4/IPv6 status.
1022 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001023 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001024 address_family = kPeerConnection_IPv6;
1025 } else {
1026 address_family = kPeerConnection_IPv4;
1027 }
1028 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1029 kPeerConnectionAddressFamilyCounter_Max);
1030
Zhi Huange830e682018-03-30 10:48:35 -07001031 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1032
Steve Anton75737c02017-11-06 10:37:17 -08001033 // RFC 3264: The numeric value of the session id and version in the
1034 // o line MUST be representable with a "64 bit signed integer".
1035 // Due to this constraint session id |session_id_| is max limited to
1036 // LLONG_MAX.
1037 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001038 JsepTransportController::Config config;
1039 config.redetermine_role_on_ice_restart =
1040 configuration.redetermine_role_on_ice_restart;
1041 config.ssl_max_version = factory_->options().ssl_max_version;
1042 config.disable_encryption = options.disable_encryption;
1043 config.bundle_policy = configuration.bundle_policy;
1044 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001045 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1046 // stub.
1047 config.crypto_options = configuration.crypto_options.has_value()
1048 ? *configuration.crypto_options
1049 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001050 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001051 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001052#if defined(ENABLE_EXTERNAL_AUTH)
1053 config.enable_external_auth = true;
1054#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001055 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001056
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001057 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001058 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001059 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001060 use_datagram_transport_for_data_channels_ =
1061 datagram_transport_data_channel_config_.enabled &&
1062 configuration.use_datagram_transport_for_data_channels.value_or(
1063 datagram_transport_data_channel_config_.default_value);
1064 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1065 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001066 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001067 if (!factory_->media_transport_factory()) {
1068 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001069 << "PeerConnecton is initialized with use_media_transport = true or "
1070 << "use_media_transport_for_data_channels = true "
1071 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001072 return false;
1073 }
1074
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001075 if (configuration.use_media_transport ||
1076 configuration.use_media_transport_for_data_channels) {
1077 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1078 // RTP media transport is introduced. But until then, we require SDES to
1079 // be enabled.
1080 if (configuration.enable_dtls_srtp.has_value() &&
1081 configuration.enable_dtls_srtp.value()) {
1082 RTC_LOG(LS_WARNING)
1083 << "When media transport is used, SDES must be enabled. Set "
1084 "configuration.enable_dtls_srtp to false. use_media_transport="
1085 << configuration.use_media_transport
1086 << ", use_media_transport_for_data_channels="
1087 << configuration.use_media_transport_for_data_channels;
1088 return false;
1089 }
1090 }
1091
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001092 config.use_media_transport_for_media = configuration.use_media_transport;
1093 config.use_media_transport_for_data_channels =
1094 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001095 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001096 config.use_datagram_transport_for_data_channels =
1097 use_datagram_transport_for_data_channels_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001098 config.media_transport_factory = factory_->media_transport_factory();
1099 }
1100
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07001101 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1102 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1103 if (!configuration.certificates.empty()) {
1104 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1105 // just picking the first one. The decision should be made based on the DTLS
1106 // handshake. The DTLS negotiations need to know about all certificates.
1107 certificate = configuration.certificates[0];
1108 }
1109
1110 if (options.disable_encryption) {
1111 dtls_enabled_ = false;
1112 } else {
1113 // Enable DTLS by default if we have an identity store or a certificate.
1114 dtls_enabled_ = (dependencies.cert_generator || certificate);
1115 // |configuration| can override the default |dtls_enabled_| value.
1116 if (configuration.enable_dtls_srtp) {
1117 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1118 }
1119 }
1120
1121 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1122
1123 if (use_datagram_transport_for_data_channels_) {
1124 if (configuration.enable_rtp_data_channel) {
1125 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1126 "use_datagram_transport_for_data_channels are "
1127 "incompatible and cannot both be set to true";
1128 return false;
1129 }
1130 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1131 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1132 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1133 } else {
1134 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1135 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1136 config.sctp_factory = sctp_factory_.get();
1137 }
1138 } else if (configuration.use_media_transport_for_data_channels) {
1139 if (configuration.enable_rtp_data_channel) {
1140 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1141 "use_media_transport_for_data_channels are "
1142 "incompatible and cannot both be set to true";
1143 return false;
1144 }
1145 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1146 } else if (configuration.enable_rtp_data_channel) {
1147 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1148 // set. It takes precendence over the disable_sctp_data_channels
1149 // PeerConnectionFactoryInterface::Options.
1150 data_channel_type_ = cricket::DCT_RTP;
1151 } else {
1152 // DTLS has to be enabled to use SCTP.
1153 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1154 data_channel_type_ = cricket::DCT_SCTP;
1155 config.sctp_factory = sctp_factory_.get();
1156 }
1157 }
1158
Zhi Huange830e682018-03-30 10:48:35 -07001159 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001160 signaling_thread(), network_thread(), port_allocator_.get(),
1161 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001162 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001163 this, &PeerConnection::OnTransportControllerConnectionState);
1164 transport_controller_->SignalStandardizedIceConnectionState.connect(
1165 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001166 transport_controller_->SignalConnectionState.connect(
1167 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001168 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001169 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001170 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001171 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001172 transport_controller_->SignalIceCandidateError.connect(
1173 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001174 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001175 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1176 transport_controller_->SignalDtlsHandshakeError.connect(
1177 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001178 transport_controller_->SignalIceCandidatePairChanged.connect(
1179 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001180
deadbeefab9b2d12015-10-14 11:33:11 -07001181 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001182 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183
Steve Antonba818672017-11-06 10:21:57 -08001184 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001185 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001186
Steve Antond25da372017-11-06 14:50:29 -08001187 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001188
Steve Anton75737c02017-11-06 10:37:17 -08001189 video_options_.screencast_min_bitrate_kbps =
1190 configuration.screencast_min_bitrate;
1191 audio_options_.combined_audio_video_bwe =
1192 configuration.combined_audio_video_bwe;
1193
1194 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001195 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001196
1197 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001198 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001199
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001200 audio_options_.audio_jitter_buffer_min_delay_ms =
1201 configuration.audio_jitter_buffer_min_delay_ms;
1202
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001203 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1204 configuration.audio_jitter_buffer_enable_rtx_handling;
1205
Steve Anton75737c02017-11-06 10:37:17 -08001206 // Whether the certificate generator/certificate is null or not determines
1207 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1208 // the right instructions by clearing the variables if needed.
1209 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001210 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001211 certificate = nullptr;
1212 } else if (certificate) {
1213 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001214 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001215 }
1216
1217 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1218 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001219 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001220 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1221 this, &PeerConnection::OnCertificateReady);
1222
1223 if (options.disable_encryption) {
1224 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1225 }
1226
1227 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001228 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001229 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230
Steve Anton4171afb2017-11-20 10:20:22 -08001231 // Add default audio/video transceivers for Plan B SDP.
1232 if (!IsUnifiedPlan()) {
1233 transceivers_.push_back(
1234 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1235 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1236 transceivers_.push_back(
1237 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1238 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1239 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001240 int delay_ms =
1241 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001242 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1243 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001244
1245 if (dependencies.video_bitrate_allocator_factory) {
1246 video_bitrate_allocator_factory_ =
1247 std::move(dependencies.video_bitrate_allocator_factory);
1248 } else {
1249 video_bitrate_allocator_factory_ =
1250 CreateBuiltinVideoBitrateAllocatorFactory();
1251 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001252 return true;
1253}
1254
Steve Anton038834f2017-07-14 15:59:59 -07001255RTCError PeerConnection::ValidateConfiguration(
1256 const RTCConfiguration& config) const {
1257 if (config.ice_regather_interval_range &&
1258 config.continual_gathering_policy == GATHER_ONCE) {
1259 return RTCError(RTCErrorType::INVALID_PARAMETER,
1260 "ice_regather_interval_range specified but continual "
1261 "gathering policy is GATHER_ONCE");
1262 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001263 auto result =
1264 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1265 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001266}
1267
Yves Gerey665174f2018-06-19 15:03:05 +02001268rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001269 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001270 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1271 "Plan SdpSemantics. Please use GetSenders "
1272 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001273 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274}
1275
Yves Gerey665174f2018-06-19 15:03:05 +02001276rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001277 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001278 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1279 "Plan SdpSemantics. Please use GetReceivers "
1280 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001281 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282}
1283
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001284bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001285 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001286 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1287 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001288 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 if (IsClosed()) {
1290 return false;
1291 }
deadbeefab9b2d12015-10-14 11:33:11 -07001292 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 return false;
1294 }
deadbeefab9b2d12015-10-14 11:33:11 -07001295
1296 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001297 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1298 observer->SignalAudioTrackAdded.connect(this,
1299 &PeerConnection::OnAudioTrackAdded);
1300 observer->SignalAudioTrackRemoved.connect(
1301 this, &PeerConnection::OnAudioTrackRemoved);
1302 observer->SignalVideoTrackAdded.connect(this,
1303 &PeerConnection::OnVideoTrackAdded);
1304 observer->SignalVideoTrackRemoved.connect(
1305 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001306 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001307
deadbeefab9b2d12015-10-14 11:33:11 -07001308 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001309 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001310 }
1311 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001312 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001313 }
1314
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001315 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001316 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 return true;
1318}
1319
1320void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001321 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001322 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1323 "Plan SdpSemantics. Please use RemoveTrack "
1324 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001325 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001326 if (!IsClosed()) {
1327 for (const auto& track : local_stream->GetAudioTracks()) {
1328 RemoveAudioTrack(track.get(), local_stream);
1329 }
1330 for (const auto& track : local_stream->GetVideoTracks()) {
1331 RemoveVideoTrack(track.get(), local_stream);
1332 }
deadbeefab9b2d12015-10-14 11:33:11 -07001333 }
deadbeefab9b2d12015-10-14 11:33:11 -07001334 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001335 stream_observers_.erase(
1336 std::remove_if(
1337 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001338 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001339 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001340 }),
1341 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001342
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 if (IsClosed()) {
1344 return;
1345 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001346 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347}
1348
Steve Anton2d6c76a2018-01-05 17:10:52 -08001349RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001350 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001351 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001352 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001353 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001354 if (!track) {
1355 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1356 }
1357 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1358 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1359 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1360 "Track has invalid kind: " + track->kind());
1361 }
Steve Antonf9381f02017-12-14 10:23:57 -08001362 if (IsClosed()) {
1363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1364 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001365 }
Steve Anton4171afb2017-11-20 10:20:22 -08001366 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001367 LOG_AND_RETURN_ERROR(
1368 RTCErrorType::INVALID_PARAMETER,
1369 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001370 }
Steve Antonf9381f02017-12-14 10:23:57 -08001371 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001372 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1373 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001374 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001375 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001376 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001377 }
1378 return sender_or_error;
1379}
deadbeefe1f9d832016-01-14 15:35:42 -08001380
Steve Antonf9381f02017-12-14 10:23:57 -08001381RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1382PeerConnection::AddTrackPlanB(
1383 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001384 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001385 if (stream_ids.size() > 1u) {
1386 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1387 "AddTrack with more than one stream is not "
1388 "supported with Plan B semantics.");
1389 }
1390 std::vector<std::string> adjusted_stream_ids = stream_ids;
1391 if (adjusted_stream_ids.empty()) {
1392 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1393 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001394 cricket::MediaType media_type =
1395 (track->kind() == MediaStreamTrackInterface::kAudioKind
1396 ? cricket::MEDIA_TYPE_AUDIO
1397 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001398 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001399 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001400 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001401 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001402 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001403 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001404 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001405 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001406 if (sender_info) {
1407 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001408 }
Steve Antonf9381f02017-12-14 10:23:57 -08001409 } else {
1410 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001411 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001412 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001413 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001414 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001415 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001416 if (sender_info) {
1417 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001418 }
deadbeefe1f9d832016-01-14 15:35:42 -08001419 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001420 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001421}
deadbeefe1f9d832016-01-14 15:35:42 -08001422
Steve Antonf9381f02017-12-14 10:23:57 -08001423RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1424PeerConnection::AddTrackUnifiedPlan(
1425 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001426 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001427 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1428 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001429 RTC_LOG(LS_INFO) << "Reusing an existing "
1430 << cricket::MediaTypeToString(transceiver->media_type())
1431 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001432 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001433 transceiver->internal()->set_direction(
1434 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001435 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001436 transceiver->internal()->set_direction(
1437 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001438 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001439 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001440 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001441 } else {
1442 cricket::MediaType media_type =
1443 (track->kind() == MediaStreamTrackInterface::kAudioKind
1444 ? cricket::MEDIA_TYPE_AUDIO
1445 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001446 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1447 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001448 std::string sender_id = track->id();
1449 // Avoid creating a sender with an existing ID by generating a random ID.
1450 // This can happen if this is the second time AddTrack has created a sender
1451 // for this track.
1452 if (FindSenderById(sender_id)) {
1453 sender_id = rtc::CreateRandomUuid();
1454 }
Florent Castelli892acf02018-10-01 22:47:20 +02001455 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001456 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1457 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001458 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001459 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001460 }
Steve Antonf9381f02017-12-14 10:23:57 -08001461 return transceiver->sender();
1462}
1463
1464rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1465PeerConnection::FindFirstTransceiverForAddedTrack(
1466 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1467 RTC_DCHECK(track);
1468 for (auto transceiver : transceivers_) {
1469 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001470 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001471 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001472 !transceiver->internal()->has_ever_been_used_to_send() &&
1473 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001474 return transceiver;
1475 }
1476 }
1477 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001478}
1479
1480bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1481 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001482 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001483}
1484
Steve Anton24db5732018-07-23 10:27:33 -07001485RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001486 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001487 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001488 if (!sender) {
1489 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1490 }
deadbeefe1f9d832016-01-14 15:35:42 -08001491 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001492 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1493 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001494 }
Steve Antonf9381f02017-12-14 10:23:57 -08001495 if (IsUnifiedPlan()) {
1496 auto transceiver = FindTransceiverBySender(sender);
1497 if (!transceiver || !sender->track()) {
1498 return RTCError::OK();
1499 }
1500 sender->SetTrack(nullptr);
1501 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001502 transceiver->internal()->set_direction(
1503 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001504 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001505 transceiver->internal()->set_direction(
1506 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001507 }
Steve Anton4171afb2017-11-20 10:20:22 -08001508 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001509 bool removed;
1510 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1511 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1512 } else {
1513 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1514 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1515 }
1516 if (!removed) {
1517 LOG_AND_RETURN_ERROR(
1518 RTCErrorType::INVALID_PARAMETER,
1519 "Couldn't find sender " + sender->id() + " to remove.");
1520 }
Steve Anton4171afb2017-11-20 10:20:22 -08001521 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001522 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001523 return RTCError::OK();
1524}
1525
1526rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1527PeerConnection::FindTransceiverBySender(
1528 rtc::scoped_refptr<RtpSenderInterface> sender) {
1529 for (auto transceiver : transceivers_) {
1530 if (transceiver->sender() == sender) {
1531 return transceiver;
1532 }
1533 }
1534 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001535}
1536
Steve Anton9158ef62017-11-27 13:01:52 -08001537RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1538PeerConnection::AddTransceiver(
1539 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1540 return AddTransceiver(track, RtpTransceiverInit());
1541}
1542
1543RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1544PeerConnection::AddTransceiver(
1545 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1546 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001547 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001548 RTC_CHECK(IsUnifiedPlan())
1549 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001550 if (!track) {
1551 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1552 }
1553 cricket::MediaType media_type;
1554 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1555 media_type = cricket::MEDIA_TYPE_AUDIO;
1556 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1557 media_type = cricket::MEDIA_TYPE_VIDEO;
1558 } else {
1559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1560 "Track kind is not audio or video");
1561 }
1562 return AddTransceiver(media_type, track, init);
1563}
1564
1565RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1566PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1567 return AddTransceiver(media_type, RtpTransceiverInit());
1568}
1569
1570RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1571PeerConnection::AddTransceiver(cricket::MediaType media_type,
1572 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001573 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001574 RTC_CHECK(IsUnifiedPlan())
1575 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001576 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1577 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1578 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1579 "media type is not audio or video");
1580 }
1581 return AddTransceiver(media_type, nullptr, init);
1582}
1583
1584RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1585PeerConnection::AddTransceiver(
1586 cricket::MediaType media_type,
1587 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001588 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001589 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001590 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1591 media_type == cricket::MEDIA_TYPE_VIDEO));
1592 if (track) {
1593 RTC_DCHECK_EQ(media_type,
1594 (track->kind() == MediaStreamTrackInterface::kAudioKind
1595 ? cricket::MEDIA_TYPE_AUDIO
1596 : cricket::MEDIA_TYPE_VIDEO));
1597 }
1598
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001599 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1600 init.send_encodings.size(), 0, 7, 8);
1601
Amit Hilbuchaa584152019-02-06 17:09:52 -08001602 size_t num_rids = absl::c_count_if(init.send_encodings,
1603 [](const RtpEncodingParameters& encoding) {
1604 return !encoding.rid.empty();
1605 });
1606 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001607 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001608 RTCErrorType::INVALID_PARAMETER,
1609 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001610 }
1611
Amit Hilbuchf4770402019-04-08 14:11:57 -07001612 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1613 [](const RtpEncodingParameters& encoding) {
1614 return !IsLegalRsidName(encoding.rid);
1615 })) {
1616 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1617 "Invalid RID value provided.");
1618 }
1619
Amit Hilbuchaa584152019-02-06 17:09:52 -08001620 if (absl::c_any_of(init.send_encodings,
1621 [](const RtpEncodingParameters& encoding) {
1622 return encoding.ssrc.has_value();
1623 })) {
1624 LOG_AND_RETURN_ERROR(
1625 RTCErrorType::UNSUPPORTED_PARAMETER,
1626 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001627 }
1628
1629 RtpParameters parameters;
1630 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001631
1632 // Encodings are dropped from the tail if too many are provided.
1633 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1634 parameters.encodings.erase(
1635 parameters.encodings.begin() + kMaxSimulcastStreams,
1636 parameters.encodings.end());
1637 }
1638
1639 // Single RID should be removed.
1640 if (parameters.encodings.size() == 1 &&
1641 !parameters.encodings[0].rid.empty()) {
1642 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1643 parameters.encodings[0].rid.clear();
1644 }
1645
1646 // If RIDs were not provided, they are generated for simulcast scenario.
1647 if (parameters.encodings.size() > 1 && num_rids == 0) {
1648 rtc::UniqueStringGenerator rid_generator;
1649 for (RtpEncodingParameters& encoding : parameters.encodings) {
1650 encoding.rid = rid_generator();
1651 }
1652 }
1653
Florent Castelli892acf02018-10-01 22:47:20 +02001654 if (UnimplementedRtpParameterHasValue(parameters)) {
1655 LOG_AND_RETURN_ERROR(
1656 RTCErrorType::UNSUPPORTED_PARAMETER,
1657 "Attempted to set an unimplemented parameter of RtpParameters.");
1658 }
Steve Anton9158ef62017-11-27 13:01:52 -08001659
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001660 auto result = cricket::CheckRtpParametersValues(parameters);
1661 if (!result.ok()) {
1662 LOG_AND_RETURN_ERROR(result.type(), result.message());
1663 }
1664
Steve Anton3d954a62018-04-02 11:27:23 -07001665 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1666 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001667 // Set the sender ID equal to the track ID if the track is specified unless
1668 // that sender ID is already in use.
1669 std::string sender_id =
1670 (track && !FindSenderById(track->id()) ? track->id()
1671 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001672 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001673 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001674 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1675 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1676 transceiver->internal()->set_direction(init.direction);
1677
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001678 if (update_negotiation_needed) {
1679 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001680 }
Steve Antonf9381f02017-12-14 10:23:57 -08001681
1682 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1683}
1684
Steve Anton02ee47c2018-01-10 16:26:06 -08001685rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1686PeerConnection::CreateSender(
1687 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001688 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001689 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001690 const std::vector<std::string>& stream_ids,
1691 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001692 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001693 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001694 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1695 RTC_DCHECK(!track ||
1696 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1697 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1698 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001699 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001700 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001701 } else {
1702 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1703 RTC_DCHECK(!track ||
1704 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1705 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001706 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001707 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001708 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001709 bool set_track_succeeded = sender->SetTrack(track);
1710 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001711 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001712 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001713 return sender;
1714}
1715
1716rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1717PeerConnection::CreateReceiver(cricket::MediaType media_type,
1718 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001719 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1720 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001721 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001722 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001723 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1724 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001725 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001726 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001727 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001728 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001729 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1730 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001731 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001732 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001733 return receiver;
1734}
1735
1736rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1737PeerConnection::CreateAndAddTransceiver(
1738 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1739 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1740 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001741 // Ensure that the new sender does not have an ID that is already in use by
1742 // another sender.
1743 // Allow receiver IDs to conflict since those come from remote SDP (which
1744 // could be invalid, but should not cause a crash).
1745 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001746 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001747 signaling_thread(),
1748 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001749 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001750 transceiver->internal()->SignalNegotiationNeeded.connect(
1751 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001752 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001753}
1754
Steve Anton52d86772018-02-20 15:48:12 -08001755void PeerConnection::OnNegotiationNeeded() {
1756 RTC_DCHECK_RUN_ON(signaling_thread());
1757 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001758 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001759}
1760
deadbeeffac06552015-11-25 11:26:01 -08001761rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001762 const std::string& kind,
1763 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001764 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001765 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1766 "Plan SdpSemantics. Please use AddTransceiver "
1767 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001768 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001769 if (IsClosed()) {
1770 return nullptr;
1771 }
Steve Anton4171afb2017-11-20 10:20:22 -08001772
Seth Hampson5b4f0752018-04-02 16:31:36 -07001773 // Internally we need to have one stream with Plan B semantics, so we
1774 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001775 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001776 if (stream_id.empty()) {
1777 stream_ids.push_back(rtc::CreateRandomUuid());
1778 RTC_LOG(LS_INFO)
1779 << "No stream_id specified for sender. Generated stream ID: "
1780 << stream_ids[0];
1781 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001782 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001783 }
1784
Steve Anton4171afb2017-11-20 10:20:22 -08001785 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001786 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001787 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001788 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001789 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001790 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001791 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001792 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001793 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001794 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001795 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001796 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001797 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001798 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001799 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001800 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001801 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001802 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001803 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001804 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001805 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001806
deadbeefe1f9d832016-01-14 15:35:42 -08001807 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001808}
1809
deadbeef70ab1a12015-09-28 16:53:55 -07001810std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1811 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001812 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001813 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001814 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001815 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001816 }
1817 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001818}
1819
Steve Anton4171afb2017-11-20 10:20:22 -08001820std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1821PeerConnection::GetSendersInternal() const {
1822 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1823 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001824 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001825 auto senders = transceiver->internal()->senders();
1826 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1827 }
1828 return all_senders;
1829}
1830
deadbeef70ab1a12015-09-28 16:53:55 -07001831std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1832PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001833 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001834 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001835 for (const auto& receiver : GetReceiversInternal()) {
1836 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001837 }
1838 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001839}
1840
Steve Anton4171afb2017-11-20 10:20:22 -08001841std::vector<
1842 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1843PeerConnection::GetReceiversInternal() const {
1844 std::vector<
1845 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1846 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001847 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001848 auto receivers = transceiver->internal()->receivers();
1849 all_receivers.insert(all_receivers.end(), receivers.begin(),
1850 receivers.end());
1851 }
1852 return all_receivers;
1853}
1854
Steve Anton9158ef62017-11-27 13:01:52 -08001855std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1856PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001857 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001858 RTC_CHECK(IsUnifiedPlan())
1859 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001860 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001861 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001862 all_transceivers.push_back(transceiver);
1863 }
1864 return all_transceivers;
1865}
1866
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001867bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001868 MediaStreamTrackInterface* track,
1869 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001870 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001871 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001872 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001873 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001874 return false;
1875 }
1876
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001877 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001878 // The StatsCollector is used to tell if a track is valid because it may
1879 // remember tracks that the PeerConnection previously removed.
1880 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001881 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1882 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001883 return false;
1884 }
Steve Antonad182762018-09-05 20:22:40 +00001885 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1886 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 return true;
1888}
1889
hbos74e1a4f2016-09-15 23:33:01 -07001890void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001891 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001892 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001893 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001894 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001895 stats_collector_->GetStatsReport(callback);
1896}
1897
Henrik Boström1df1bf82018-03-20 13:24:20 +01001898void PeerConnection::GetStats(
1899 rtc::scoped_refptr<RtpSenderInterface> selector,
1900 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1901 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001902 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001903 RTC_DCHECK(callback);
1904 RTC_DCHECK(stats_collector_);
1905 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1906 if (selector) {
1907 for (const auto& proxy_transceiver : transceivers_) {
1908 for (const auto& proxy_sender :
1909 proxy_transceiver->internal()->senders()) {
1910 if (proxy_sender == selector) {
1911 internal_sender = proxy_sender->internal();
1912 break;
1913 }
1914 }
1915 if (internal_sender)
1916 break;
1917 }
1918 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001919 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001920 // belong to the PeerConnection (in Plan B, senders can be removed from the
1921 // PeerConnection). This means that "all the stats objects representing the
1922 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1923 // produces an empty stats report.
1924 stats_collector_->GetStatsReport(internal_sender, callback);
1925}
1926
1927void PeerConnection::GetStats(
1928 rtc::scoped_refptr<RtpReceiverInterface> selector,
1929 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1930 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001931 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001932 RTC_DCHECK(callback);
1933 RTC_DCHECK(stats_collector_);
1934 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1935 if (selector) {
1936 for (const auto& proxy_transceiver : transceivers_) {
1937 for (const auto& proxy_receiver :
1938 proxy_transceiver->internal()->receivers()) {
1939 if (proxy_receiver == selector) {
1940 internal_receiver = proxy_receiver->internal();
1941 break;
1942 }
1943 }
1944 if (internal_receiver)
1945 break;
1946 }
1947 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001948 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001949 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1950 // the PeerConnection). This means that "all the stats objects representing
1951 // the selector" is an empty set. Invoking GetStatsReport() with a null
1952 // selector produces an empty stats report.
1953 stats_collector_->GetStatsReport(internal_receiver, callback);
1954}
1955
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001956PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001957 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001958 return signaling_state_;
1959}
1960
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001961PeerConnectionInterface::IceConnectionState
1962PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001963 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 return ice_connection_state_;
1965}
1966
Alex Loiko9289eda2018-11-23 16:18:59 +00001967PeerConnectionInterface::IceConnectionState
1968PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001969 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001970 return standardized_ice_connection_state_;
1971}
1972
Jonas Olsson635474e2018-10-18 15:58:17 +02001973PeerConnectionInterface::PeerConnectionState
1974PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001975 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001976 return connection_state_;
1977}
1978
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001979PeerConnectionInterface::IceGatheringState
1980PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001981 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982 return ice_gathering_state_;
1983}
1984
Yves Gerey665174f2018-06-19 15:03:05 +02001985rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 const std::string& label,
1987 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001988 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001989 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001990
deadbeefab9b2d12015-10-14 11:33:11 -07001991 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001992
kwibergd1fe2812016-04-27 06:47:29 -07001993 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001994 if (config) {
1995 internal_config.reset(new InternalDataChannelInit(*config));
1996 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001997 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001998 InternalCreateDataChannel(label, internal_config.get()));
1999 if (!channel.get()) {
2000 return nullptr;
2001 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002003 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2004 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002005 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002006 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002007 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002008 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 return DataChannelProxy::Create(signaling_thread(), channel.get());
2010}
2011
Henrik Boström79b69802019-07-18 11:16:56 +02002012void PeerConnection::RestartIce() {
2013 RTC_DCHECK_RUN_ON(signaling_thread());
2014 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2015 current_local_description_.get(), pending_local_description_.get());
2016 UpdateNegotiationNeeded();
2017}
2018
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002019void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002020 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002021 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002022 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002023
nisse7ce109a2017-01-31 00:57:56 -08002024 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002025 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002026 return;
2027 }
deadbeefab9b2d12015-10-14 11:33:11 -07002028
Steve Anton8d3444d2017-10-20 15:30:51 -07002029 if (IsClosed()) {
2030 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002031 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002032 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002033 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002034 return;
2035 }
2036
Steve Anton25ca0ac2019-06-25 10:40:48 -07002037 // If a session error has occurred the PeerConnection is in a possibly
2038 // inconsistent state so fail right away.
2039 if (session_error() != SessionError::kNone) {
2040 std::string error_message = GetSessionErrorMsg();
2041 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2042 PostCreateSessionDescriptionFailure(
2043 observer,
2044 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2045 return;
2046 }
2047
zhihuang1c378ed2017-08-17 14:10:50 -07002048 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002049 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002050 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002051 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002052 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002053 return;
2054 }
2055
Steve Anton22da89f2018-01-25 13:58:07 -08002056 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2057 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2058 if (IsUnifiedPlan()) {
2059 RTCError error = HandleLegacyOfferOptions(options);
2060 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002061 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002062 return;
2063 }
2064 }
2065
zhihuang1c378ed2017-08-17 14:10:50 -07002066 cricket::MediaSessionOptions session_options;
2067 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002068 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002069}
2070
Steve Anton22da89f2018-01-25 13:58:07 -08002071RTCError PeerConnection::HandleLegacyOfferOptions(
2072 const RTCOfferAnswerOptions& options) {
2073 RTC_DCHECK(IsUnifiedPlan());
2074
2075 if (options.offer_to_receive_audio == 0) {
2076 RemoveRecvDirectionFromReceivingTransceiversOfType(
2077 cricket::MEDIA_TYPE_AUDIO);
2078 } else if (options.offer_to_receive_audio == 1) {
2079 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2080 } else if (options.offer_to_receive_audio > 1) {
2081 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2082 "offer_to_receive_audio > 1 is not supported.");
2083 }
2084
2085 if (options.offer_to_receive_video == 0) {
2086 RemoveRecvDirectionFromReceivingTransceiversOfType(
2087 cricket::MEDIA_TYPE_VIDEO);
2088 } else if (options.offer_to_receive_video == 1) {
2089 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2090 } else if (options.offer_to_receive_video > 1) {
2091 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2092 "offer_to_receive_video > 1 is not supported.");
2093 }
2094
2095 return RTCError::OK();
2096}
2097
2098void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2099 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002100 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002101 RtpTransceiverDirection new_direction =
2102 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2103 if (new_direction != transceiver->direction()) {
2104 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2105 << " transceiver (MID="
2106 << transceiver->mid().value_or("<not set>") << ") from "
2107 << RtpTransceiverDirectionToString(
2108 transceiver->direction())
2109 << " to "
2110 << RtpTransceiverDirectionToString(new_direction)
2111 << " since CreateOffer specified offer_to_receive=0";
2112 transceiver->internal()->set_direction(new_direction);
2113 }
Steve Anton22da89f2018-01-25 13:58:07 -08002114 }
2115}
2116
2117void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2118 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002119 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002120 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002121 RTC_LOG(LS_INFO)
2122 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2123 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002124 RtpTransceiverInit init;
2125 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002126 AddTransceiver(media_type, nullptr, init,
2127 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002128 }
2129}
2130
2131std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2132PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2133 std::vector<
2134 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2135 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002136 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002137 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002138 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2139 receiving_transceivers.push_back(transceiver);
2140 }
2141 }
2142 return receiving_transceivers;
2143}
2144
htaa2a49d92016-03-04 02:51:39 -08002145void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2146 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002147 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002148 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002149 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002150 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002151 return;
2152 }
2153
Steve Anton25ca0ac2019-06-25 10:40:48 -07002154 // If a session error has occurred the PeerConnection is in a possibly
2155 // inconsistent state so fail right away.
2156 if (session_error() != SessionError::kNone) {
2157 std::string error_message = GetSessionErrorMsg();
2158 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2159 PostCreateSessionDescriptionFailure(
2160 observer,
2161 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2162 return;
2163 }
2164
Steve Antondffead82018-02-06 10:31:29 -08002165 if (!(signaling_state_ == kHaveRemoteOffer ||
2166 signaling_state_ == kHaveLocalPrAnswer)) {
2167 std::string error =
2168 "PeerConnection cannot create an answer in a state other than "
2169 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002170 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002171 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002172 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002173 return;
2174 }
2175
Steve Antondffead82018-02-06 10:31:29 -08002176 // The remote description should be set if we're in the right state.
2177 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002178
Steve Anton22da89f2018-01-25 13:58:07 -08002179 if (IsUnifiedPlan()) {
2180 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2181 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2182 "supported with Unified Plan semantics. Use the "
2183 "RtpTransceiver API instead.";
2184 }
2185 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2186 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2187 "supported with Unified Plan semantics. Use the "
2188 "RtpTransceiver API instead.";
2189 }
2190 }
2191
htaa2a49d92016-03-04 02:51:39 -08002192 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002193 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002194
Steve Antond25da372017-11-06 14:50:29 -08002195 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196}
2197
2198void PeerConnection::SetLocalDescription(
2199 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002200 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002201 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002202 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002203
Steve Anton80dd7b52018-02-16 17:08:42 -08002204 // The SetLocalDescription contract is that we take ownership of the session
2205 // description regardless of the outcome, so wrap it in a unique_ptr right
2206 // away. Ideally, SetLocalDescription's signature will be changed to take the
2207 // description as a unique_ptr argument to formalize this agreement.
2208 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2209
nisse7ce109a2017-01-31 00:57:56 -08002210 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002211 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002212 return;
2213 }
Steve Anton8a006912017-12-04 15:25:56 -08002214
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002216 PostSetSessionDescriptionFailure(
2217 observer,
2218 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219 return;
2220 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002221
Steve Anton80dd7b52018-02-16 17:08:42 -08002222 // If a session error has occurred the PeerConnection is in a possibly
2223 // inconsistent state so fail right away.
2224 if (session_error() != SessionError::kNone) {
2225 std::string error_message = GetSessionErrorMsg();
2226 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002227 PostSetSessionDescriptionFailure(
2228 observer,
2229 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002230 return;
2231 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002232
Steve Anton80dd7b52018-02-16 17:08:42 -08002233 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2234 if (!error.ok()) {
2235 std::string error_message = GetSetDescriptionErrorMessage(
2236 cricket::CS_LOCAL, desc->GetType(), error);
2237 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002238 PostSetSessionDescriptionFailure(
2239 observer,
2240 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002241 return;
2242 }
2243
2244 // Grab the description type before moving ownership to ApplyLocalDescription,
2245 // which may destroy it before returning.
2246 const SdpType type = desc->GetType();
2247
2248 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002249 // |desc| may be destroyed at this point.
2250
2251 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002252 // If ApplyLocalDescription fails, the PeerConnection could be in an
2253 // inconsistent state, so act conservatively here and set the session error
2254 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2255 SetSessionError(SessionError::kContent, error.message());
2256 std::string error_message =
2257 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2258 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002259 PostSetSessionDescriptionFailure(
2260 observer,
2261 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002262 return;
2263 }
Steve Anton8a006912017-12-04 15:25:56 -08002264 RTC_DCHECK(local_description());
2265
2266 PostSetSessionDescriptionSuccess(observer);
2267
Steve Antonad182762018-09-05 20:22:40 +00002268 // MaybeStartGathering needs to be called after posting
2269 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2270 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002271 transport_controller_->MaybeStartGathering();
2272
Steve Antona3a92c22017-12-07 10:27:41 -08002273 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002274 // TODO(deadbeef): We already had to hop to the network thread for
2275 // MaybeStartGathering...
2276 network_thread()->Invoke<void>(
2277 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2278 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002279 // Make UMA notes about what was agreed to.
2280 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002281 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002282
2283 if (IsUnifiedPlan()) {
2284 bool was_negotiation_needed = is_negotiation_needed_;
2285 UpdateNegotiationNeeded();
2286 if (signaling_state() == kStable && was_negotiation_needed &&
2287 is_negotiation_needed_) {
2288 Observer()->OnRenegotiationNeeded();
2289 }
2290 }
2291
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002292 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002293}
2294
2295RTCError PeerConnection::ApplyLocalDescription(
2296 std::unique_ptr<SessionDescriptionInterface> desc) {
2297 RTC_DCHECK_RUN_ON(signaling_thread());
2298 RTC_DCHECK(desc);
2299
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 // Update stats here so that we have the most recent stats for tracks and
2301 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002302 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002303
Steve Antondcc3c022017-12-22 16:02:54 -08002304 // Take a reference to the old local description since it's used below to
2305 // compare against the new local description. When setting the new local
2306 // description, grab ownership of the replaced session description in case it
2307 // is the same as |old_local_description|, to keep it alive for the duration
2308 // of the method.
2309 const SessionDescriptionInterface* old_local_description =
2310 local_description();
2311 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002312 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002313 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002314 replaced_local_description = pending_local_description_
2315 ? std::move(pending_local_description_)
2316 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002317 current_local_description_ = std::move(desc);
2318 pending_local_description_ = nullptr;
2319 current_remote_description_ = std::move(pending_remote_description_);
2320 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002321 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002322 pending_local_description_ = std::move(desc);
2323 }
2324 // The session description to apply now must be accessed by
2325 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002326 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002327
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002328 // Report statistics about any use of simulcast.
2329 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2330 *local_description()->description());
2331
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002332 if (!is_caller_) {
2333 if (remote_description()) {
2334 // Remote description was applied first, so this PC is the callee.
2335 is_caller_ = false;
2336 } else {
2337 // Local description is applied first, so this PC is the caller.
2338 is_caller_ = true;
2339 }
2340 }
2341
Zhi Huange830e682018-03-30 10:48:35 -07002342 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2343 if (!error.ok()) {
2344 return error;
2345 }
2346
Steve Antondcc3c022017-12-22 16:02:54 -08002347 if (IsUnifiedPlan()) {
2348 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002349 cricket::CS_LOCAL, *local_description(), old_local_description,
2350 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002351 if (!error.ok()) {
2352 return error;
2353 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002354 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2355 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002356 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002357 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2358 // Note that code paths that don't set MID won't be able to use
2359 // information about DTLS transports.
2360 if (transceiver->mid()) {
2361 auto dtls_transport =
2362 LookupDtlsTransportByMidInternal(*transceiver->mid());
2363 transceiver->internal()->sender_internal()->set_transport(
2364 dtls_transport);
2365 transceiver->internal()->receiver_internal()->set_transport(
2366 dtls_transport);
2367 }
2368
Steve Antondcc3c022017-12-22 16:02:54 -08002369 const ContentInfo* content =
2370 FindMediaSectionForTransceiver(transceiver, local_description());
2371 if (!content) {
2372 continue;
2373 }
2374 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002375 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2376 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002377 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002378 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2379 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2380 // "recvonly", process the removal of a remote track for the media
2381 // description, given transceiver, removeList, and muteTracks.
2382 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2383 (transceiver->internal()->fired_direction() &&
2384 RtpTransceiverDirectionHasRecv(
2385 *transceiver->internal()->fired_direction()))) {
2386 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2387 &removed_streams);
2388 }
2389 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2390 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002391 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002392 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002393 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002394 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002395 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002396 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002397 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002398 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002399 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002400 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002401 }
2402 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002403 // Media channels will be created only when offer is set. These may use new
2404 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002405 if (type == SdpType::kOffer) {
2406 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2407 // description is applied. Restore back to old description.
2408 RTCError error = CreateChannels(*local_description()->description());
2409 if (!error.ok()) {
2410 return error;
2411 }
2412 }
Steve Antondcc3c022017-12-22 16:02:54 -08002413 // Remove unused channels if MediaContentDescription is rejected.
2414 RemoveUnusedChannels(local_description()->description());
2415 }
Steve Anton8a006912017-12-04 15:25:56 -08002416
Zhi Huange830e682018-03-30 10:48:35 -07002417 error = UpdateSessionState(type, cricket::CS_LOCAL,
2418 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002419 if (!error.ok()) {
2420 return error;
2421 }
Steve Antondcc3c022017-12-22 16:02:54 -08002422
Steve Anton8a006912017-12-04 15:25:56 -08002423 if (remote_description()) {
2424 // Now that we have a local description, we can push down remote candidates.
2425 UseCandidatesInSessionDescription(remote_description());
2426 }
2427
2428 pending_ice_restarts_.clear();
2429 if (session_error() != SessionError::kNone) {
2430 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2431 }
2432
deadbeefab9b2d12015-10-14 11:33:11 -07002433 // If setting the description decided our SSL role, allocate any necessary
2434 // SCTP sids.
2435 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002436 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002437 AllocateSctpSids(role);
2438 }
2439
Steve Antond3679212018-01-17 17:41:02 -08002440 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002441 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002442 const ContentInfo* content =
2443 FindMediaSectionForTransceiver(transceiver, local_description());
2444 if (!content) {
2445 continue;
2446 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002447 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2448 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002449 // 0 is a special value meaning "this sender has no associated send
2450 // stream". Need to call this so the sender won't attempt to configure
2451 // a no longer existing stream and run into DCHECKs in the lower
2452 // layers.
2453 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002454 } else {
2455 // Get the StreamParams from the channel which could generate SSRCs.
2456 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002457 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002458 streams[0].stream_ids());
2459 transceiver->internal()->sender_internal()->SetSsrc(
2460 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002461 }
2462 }
2463 } else {
2464 // Plan B semantics.
2465
Steve Antondcc3c022017-12-22 16:02:54 -08002466 // Update state and SSRC of local MediaStreams and DataChannels based on the
2467 // local session description.
2468 const cricket::ContentInfo* audio_content =
2469 GetFirstAudioContent(local_description()->description());
2470 if (audio_content) {
2471 if (audio_content->rejected) {
2472 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2473 } else {
2474 const cricket::AudioContentDescription* audio_desc =
2475 audio_content->media_description()->as_audio();
2476 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2477 }
deadbeeffaac4972015-11-12 15:33:07 -08002478 }
deadbeefab9b2d12015-10-14 11:33:11 -07002479
Steve Antondcc3c022017-12-22 16:02:54 -08002480 const cricket::ContentInfo* video_content =
2481 GetFirstVideoContent(local_description()->description());
2482 if (video_content) {
2483 if (video_content->rejected) {
2484 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2485 } else {
2486 const cricket::VideoContentDescription* video_desc =
2487 video_content->media_description()->as_video();
2488 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2489 }
deadbeeffaac4972015-11-12 15:33:07 -08002490 }
deadbeefab9b2d12015-10-14 11:33:11 -07002491 }
2492
2493 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002494 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002495 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002496 const cricket::RtpDataContentDescription* rtp_data_desc =
2497 data_content->media_description()->as_rtp_data();
2498 // rtp_data_desc will be null if this is an SCTP description.
2499 if (rtp_data_desc) {
2500 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002501 }
2502 }
2503
Henrik Boström79b69802019-07-18 11:16:56 +02002504 if (type == SdpType::kAnswer &&
2505 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2506 *current_local_description_)) {
2507 local_ice_credentials_to_replace_->ClearIceCredentials();
2508 }
2509
Steve Anton8a006912017-12-04 15:25:56 -08002510 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002511}
2512
Steve Anton06817cd2018-12-18 15:55:30 -08002513// The SDP parser used to populate these values by default for the 'content
2514// name' if an a=mid line was absent.
2515static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2516 switch (media_type) {
2517 case cricket::MEDIA_TYPE_AUDIO:
2518 return cricket::CN_AUDIO;
2519 case cricket::MEDIA_TYPE_VIDEO:
2520 return cricket::CN_VIDEO;
2521 case cricket::MEDIA_TYPE_DATA:
2522 return cricket::CN_DATA;
2523 }
2524 RTC_NOTREACHED();
2525 return "";
2526}
2527
2528void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002529 cricket::SessionDescription* new_remote_description) {
2530 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002531 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002532 const cricket::ContentInfos& local_contents =
2533 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002534 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002535 const cricket::ContentInfos& remote_contents =
2536 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002537 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002538 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2539 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002540 if (!content.name.empty()) {
2541 continue;
2542 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002543 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002544 absl::string_view source_explanation;
2545 if (IsUnifiedPlan()) {
2546 if (i < local_contents.size()) {
2547 new_mid = local_contents[i].name;
2548 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002549 } else if (i < remote_contents.size()) {
2550 new_mid = remote_contents[i].name;
2551 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002552 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002553 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002554 source_explanation = "generated just now";
2555 }
2556 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002557 new_mid = std::string(
2558 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002559 source_explanation = "to match pre-existing behavior";
2560 }
Steve Antond7180cc2019-02-07 10:44:53 -08002561 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002562 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002563 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002564 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2565 << " is missing an a=mid line. Filling in the value '"
2566 << new_mid << "' " << source_explanation << ".";
2567 }
2568}
2569
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002571 SetSessionDescriptionObserver* observer,
2572 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002573 SetRemoteDescription(
2574 std::unique_ptr<SessionDescriptionInterface>(desc),
2575 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2576 new SetRemoteDescriptionObserverAdapter(this, observer)));
2577}
2578
2579void PeerConnection::SetRemoteDescription(
2580 std::unique_ptr<SessionDescriptionInterface> desc,
2581 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002582 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002583 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002584
nisse7ce109a2017-01-31 00:57:56 -08002585 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002586 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002587 return;
2588 }
Steve Anton8a006912017-12-04 15:25:56 -08002589
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002590 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002591 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002592 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 return;
2594 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002595
Steve Anton80dd7b52018-02-16 17:08:42 -08002596 // If a session error has occurred the PeerConnection is in a possibly
2597 // inconsistent state so fail right away.
2598 if (session_error() != SessionError::kNone) {
2599 std::string error_message = GetSessionErrorMsg();
2600 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2601 observer->OnSetRemoteDescriptionComplete(
2602 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2603 return;
2604 }
Steve Anton71439a62018-02-15 11:53:06 -08002605
Steve Antonba42e992018-04-09 14:10:01 -07002606 if (desc->GetType() == SdpType::kOffer) {
2607 // Report to UMA the format of the received offer.
2608 ReportSdpFormatReceived(*desc);
2609 }
2610
Steve Anton06817cd2018-12-18 15:55:30 -08002611 // Handle remote descriptions missing a=mid lines for interop with legacy end
2612 // points.
2613 FillInMissingRemoteMids(desc->description());
2614
Steve Anton80dd7b52018-02-16 17:08:42 -08002615 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002616 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002617 std::string error_message = GetSetDescriptionErrorMessage(
2618 cricket::CS_REMOTE, desc->GetType(), error);
2619 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002620 observer->OnSetRemoteDescriptionComplete(
2621 RTCError(error.type(), std::move(error_message)));
2622 return;
2623 }
Steve Anton71439a62018-02-15 11:53:06 -08002624
Steve Anton80dd7b52018-02-16 17:08:42 -08002625 // Grab the description type before moving ownership to
2626 // ApplyRemoteDescription, which may destroy it before returning.
2627 const SdpType type = desc->GetType();
2628
2629 error = ApplyRemoteDescription(std::move(desc));
2630 // |desc| may be destroyed at this point.
2631
2632 if (!error.ok()) {
2633 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2634 // inconsistent state, so act conservatively here and set the session error
2635 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2636 SetSessionError(SessionError::kContent, error.message());
2637 std::string error_message =
2638 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2639 RTC_LOG(LS_ERROR) << error_message;
2640 observer->OnSetRemoteDescriptionComplete(
2641 RTCError(error.type(), std::move(error_message)));
2642 return;
2643 }
2644 RTC_DCHECK(remote_description());
2645
2646 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002647 // TODO(deadbeef): We already had to hop to the network thread for
2648 // MaybeStartGathering...
2649 network_thread()->Invoke<void>(
2650 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2651 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002652 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002653 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002654 }
2655
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002656 if (IsUnifiedPlan()) {
2657 bool was_negotiation_needed = is_negotiation_needed_;
2658 UpdateNegotiationNeeded();
2659 if (signaling_state() == kStable && was_negotiation_needed &&
2660 is_negotiation_needed_) {
2661 Observer()->OnRenegotiationNeeded();
2662 }
2663 }
2664
Steve Anton8a006912017-12-04 15:25:56 -08002665 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002666 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002667}
2668
2669RTCError PeerConnection::ApplyRemoteDescription(
2670 std::unique_ptr<SessionDescriptionInterface> desc) {
2671 RTC_DCHECK_RUN_ON(signaling_thread());
2672 RTC_DCHECK(desc);
2673
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002674 // Update stats here so that we have the most recent stats for tracks and
2675 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002676 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002677
Steve Antondcc3c022017-12-22 16:02:54 -08002678 // Take a reference to the old remote description since it's used below to
2679 // compare against the new remote description. When setting the new remote
2680 // description, grab ownership of the replaced session description in case it
2681 // is the same as |old_remote_description|, to keep it alive for the duration
2682 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002683 const SessionDescriptionInterface* old_remote_description =
2684 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002685 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002686 SdpType type = desc->GetType();
2687 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002688 replaced_remote_description = pending_remote_description_
2689 ? std::move(pending_remote_description_)
2690 : std::move(current_remote_description_);
2691 current_remote_description_ = std::move(desc);
2692 pending_remote_description_ = nullptr;
2693 current_local_description_ = std::move(pending_local_description_);
2694 } else {
2695 replaced_remote_description = std::move(pending_remote_description_);
2696 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002697 }
Steve Anton8a006912017-12-04 15:25:56 -08002698 // The session description to apply now must be accessed by
2699 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002700 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002702 // Report statistics about any use of simulcast.
2703 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2704 *remote_description()->description());
2705
Zhi Huange830e682018-03-30 10:48:35 -07002706 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2707 if (!error.ok()) {
2708 return error;
2709 }
Steve Anton8a006912017-12-04 15:25:56 -08002710 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002711 if (IsUnifiedPlan()) {
2712 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002713 cricket::CS_REMOTE, *remote_description(), local_description(),
2714 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002715 if (!error.ok()) {
2716 return error;
2717 }
Steve Antondcc3c022017-12-22 16:02:54 -08002718 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002719 // Media channels will be created only when offer is set. These may use new
2720 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002721 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002722 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002723 // description is applied. Restore back to old description.
2724 RTCError error = CreateChannels(*remote_description()->description());
2725 if (!error.ok()) {
2726 return error;
2727 }
2728 }
Steve Antondcc3c022017-12-22 16:02:54 -08002729 // Remove unused channels if MediaContentDescription is rejected.
2730 RemoveUnusedChannels(remote_description()->description());
2731 }
Steve Anton8a006912017-12-04 15:25:56 -08002732
Zhi Huange830e682018-03-30 10:48:35 -07002733 // NOTE: Candidates allocation will be initiated only when
2734 // SetLocalDescription is called.
2735 error = UpdateSessionState(type, cricket::CS_REMOTE,
2736 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002737 if (!error.ok()) {
2738 return error;
2739 }
2740
2741 if (local_description() &&
2742 !UseCandidatesInSessionDescription(remote_description())) {
2743 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2744 }
2745
2746 if (old_remote_description) {
2747 for (const cricket::ContentInfo& content :
2748 old_remote_description->description()->contents()) {
2749 // Check if this new SessionDescription contains new ICE ufrag and
2750 // password that indicates the remote peer requests an ICE restart.
2751 // TODO(deadbeef): When we start storing both the current and pending
2752 // remote description, this should reset pending_ice_restarts and compare
2753 // against the current description.
2754 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2755 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002756 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002757 pending_ice_restarts_.insert(content.name);
2758 }
2759 } else {
2760 // We retain all received candidates only if ICE is not restarted.
2761 // When ICE is restarted, all previous candidates belong to an old
2762 // generation and should not be kept.
2763 // TODO(deadbeef): This goes against the W3C spec which says the remote
2764 // description should only contain candidates from the last set remote
2765 // description plus any candidates added since then. We should remove
2766 // this once we're sure it won't break anything.
2767 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2768 old_remote_description, content.name, mutable_remote_description());
2769 }
2770 }
2771 }
2772
2773 if (session_error() != SessionError::kNone) {
2774 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2775 }
2776
2777 // Set the the ICE connection state to connecting since the connection may
2778 // become writable with peer reflexive candidates before any remote candidate
2779 // is signaled.
2780 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2781 // is to have a new signal the indicates a change in checking state from the
2782 // transport and expose a new checking() member from transport that can be
2783 // read to determine the current checking state. The existing SignalConnecting
2784 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002785 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002786 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002787 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2788 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2789 }
2790
deadbeefab9b2d12015-10-14 11:33:11 -07002791 // If setting the description decided our SSL role, allocate any necessary
2792 // SCTP sids.
2793 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002794 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002795 AllocateSctpSids(role);
2796 }
2797
Steve Antondcc3c022017-12-22 16:02:54 -08002798 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002799 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002800 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002801 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002802 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002803 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002804 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002805 const ContentInfo* content =
2806 FindMediaSectionForTransceiver(transceiver, remote_description());
2807 if (!content) {
2808 continue;
2809 }
2810 const MediaContentDescription* media_desc = content->media_description();
2811 RtpTransceiverDirection local_direction =
2812 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002813 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2814 // RTCSessionDescription: Set the associated remote streams given
2815 // transceiver.[[Receiver]], msids, addList, and removeList".
2816 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2817 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2818 std::vector<std::string> stream_ids;
2819 if (!media_desc->streams().empty()) {
2820 // The remote description has signaled the stream IDs.
2821 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002822 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002823 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2824 << " (" << GetStreamIdsString(stream_ids) << ").";
2825 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2826 stream_ids, &added_streams,
2827 &removed_streams);
2828 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2829 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2830 // and transceiver's current direction is neither sendrecv nor recvonly,
2831 // process the addition of a remote track for the media description.
2832 if (!transceiver->fired_direction() ||
2833 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2834 RTC_LOG(LS_INFO)
2835 << "Processing the addition of a remote track for MID="
2836 << content->name << ".";
2837 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002838 }
Steve Antondcc3c022017-12-22 16:02:54 -08002839 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002840 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002841 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2842 // removal of a remote track for the media description, given transceiver,
2843 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002844 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002845 (transceiver->fired_direction() &&
2846 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2847 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2848 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002849 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002850 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002851 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002852 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002853 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002854 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002855 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002856 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002857 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002858 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2859 if (transceiver->mid()) {
2860 auto dtls_transport =
2861 LookupDtlsTransportByMidInternal(*transceiver->mid());
2862 transceiver->internal()->sender_internal()->set_transport(
2863 dtls_transport);
2864 transceiver->internal()->receiver_internal()->set_transport(
2865 dtls_transport);
2866 }
Steve Antondcc3c022017-12-22 16:02:54 -08002867 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002868 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002869 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002870 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002871 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2872 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002873 transceiver->Stop();
2874 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002875 if (!content->rejected &&
2876 RtpTransceiverDirectionHasRecv(local_direction)) {
2877 // Set ssrc to 0 in the case of an unsignalled ssrc.
2878 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002879 if (!media_desc->streams().empty() &&
2880 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002881 ssrc = media_desc->streams()[0].first_ssrc();
2882 }
2883 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002884 }
Steve Antondcc3c022017-12-22 16:02:54 -08002885 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002886 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002887 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002888 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002889 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002890 observer->OnTrack(transceiver);
2891 observer->OnAddTrack(transceiver->receiver(),
2892 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002893 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002894 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002895 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002896 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002897 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002898 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002899 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002900 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002901 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002902 }
Steve Antondcc3c022017-12-22 16:02:54 -08002903 }
2904
Henrik Boströmfdb92012017-11-09 19:55:44 +01002905 const cricket::ContentInfo* audio_content =
2906 GetFirstAudioContent(remote_description()->description());
2907 const cricket::ContentInfo* video_content =
2908 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002909 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002910 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002911 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002912 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002913 const cricket::RtpDataContentDescription* rtp_data_desc =
2914 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002915
2916 // Check if the descriptions include streams, just in case the peer supports
2917 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002918 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002919 (audio_desc && !audio_desc->streams().empty()) ||
2920 (video_desc && !video_desc->streams().empty())) {
2921 remote_peer_supports_msid_ = true;
2922 }
deadbeefab9b2d12015-10-14 11:33:11 -07002923
2924 // We wait to signal new streams until we finish processing the description,
2925 // since only at that point will new streams have all their tracks.
2926 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2927
Steve Antondcc3c022017-12-22 16:02:54 -08002928 if (!IsUnifiedPlan()) {
2929 // TODO(steveanton): When removing RTP senders/receivers in response to a
2930 // rejected media section, there is some cleanup logic that expects the
2931 // voice/ video channel to still be set. But in this method the voice/video
2932 // channel would have been destroyed by the SetRemoteDescription caller
2933 // above so the cleanup that relies on them fails to run. The RemoveSenders
2934 // calls should be moved to right before the DestroyChannel calls to fix
2935 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002936
Steve Antondcc3c022017-12-22 16:02:54 -08002937 // Find all audio rtp streams and create corresponding remote AudioTracks
2938 // and MediaStreams.
2939 if (audio_content) {
2940 if (audio_content->rejected) {
2941 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2942 } else {
2943 bool default_audio_track_needed =
2944 !remote_peer_supports_msid_ &&
2945 RtpTransceiverDirectionHasSend(audio_desc->direction());
2946 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2947 default_audio_track_needed, audio_desc->type(),
2948 new_streams);
2949 }
deadbeeffaac4972015-11-12 15:33:07 -08002950 }
deadbeefab9b2d12015-10-14 11:33:11 -07002951
Steve Antondcc3c022017-12-22 16:02:54 -08002952 // Find all video rtp streams and create corresponding remote VideoTracks
2953 // and MediaStreams.
2954 if (video_content) {
2955 if (video_content->rejected) {
2956 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2957 } else {
2958 bool default_video_track_needed =
2959 !remote_peer_supports_msid_ &&
2960 RtpTransceiverDirectionHasSend(video_desc->direction());
2961 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2962 default_video_track_needed, video_desc->type(),
2963 new_streams);
2964 }
deadbeeffaac4972015-11-12 15:33:07 -08002965 }
deadbeefab9b2d12015-10-14 11:33:11 -07002966
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002967 // If this is an RTP data transport, update the DataChannels with the
2968 // information from the remote peer.
2969 if (rtp_data_desc) {
2970 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002971 }
deadbeefab9b2d12015-10-14 11:33:11 -07002972
Steve Antondcc3c022017-12-22 16:02:54 -08002973 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002974 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002975 for (size_t i = 0; i < new_streams->count(); ++i) {
2976 MediaStreamInterface* new_stream = new_streams->at(i);
2977 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002978 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002979 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2980 }
deadbeefab9b2d12015-10-14 11:33:11 -07002981
Steve Antondcc3c022017-12-22 16:02:54 -08002982 UpdateEndedRemoteMediaStreams();
2983 }
deadbeefab9b2d12015-10-14 11:33:11 -07002984
Henrik Boström79b69802019-07-18 11:16:56 +02002985 if (type == SdpType::kAnswer &&
2986 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2987 *current_local_description_)) {
2988 local_ice_credentials_to_replace_->ClearIceCredentials();
2989 }
2990
Steve Anton8a006912017-12-04 15:25:56 -08002991 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002992}
2993
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002994void PeerConnection::SetAssociatedRemoteStreams(
2995 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2996 const std::vector<std::string>& stream_ids,
2997 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2998 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2999 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3000 for (const std::string& stream_id : stream_ids) {
3001 rtc::scoped_refptr<MediaStreamInterface> stream =
3002 remote_streams_->find(stream_id);
3003 if (!stream) {
3004 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3005 MediaStream::Create(stream_id));
3006 remote_streams_->AddStream(stream);
3007 added_streams->push_back(stream);
3008 }
3009 media_streams.push_back(stream);
3010 }
3011 // Special case: "a=msid" missing, use random stream ID.
3012 if (media_streams.empty() &&
3013 !(remote_description()->description()->msid_signaling() &
3014 cricket::kMsidSignalingMediaSection)) {
3015 if (!missing_msid_default_stream_) {
3016 missing_msid_default_stream_ = MediaStreamProxy::Create(
3017 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3018 added_streams->push_back(missing_msid_default_stream_);
3019 }
3020 media_streams.push_back(missing_msid_default_stream_);
3021 }
3022 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3023 receiver->streams();
3024 // SetStreams() will add/remove the receiver's track to/from the streams. This
3025 // differs from the spec - the spec uses an "addList" and "removeList" to
3026 // update the stream-track relationships in a later step. We do this earlier,
3027 // changing the order of things, but the end-result is the same.
3028 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3029 // instead. https://crbug.com/webrtc/9480
3030 receiver->SetStreams(media_streams);
3031 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3032}
3033
Steve Anton0f5400a2018-07-17 14:25:36 -07003034void PeerConnection::ProcessRemovalOfRemoteTrack(
3035 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3036 transceiver,
3037 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3038 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3039 RTC_DCHECK(transceiver->mid());
3040 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3041 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003042 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003043 transceiver->internal()->receiver_internal()->streams();
3044 // This will remove the remote track from the streams.
3045 transceiver->internal()->receiver_internal()->set_stream_ids({});
3046 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003047 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3048}
3049
3050void PeerConnection::RemoveRemoteStreamsIfEmpty(
3051 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3052 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3053 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3054 // streams, see if the stream was removed by checking if this was the last
3055 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003056 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003057 if (remote_stream->GetAudioTracks().empty() &&
3058 remote_stream->GetVideoTracks().empty()) {
3059 remote_streams_->RemoveStream(remote_stream);
3060 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003061 }
3062 }
3063}
3064
Steve Antondcc3c022017-12-22 16:02:54 -08003065RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3066 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003067 const SessionDescriptionInterface& new_session,
3068 const SessionDescriptionInterface* old_local_description,
3069 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003070 RTC_DCHECK(IsUnifiedPlan());
3071
Steve Anton7464fca2018-01-19 11:10:37 -08003072 const cricket::ContentGroup* bundle_group = nullptr;
3073 if (new_session.GetType() == SdpType::kOffer) {
3074 auto bundle_group_or_error =
3075 GetEarlyBundleGroup(*new_session.description());
3076 if (!bundle_group_or_error.ok()) {
3077 return bundle_group_or_error.MoveError();
3078 }
3079 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003080 }
Steve Antondcc3c022017-12-22 16:02:54 -08003081
Steve Antondcc3c022017-12-22 16:02:54 -08003082 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003083 for (size_t i = 0; i < new_contents.size(); ++i) {
3084 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003085 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003086 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003087 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3088 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003089 const cricket::ContentInfo* old_local_content = nullptr;
3090 if (old_local_description &&
3091 i < old_local_description->description()->contents().size()) {
3092 old_local_content =
3093 &old_local_description->description()->contents()[i];
3094 }
3095 const cricket::ContentInfo* old_remote_content = nullptr;
3096 if (old_remote_description &&
3097 i < old_remote_description->description()->contents().size()) {
3098 old_remote_content =
3099 &old_remote_description->description()->contents()[i];
3100 }
Steve Antondcc3c022017-12-22 16:02:54 -08003101 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003102 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3103 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003104 if (!transceiver_or_error.ok()) {
3105 return transceiver_or_error.MoveError();
3106 }
3107 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003108 RTCError error =
3109 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3110 if (!error.ok()) {
3111 return error;
3112 }
3113 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003114 if (GetDataMid() && new_content.name != *GetDataMid()) {
3115 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003116 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3117 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003118 continue;
3119 }
3120 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3121 if (!error.ok()) {
3122 return error;
3123 }
Steve Antondcc3c022017-12-22 16:02:54 -08003124 } else {
3125 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3126 "Unknown section type.");
3127 }
3128 }
3129
3130 return RTCError::OK();
3131}
3132
3133RTCError PeerConnection::UpdateTransceiverChannel(
3134 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3135 transceiver,
3136 const cricket::ContentInfo& content,
3137 const cricket::ContentGroup* bundle_group) {
3138 RTC_DCHECK(IsUnifiedPlan());
3139 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003140 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003141 if (content.rejected) {
3142 if (channel) {
3143 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003144 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003145 }
3146 } else {
3147 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003148 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003149 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003150 } else {
Steve Anton69470252018-02-09 11:43:08 -08003151 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003152 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003153 }
3154 if (!channel) {
3155 LOG_AND_RETURN_ERROR(
3156 RTCErrorType::INTERNAL_ERROR,
3157 "Failed to create channel for mid=" + content.name);
3158 }
3159 transceiver->internal()->SetChannel(channel);
3160 }
3161 }
3162 return RTCError::OK();
3163}
3164
Steve Antonfa2260d2017-12-28 16:38:23 -08003165RTCError PeerConnection::UpdateDataChannel(
3166 cricket::ContentSource source,
3167 const cricket::ContentInfo& content,
3168 const cricket::ContentGroup* bundle_group) {
3169 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003170 // If data channels are disabled, ignore this media section. CreateAnswer
3171 // will take care of rejecting it.
3172 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003173 }
3174 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003175 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003176 DestroyDataChannel();
3177 } else {
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07003178 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003179 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003180 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003181 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3182 "Failed to create data channel.");
3183 }
3184 }
3185 if (source == cricket::CS_REMOTE) {
3186 const MediaContentDescription* data_desc = content.media_description();
3187 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3188 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3189 }
3190 }
3191 }
3192 return RTCError::OK();
3193}
3194
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003195// This method will extract any send encodings that were sent by the remote
3196// connection. This is currently only relevant for Simulcast scenario (where
3197// the number of layers may be communicated by the server).
3198static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3199 const MediaContentDescription& desc) {
3200 if (!desc.HasSimulcast()) {
3201 return {};
3202 }
3203 std::vector<RtpEncodingParameters> result;
3204 const SimulcastDescription& simulcast = desc.simulcast_description();
3205
3206 // This is a remote description, the parameters we are after should appear
3207 // as receive streams.
3208 for (const auto& alternatives : simulcast.receive_layers()) {
3209 RTC_DCHECK(!alternatives.empty());
3210 // There is currently no way to specify or choose from alternatives.
3211 // We will always use the first alternative, which is the most preferred.
3212 const SimulcastLayer& layer = alternatives[0];
3213 RtpEncodingParameters parameters;
3214 parameters.rid = layer.rid;
3215 parameters.active = !layer.is_paused;
3216 result.push_back(parameters);
3217 }
3218
3219 return result;
3220}
3221
3222static RTCError UpdateSimulcastLayerStatusInSender(
3223 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003224 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003225 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003226 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003227 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003228
3229 // The simulcast envelope cannot be changed, only the status of the streams.
3230 // So we will iterate over the send encodings rather than the layers.
3231 for (RtpEncodingParameters& encoding : parameters.encodings) {
3232 auto iter = std::find_if(layers.begin(), layers.end(),
3233 [&encoding](const SimulcastLayer& layer) {
3234 return layer.rid == encoding.rid;
3235 });
3236 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003237 if (iter == layers.end()) {
3238 disabled_layers.push_back(encoding.rid);
3239 continue;
3240 }
3241
3242 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003243 }
3244
Amit Hilbuch619b2942019-02-26 15:55:19 -08003245 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003246 if (result.ok()) {
3247 result = sender->DisableEncodingLayers(disabled_layers);
3248 }
3249
3250 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003251}
3252
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003253static bool SimulcastIsRejected(
3254 const ContentInfo* local_content,
3255 const MediaContentDescription& answer_media_desc) {
3256 bool simulcast_offered = local_content &&
3257 local_content->media_description() &&
3258 local_content->media_description()->HasSimulcast();
3259 bool simulcast_answered = answer_media_desc.HasSimulcast();
3260 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3261 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3262 return simulcast_offered && (!simulcast_answered || !rids_supported);
3263}
3264
Amit Hilbuch2297d332019-02-19 12:49:22 -08003265static RTCError DisableSimulcastInSender(
3266 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003267 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003268 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003269 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003270 return RTCError::OK();
3271 }
3272
Amit Hilbuch2297d332019-02-19 12:49:22 -08003273 std::vector<std::string> disabled_layers;
3274 std::transform(
3275 parameters.encodings.begin() + 1, parameters.encodings.end(),
3276 std::back_inserter(disabled_layers),
3277 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3278 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003279}
3280
Steve Antondcc3c022017-12-22 16:02:54 -08003281RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3282PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003283 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003284 size_t mline_index,
3285 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003286 const ContentInfo* old_local_content,
3287 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003288 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003289 // If this is an offer then the m= section might be recycled. If the m=
3290 // section is being recycled (defined as: rejected in the current local or
3291 // remote description and not rejected in new description), dissociate the
3292 // currently associated RtpTransceiver by setting its mid property to null,
3293 // and discard the mapping between the transceiver and its m= section index.
3294 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3295 old_remote_content)) {
3296 // We want to dissociate the transceiver that has the rejected mid.
3297 const std::string& old_mid =
3298 (old_local_content && old_local_content->rejected)
3299 ? old_local_content->name
3300 : old_remote_content->name;
3301 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003302 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003303 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3304 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003305 old_transceiver->internal()->set_mid(absl::nullopt);
3306 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003307 }
3308 }
3309 const MediaContentDescription* media_desc = content.media_description();
3310 auto transceiver = GetAssociatedTransceiver(content.name);
3311 if (source == cricket::CS_LOCAL) {
3312 // Find the RtpTransceiver that corresponds to this m= section, using the
3313 // mapping between transceivers and m= section indices established when
3314 // creating the offer.
3315 if (!transceiver) {
3316 transceiver = GetTransceiverByMLineIndex(mline_index);
3317 }
3318 if (!transceiver) {
3319 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3320 "Unknown transceiver");
3321 }
3322 } else {
3323 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3324 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3325 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003326 // When simulcast is requested, a transceiver cannot be associated because
3327 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003328 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003329 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3330 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003331 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3332 }
3333 // If no RtpTransceiver was found in the previous step, create one with a
3334 // recvonly direction.
3335 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003336 RTC_LOG(LS_INFO) << "Adding "
3337 << cricket::MediaTypeToString(media_desc->type())
3338 << " transceiver for MID=" << content.name
3339 << " at i=" << mline_index
3340 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003341 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003342 std::vector<RtpEncodingParameters> send_encodings =
3343 GetSendEncodingsFromRemoteDescription(*media_desc);
3344 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3345 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003346 std::string receiver_id;
3347 if (!media_desc->streams().empty()) {
3348 receiver_id = media_desc->streams()[0].id;
3349 } else {
3350 receiver_id = rtc::CreateRandomUuid();
3351 }
3352 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003353 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003354 transceiver->internal()->set_direction(
3355 RtpTransceiverDirection::kRecvOnly);
3356 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003357
3358 // Check if the offer indicated simulcast but the answer rejected it.
3359 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003360 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003361 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003362 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003363 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003364 if (!error.ok()) {
3365 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3366 return std::move(error);
3367 }
3368 }
Steve Antondcc3c022017-12-22 16:02:54 -08003369 }
3370 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003371 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003372 LOG_AND_RETURN_ERROR(
3373 RTCErrorType::INVALID_PARAMETER,
3374 "Transceiver type does not match media description type.");
3375 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003376 if (media_desc->HasSimulcast()) {
3377 std::vector<SimulcastLayer> layers =
3378 source == cricket::CS_LOCAL
3379 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3380 : media_desc->simulcast_description()
3381 .receive_layers()
3382 .GetAllLayers();
3383 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003384 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003385 if (!error.ok()) {
3386 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3387 return std::move(error);
3388 }
3389 }
Steve Antondcc3c022017-12-22 16:02:54 -08003390 // Associate the found or created RtpTransceiver with the m= section by
3391 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3392 // section, and establish a mapping between the transceiver and the index of
3393 // the m= section.
3394 transceiver->internal()->set_mid(content.name);
3395 transceiver->internal()->set_mline_index(mline_index);
3396 return std::move(transceiver);
3397}
3398
3399rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3400PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3401 RTC_DCHECK(IsUnifiedPlan());
3402 for (auto transceiver : transceivers_) {
3403 if (transceiver->mid() == mid) {
3404 return transceiver;
3405 }
3406 }
3407 return nullptr;
3408}
3409
3410rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3411PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3412 RTC_DCHECK(IsUnifiedPlan());
3413 for (auto transceiver : transceivers_) {
3414 if (transceiver->internal()->mline_index() == mline_index) {
3415 return transceiver;
3416 }
3417 }
3418 return nullptr;
3419}
3420
3421rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3422PeerConnection::FindAvailableTransceiverToReceive(
3423 cricket::MediaType media_type) const {
3424 RTC_DCHECK(IsUnifiedPlan());
3425 // From JSEP section 5.10 (Applying a Remote Description):
3426 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3427 // the same type that were added to the PeerConnection by addTrack and are not
3428 // associated with any m= section and are not stopped, find the first such
3429 // RtpTransceiver.
3430 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003431 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003432 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3433 !transceiver->stopped()) {
3434 return transceiver;
3435 }
3436 }
3437 return nullptr;
3438}
3439
Steve Antoned10bd92017-12-05 10:52:59 -08003440const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3441 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3442 transceiver,
3443 const SessionDescriptionInterface* sdesc) const {
3444 RTC_DCHECK(transceiver);
3445 RTC_DCHECK(sdesc);
3446 if (IsUnifiedPlan()) {
3447 if (!transceiver->internal()->mid()) {
3448 // This transceiver is not associated with a media section yet.
3449 return nullptr;
3450 }
3451 return sdesc->description()->GetContentByName(
3452 *transceiver->internal()->mid());
3453 } else {
3454 // Plan B only allows at most one audio and one video section, so use the
3455 // first media section of that type.
3456 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003457 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003458 }
3459}
3460
deadbeef46c73892016-11-16 19:42:04 -08003461PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003462 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003463 return configuration_;
3464}
3465
Niels Möller2579f0c2019-08-19 09:58:17 +02003466RTCError PeerConnection::SetConfiguration(
3467 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003468 RTC_DCHECK_RUN_ON(signaling_thread());
3469 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003470 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003471 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003472 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3473 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003474 }
3475
Qingsi Wanga2d60672018-04-11 16:57:45 -07003476 // According to JSEP, after setLocalDescription, changing the candidate pool
3477 // size is not allowed, and changing the set of ICE servers will not result
3478 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003479 if (local_description() && configuration.ice_candidate_pool_size !=
3480 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3482 "Can't change candidate pool size after calling "
3483 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003484 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003485
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003486 if (local_description() &&
3487 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003488 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3489 "Can't change media_transport after calling "
3490 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003491 }
3492
3493 if (remote_description() &&
3494 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003495 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3496 "Can't change media_transport after calling "
3497 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003498 }
3499
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003500 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003501 configuration.use_media_transport_for_data_channels !=
3502 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003503 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3504 "Can't change media_transport_for_data_channels "
3505 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003506 }
3507
3508 if (remote_description() &&
3509 configuration.use_media_transport_for_data_channels !=
3510 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003511 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3512 "Can't change media_transport_for_data_channels "
3513 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003514 }
3515
3516 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003517 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3519 "Can't change crypto_options after calling "
3520 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003521 }
3522
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003523 if (local_description() && configuration.use_datagram_transport !=
3524 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003525 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3526 "Can't change use_datagram_transport "
3527 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003528 }
3529
3530 if (remote_description() && configuration.use_datagram_transport !=
3531 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3533 "Can't change use_datagram_transport "
3534 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003535 }
3536
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003537 if (local_description() &&
3538 configuration.use_datagram_transport_for_data_channels !=
3539 configuration_.use_datagram_transport_for_data_channels) {
3540 LOG_AND_RETURN_ERROR(
3541 RTCErrorType::INVALID_MODIFICATION,
3542 "Can't change use_datagram_transport_for_data_channels "
3543 "after calling SetLocalDescription.");
3544 }
3545
3546 if (remote_description() &&
3547 configuration.use_datagram_transport_for_data_channels !=
3548 configuration_.use_datagram_transport_for_data_channels) {
3549 LOG_AND_RETURN_ERROR(
3550 RTCErrorType::INVALID_MODIFICATION,
3551 "Can't change use_datagram_transport_for_data_channels "
3552 "after calling SetRemoteDescription.");
3553 }
3554
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003555 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003556 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003557 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003558 *configuration.use_datagram_transport) ||
3559 (configuration.use_datagram_transport_for_data_channels &&
3560 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003561 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3562 << "Media transport requires MaxBundle policy.";
3563 }
3564
deadbeef293e9262017-01-11 12:28:30 -08003565 // The simplest (and most future-compatible) way to tell if the config was
3566 // modified in an invalid way is to copy each property we do support
3567 // modifying, then use operator==. There are far more properties we don't
3568 // support modifying than those we do, and more could be added.
3569 RTCConfiguration modified_config = configuration_;
3570 modified_config.servers = configuration.servers;
3571 modified_config.type = configuration.type;
3572 modified_config.ice_candidate_pool_size =
3573 configuration.ice_candidate_pool_size;
3574 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003575 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3576 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003577 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003578 modified_config.ice_check_interval_strong_connectivity =
3579 configuration.ice_check_interval_strong_connectivity;
3580 modified_config.ice_check_interval_weak_connectivity =
3581 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003582 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3583 modified_config.ice_unwritable_min_checks =
3584 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003585 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003586 modified_config.stun_candidate_keepalive_interval =
3587 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003588 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003589 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003590 modified_config.active_reset_srtp_params =
3591 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003592 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003593 modified_config.use_media_transport_for_data_channels =
3594 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003595 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003596 modified_config.use_datagram_transport_for_data_channels =
3597 configuration.use_datagram_transport_for_data_channels;
Jonas Oreland3c028422019-08-22 16:16:35 +02003598 modified_config.turn_logging_id = configuration.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -08003599 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003600 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3601 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003602 }
3603
Steve Anton038834f2017-07-14 15:59:59 -07003604 // Validate the modified configuration.
3605 RTCError validate_error = ValidateConfiguration(modified_config);
3606 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003607 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003608 }
3609
deadbeef293e9262017-01-11 12:28:30 -08003610 // Note that this isn't possible through chromium, since it's an unsigned
3611 // short in WebIDL.
3612 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003613 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003614 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003615 }
3616
3617 // Parse ICE servers before hopping to network thread.
3618 cricket::ServerAddresses stun_servers;
3619 std::vector<cricket::RelayServerConfig> turn_servers;
3620 RTCErrorType parse_error =
3621 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3622 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003623 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003624 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003625 // Add the turn logging id to all turn servers
3626 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3627 turn_server.turn_logging_id = configuration.turn_logging_id;
3628 }
3629
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003630 // Note if STUN or TURN servers were supplied.
3631 if (!stun_servers.empty()) {
3632 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3633 }
3634 if (!turn_servers.empty()) {
3635 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3636 }
deadbeef293e9262017-01-11 12:28:30 -08003637
3638 // In theory this shouldn't fail.
3639 if (!network_thread()->Invoke<bool>(
3640 RTC_FROM_HERE,
3641 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3642 stun_servers, turn_servers, modified_config.type,
3643 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003644 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003645 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003646 modified_config.stun_candidate_keepalive_interval,
3647 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003648 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3649 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003650 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003651
deadbeefd1a38b52016-12-10 13:15:33 -08003652 // As described in JSEP, calling setConfiguration with new ICE servers or
3653 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3654 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003655 if (modified_config.servers != configuration_.servers ||
3656 modified_config.type != configuration_.type ||
3657 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003658 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003659 }
skvladd1f5fda2017-02-03 16:54:05 -08003660
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003661 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003662
3663 use_datagram_transport_ = datagram_transport_config_.enabled &&
3664 modified_config.use_datagram_transport.value_or(
3665 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003666 use_datagram_transport_for_data_channels_ =
3667 datagram_transport_data_channel_config_.enabled &&
3668 modified_config.use_datagram_transport_for_data_channels.value_or(
3669 datagram_transport_data_channel_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003670 transport_controller_->SetMediaTransportSettings(
3671 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003672 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003673 use_datagram_transport_, use_datagram_transport_for_data_channels_);
skvladd1f5fda2017-02-03 16:54:05 -08003674
Zhi Huangb57e1692018-06-12 11:41:11 -07003675 if (configuration_.active_reset_srtp_params !=
3676 modified_config.active_reset_srtp_params) {
3677 transport_controller_->SetActiveResetSrtpParams(
3678 modified_config.active_reset_srtp_params);
3679 }
3680
deadbeef293e9262017-01-11 12:28:30 -08003681 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003682 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003683 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003684}
3685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003686bool PeerConnection::AddIceCandidate(
3687 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003688 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003689 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003690 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003691 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003692 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003693 return false;
3694 }
Steve Antond25da372017-11-06 14:50:29 -08003695
3696 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003697 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003698 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003699 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003700 return false;
3701 }
3702
3703 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003704 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003705 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003706 return false;
3707 }
3708
3709 bool valid = false;
3710 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3711 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003712 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003713 return false;
3714 }
3715
3716 // Add this candidate to the remote session description.
3717 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003718 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003719 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003720 return false;
3721 }
3722
3723 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003724 bool result = UseCandidate(ice_candidate);
3725 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003726 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003727 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3728 } else {
3729 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3730 }
3731 return result;
Steve Antond25da372017-11-06 14:50:29 -08003732 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003733 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003734 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003735 return true;
3736 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003737}
3738
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003739bool PeerConnection::RemoveIceCandidates(
3740 const std::vector<cricket::Candidate>& candidates) {
3741 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003742 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003743 if (IsClosed()) {
3744 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3745 return false;
3746 }
3747
Steve Antond25da372017-11-06 14:50:29 -08003748 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003749 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3750 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003751 return false;
3752 }
3753
3754 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003755 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003756 return false;
3757 }
3758
3759 size_t number_removed =
3760 mutable_remote_description()->RemoveCandidates(candidates);
3761 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003762 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003763 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003764 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003765 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003766 }
3767
3768 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003769 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3770 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003771 RTC_LOG(LS_ERROR)
3772 << "RemoveIceCandidates: Error when removing remote candidates: "
3773 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003774 }
3775 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003776}
3777
Niels Möller0c4f7be2018-05-07 14:01:37 +02003778RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003779 if (!worker_thread()->IsCurrent()) {
3780 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003781 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003782 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003783 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003784
Niels Möller0c4f7be2018-05-07 14:01:37 +02003785 const bool has_min = bitrate.min_bitrate_bps.has_value();
3786 const bool has_start = bitrate.start_bitrate_bps.has_value();
3787 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003788 if (has_min && *bitrate.min_bitrate_bps < 0) {
3789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3790 "min_bitrate_bps <= 0");
3791 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003792 if (has_start) {
3793 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003794 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003795 "start_bitrate_bps < min_bitrate_bps");
3796 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3798 "curent_bitrate_bps < 0");
3799 }
3800 }
3801 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003802 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003803 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003804 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003805 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3806 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3807 "max_bitrate_bps < min_bitrate_bps");
3808 } else if (*bitrate.max_bitrate_bps < 0) {
3809 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3810 "max_bitrate_bps < 0");
3811 }
3812 }
3813
zstein4b979802017-06-02 14:37:37 -07003814 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003815 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003816
3817 return RTCError::OK();
3818}
3819
henrika5f6bf242017-11-01 11:06:56 +01003820void PeerConnection::SetAudioPlayout(bool playout) {
3821 if (!worker_thread()->IsCurrent()) {
3822 worker_thread()->Invoke<void>(
3823 RTC_FROM_HERE,
3824 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3825 return;
3826 }
3827 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003828 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003829 audio_state->SetPlayout(playout);
3830}
3831
3832void PeerConnection::SetAudioRecording(bool recording) {
3833 if (!worker_thread()->IsCurrent()) {
3834 worker_thread()->Invoke<void>(
3835 RTC_FROM_HERE,
3836 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3837 return;
3838 }
3839 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003840 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003841 audio_state->SetRecording(recording);
3842}
3843
Steve Anton8c0f7a72017-10-03 10:03:10 -07003844std::unique_ptr<rtc::SSLCertificate>
3845PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003846 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3847 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003848 return nullptr;
3849 }
Steve Antonf25303e2018-10-16 15:23:31 -07003850 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003851}
3852
Zhi Huang70b820f2018-01-27 14:16:15 -08003853std::unique_ptr<rtc::SSLCertChain>
3854PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003855 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003856 auto audio_transceiver = GetFirstAudioTransceiver();
3857 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003858 return nullptr;
3859 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003860 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003861 audio_transceiver->internal()->channel()->transport_name());
3862}
3863
3864rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3865PeerConnection::GetFirstAudioTransceiver() const {
3866 for (auto transceiver : transceivers_) {
3867 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3868 return transceiver;
3869 }
3870 }
3871 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003872}
3873
Bjorn Tereliusde939432017-11-20 17:38:14 +01003874bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3875 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003876 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02003877 RTC_FROM_HERE,
3878 [this, output = std::move(output), output_period_ms]() mutable {
3879 return StartRtcEventLog_w(std::move(output), output_period_ms);
3880 });
ivoc14d5dbe2016-07-04 07:06:55 -07003881}
3882
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003883bool PeerConnection::StartRtcEventLog(
3884 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003885 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3886 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3887 output_period_ms = 5000;
3888 }
3889 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003890}
3891
ivoc14d5dbe2016-07-04 07:06:55 -07003892void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003893 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003894 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3895}
3896
Harald Alvestrandad88c882018-11-28 16:47:46 +01003897rtc::scoped_refptr<DtlsTransportInterface>
3898PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003899 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003900 return transport_controller_->LookupDtlsTransportByMid(mid);
3901}
3902
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003903rtc::scoped_refptr<DtlsTransport>
3904PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003905 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003906 return transport_controller_->LookupDtlsTransportByMid(mid);
3907}
3908
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003909rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3910 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003911 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07003912 if (!sctp_mid_) {
3913 return nullptr;
3914 }
3915 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003916}
3917
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003918const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003919 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003920 return pending_local_description_ ? pending_local_description_.get()
3921 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003922}
3923
3924const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003925 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003926 return pending_remote_description_ ? pending_remote_description_.get()
3927 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003928}
3929
deadbeeffe4a8a42016-12-20 17:56:17 -08003930const SessionDescriptionInterface* PeerConnection::current_local_description()
3931 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003932 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003933 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003934}
3935
3936const SessionDescriptionInterface* PeerConnection::current_remote_description()
3937 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003938 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003939 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003940}
3941
3942const SessionDescriptionInterface* PeerConnection::pending_local_description()
3943 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003944 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003945 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003946}
3947
3948const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3949 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003950 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003951 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003952}
3953
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003954void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003955 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003956 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003957 // Update stats here so that we have the most recent stats for tracks and
3958 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003959 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003960
Steve Anton75737c02017-11-06 10:37:17 -08003961 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003962 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003963
Mirko Bonadei739baf02019-01-27 17:29:42 +01003964 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003965 transceiver->Stop();
3966 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003967
3968 // Ensure that all asynchronous stats requests are completed before destroying
3969 // the transport controller below.
3970 if (stats_collector_) {
3971 stats_collector_->WaitForPendingRequest();
3972 }
3973
3974 // Don't destroy BaseChannels until after stats has been cleaned up so that
3975 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003976 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003977
Qingsi Wang93a84392018-01-30 17:13:09 -08003978 // The event log is used in the transport controller, which must be outlived
3979 // by the former. CreateOffer by the peer connection is implemented
3980 // asynchronously and if the peer connection is closed without resetting the
3981 // WebRTC session description factory, the session description factory would
3982 // call the transport controller.
3983 webrtc_session_desc_factory_.reset();
3984 transport_controller_.reset();
3985
deadbeef42a42632017-03-10 15:18:00 -08003986 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003987 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3988 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003989
Steve Anton978b8762017-09-29 12:15:02 -07003990 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003991 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003992 call_.reset();
3993 // The event log must outlive call (and any other object that uses it).
3994 event_log_.reset();
3995 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003996 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003997 // The .h file says that observer can be discarded after close() returns.
3998 // Make sure this is true.
3999 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004000}
4001
Steve Antonad182762018-09-05 20:22:40 +00004002void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004003 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004004 switch (msg->message_id) {
4005 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4006 SetSessionDescriptionMsg* param =
4007 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4008 param->observer->OnSuccess();
4009 delete param;
4010 break;
4011 }
4012 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4013 SetSessionDescriptionMsg* param =
4014 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4015 param->observer->OnFailure(std::move(param->error));
4016 delete param;
4017 break;
4018 }
4019 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4020 CreateSessionDescriptionMsg* param =
4021 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4022 param->observer->OnFailure(std::move(param->error));
4023 delete param;
4024 break;
4025 }
4026 case MSG_GETSTATS: {
4027 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4028 StatsReports reports;
4029 stats_->GetStats(param->track, &reports);
4030 param->observer->OnComplete(reports);
4031 delete param;
4032 break;
4033 }
4034 case MSG_FREE_DATACHANNELS: {
4035 sctp_data_channels_to_free_.clear();
4036 break;
4037 }
4038 case MSG_REPORT_USAGE_PATTERN: {
4039 ReportUsagePattern();
4040 break;
4041 }
4042 default:
4043 RTC_NOTREACHED() << "Not implemented";
4044 break;
4045 }
4046}
4047
Steve Antonafb0bb72018-02-20 11:35:37 -08004048cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4049 RTC_DCHECK(!IsUnifiedPlan());
4050 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4051 GetAudioTransceiver()->internal()->channel());
4052 if (voice_channel) {
4053 return voice_channel->media_channel();
4054 } else {
4055 return nullptr;
4056 }
4057}
4058
4059cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4060 RTC_DCHECK(!IsUnifiedPlan());
4061 auto* video_channel = static_cast<cricket::VideoChannel*>(
4062 GetVideoTransceiver()->internal()->channel());
4063 if (video_channel) {
4064 return video_channel->media_channel();
4065 } else {
4066 return nullptr;
4067 }
4068}
4069
Steve Anton4171afb2017-11-20 10:20:22 -08004070void PeerConnection::CreateAudioReceiver(
4071 MediaStreamInterface* stream,
4072 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004073 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4074 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004075 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4076 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004077 auto* audio_receiver = new AudioRtpReceiver(
4078 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004079 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004080 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4081 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4082 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004083 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004084 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004085 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004086}
4087
Steve Anton4171afb2017-11-20 10:20:22 -08004088void PeerConnection::CreateVideoReceiver(
4089 MediaStreamInterface* stream,
4090 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004091 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4092 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004093 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4094 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004095 auto* video_receiver = new VideoRtpReceiver(
4096 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004097 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004098 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4099 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4100 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004101 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004102 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004103 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004104}
4105
deadbeef70ab1a12015-09-28 16:53:55 -07004106// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4107// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004108rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004109 const RtpSenderInfo& remote_sender_info) {
4110 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4111 if (!receiver) {
4112 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4113 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004114 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004115 }
Steve Anton4171afb2017-11-20 10:20:22 -08004116 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4117 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4118 } else {
4119 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4120 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004121 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004122}
4123
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004124void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4125 MediaStreamInterface* stream) {
4126 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004127 RTC_DCHECK(track);
4128 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004129 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004130 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004131 // We already have a sender for this track, so just change the stream_id
4132 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004133 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004134 return;
4135 }
4136
4137 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004138 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004139 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004140 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004141 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004142 // If the sender has already been configured in SDP, we call SetSsrc,
4143 // which will connect the sender to the underlying transport. This can
4144 // occur if a local session description that contains the ID of the sender
4145 // is set before AddStream is called. It can also occur if the local
4146 // session description is not changed and RemoveStream is called, and
4147 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004148 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004149 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004150 if (sender_info) {
4151 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004152 }
4153}
4154
4155// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4156// indefinitely, when we have unified plan SDP.
4157void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4158 MediaStreamInterface* stream) {
4159 RTC_DCHECK(!IsClosed());
4160 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004161 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004162 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4163 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004164 return;
4165 }
Steve Anton4171afb2017-11-20 10:20:22 -08004166 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004167}
4168
4169void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4170 MediaStreamInterface* stream) {
4171 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004172 RTC_DCHECK(track);
4173 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004174 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004175 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004176 // We already have a sender for this track, so just change the stream_id
4177 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004178 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004179 return;
4180 }
4181
4182 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004183 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004184 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004185 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004186 GetVideoTransceiver()->internal()->AddSender(new_sender);
4187 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004188 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004189 if (sender_info) {
4190 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004191 }
4192}
4193
4194void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4195 MediaStreamInterface* stream) {
4196 RTC_DCHECK(!IsClosed());
4197 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004198 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004199 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4200 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004201 return;
4202 }
Steve Anton4171afb2017-11-20 10:20:22 -08004203 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004204}
4205
Steve Antonba818672017-11-06 10:21:57 -08004206void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004207 if (ice_connection_state_ == new_state) {
4208 return;
4209 }
4210
deadbeefcbecd352015-09-23 11:50:27 -07004211 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004212 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004213 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004214 return;
4215 }
Steve Antonba818672017-11-06 10:21:57 -08004216
Mirko Bonadei675513b2017-11-09 11:09:25 +01004217 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4218 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004219 RTC_DCHECK(ice_connection_state_ !=
4220 PeerConnectionInterface::kIceConnectionClosed);
4221
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004222 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004223 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004224}
4225
Alex Loiko9289eda2018-11-23 16:18:59 +00004226void PeerConnection::SetStandardizedIceConnectionState(
4227 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004228 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004229 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004230 }
4231
4232 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004233 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004234 }
4235
4236 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4237 << standardized_ice_connection_state_ << " => " << new_state;
4238
Alex Loiko9289eda2018-11-23 16:18:59 +00004239 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004240 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004241}
4242
Jonas Olsson635474e2018-10-18 15:58:17 +02004243void PeerConnection::SetConnectionState(
4244 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004245 if (connection_state_ == new_state)
4246 return;
4247 if (IsClosed())
4248 return;
4249 connection_state_ = new_state;
4250 Observer()->OnConnectionChange(new_state);
4251}
4252
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004253void PeerConnection::OnIceGatheringChange(
4254 PeerConnectionInterface::IceGatheringState new_state) {
4255 if (IsClosed()) {
4256 return;
4257 }
4258 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004259 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004260}
4261
jbauch81bf7b02017-03-25 08:31:12 -07004262void PeerConnection::OnIceCandidate(
4263 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004264 if (IsClosed()) {
4265 return;
4266 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004267 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004268 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004269}
4270
Eldar Relloda13ea22019-06-01 12:23:43 +03004271void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4272 const std::string& url,
4273 int error_code,
4274 const std::string& error_text) {
4275 if (IsClosed()) {
4276 return;
4277 }
4278 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4279}
4280
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004281void PeerConnection::OnIceCandidatesRemoved(
4282 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004283 if (IsClosed()) {
4284 return;
4285 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004286 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004287}
4288
Alex Drake00c7ecf2019-08-06 10:54:47 -07004289void PeerConnection::OnSelectedCandidatePairChanged(
4290 const cricket::CandidatePairChangeEvent& event) {
4291 if (IsClosed()) {
4292 return;
4293 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004294
Alex Drake00c7ecf2019-08-06 10:54:47 -07004295 Observer()->OnIceSelectedCandidatePairChanged(event);
4296}
4297
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004298void PeerConnection::ChangeSignalingState(
4299 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004300 if (signaling_state_ == signaling_state) {
4301 return;
4302 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004303 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4304 << GetSignalingStateString(signaling_state_)
4305 << " New state: "
4306 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004307 signaling_state_ = signaling_state;
4308 if (signaling_state == kClosed) {
4309 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004310 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004311 standardized_ice_connection_state_ =
4312 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004313 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4314 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004315 if (ice_gathering_state_ != kIceGatheringComplete) {
4316 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004317 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004318 }
4319 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004320 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004321}
4322
deadbeefeb459812015-12-15 19:24:43 -08004323void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4324 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004325 if (IsClosed()) {
4326 return;
4327 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004328 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004329 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004330}
4331
deadbeefeb459812015-12-15 19:24:43 -08004332void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4333 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004334 if (IsClosed()) {
4335 return;
4336 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004337 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004338 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004339}
4340
4341void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4342 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004343 if (IsClosed()) {
4344 return;
4345 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004346 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004347 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004348}
4349
4350void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4351 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004352 if (IsClosed()) {
4353 return;
4354 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004355 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004356 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004357}
4358
Henrik Boström31638672017-11-23 17:48:32 +01004359void PeerConnection::PostSetSessionDescriptionSuccess(
4360 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004361 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4362 signaling_thread()->Post(RTC_FROM_HERE, this,
4363 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004364}
4365
deadbeefab9b2d12015-10-14 11:33:11 -07004366void PeerConnection::PostSetSessionDescriptionFailure(
4367 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004368 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004369 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004370 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4371 msg->error = std::move(error);
4372 signaling_thread()->Post(RTC_FROM_HERE, this,
4373 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004374}
4375
4376void PeerConnection::PostCreateSessionDescriptionFailure(
4377 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004378 RTCError error) {
4379 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004380 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4381 msg->error = std::move(error);
4382 signaling_thread()->Post(RTC_FROM_HERE, this,
4383 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004384}
4385
zhihuang1c378ed2017-08-17 14:10:50 -07004386void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004387 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004388 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004389 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004390
Steve Antondcc3c022017-12-22 16:02:54 -08004391 if (IsUnifiedPlan()) {
4392 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4393 } else {
4394 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4395 }
4396
Steve Antonfa2260d2017-12-28 16:38:23 -08004397 // Intentionally unset the data channel type for RTP data channel with the
4398 // second condition. Otherwise the RTP data channels would be successfully
4399 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4400 // when building with chromium. We want to leave RTP data channels broken, so
4401 // people won't try to use them.
4402 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4403 session_options->data_channel_type = data_channel_type();
4404 }
4405
Steve Antondcc3c022017-12-22 16:02:54 -08004406 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004407 bool ice_restart = offer_answer_options.ice_restart ||
4408 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004409 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004410 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004411 options.transport_options.enable_ice_renomination =
4412 configuration_.enable_ice_renomination;
4413 }
4414
4415 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004416 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004417 session_options->pooled_ice_credentials =
4418 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4419 RTC_FROM_HERE,
4420 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4421 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004422 session_options->offer_extmap_allow_mixed =
4423 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004424
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004425 if (configuration_.use_media_transport ||
4426 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004427 session_options->media_transport_settings =
4428 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4429 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004430
4431 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004432 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004433 for (auto& options : session_options->media_description_options) {
4434 options.transport_options.opaque_parameters =
4435 transport_controller_->GetTransportParameters(options.mid);
4436 }
4437 }
4438
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004439 // Allow fallback for using obsolete SCTP syntax.
4440 // Note that the default in |session_options| is true, while
4441 // the default in |options| is false.
4442 session_options->use_obsolete_sctp_sdp =
4443 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004444}
4445
4446void PeerConnection::GetOptionsForPlanBOffer(
4447 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4448 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004449 // Figure out transceiver directional preferences.
4450 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4451 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4452
4453 // By default, generate sendrecv/recvonly m= sections.
4454 bool recv_audio = true;
4455 bool recv_video = true;
4456
4457 // By default, only offer a new m= section if we have media to send with it.
4458 bool offer_new_audio_description = send_audio;
4459 bool offer_new_video_description = send_video;
4460 bool offer_new_data_description = HasDataChannels();
4461
4462 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004463 if (offer_answer_options.offer_to_receive_audio !=
4464 RTCOfferAnswerOptions::kUndefined) {
4465 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004466 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004467 offer_new_audio_description ||
4468 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004469 }
Steve Antondcc3c022017-12-22 16:02:54 -08004470 if (offer_answer_options.offer_to_receive_video !=
4471 RTCOfferAnswerOptions::kUndefined) {
4472 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004473 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004474 offer_new_video_description ||
4475 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004476 }
4477
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004478 absl::optional<size_t> audio_index;
4479 absl::optional<size_t> video_index;
4480 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004481 // If a current description exists, generate m= sections in the same order,
4482 // using the first audio/video/data section that appears and rejecting
4483 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004484 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004485 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004486 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004487 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4488 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4489 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004490 }
4491
zhihuang1c378ed2017-08-17 14:10:50 -07004492 // Add audio/video/data m= sections to the end if needed.
4493 if (!audio_index && offer_new_audio_description) {
4494 session_options->media_description_options.push_back(
4495 cricket::MediaDescriptionOptions(
4496 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004497 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4498 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004499 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004500 }
zhihuang1c378ed2017-08-17 14:10:50 -07004501 if (!video_index && offer_new_video_description) {
4502 session_options->media_description_options.push_back(
4503 cricket::MediaDescriptionOptions(
4504 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004505 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4506 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004507 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004508 }
zhihuang1c378ed2017-08-17 14:10:50 -07004509 if (!data_index && offer_new_data_description) {
4510 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004511 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004512 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004513 }
4514
4515 cricket::MediaDescriptionOptions* audio_media_description_options =
4516 !audio_index ? nullptr
4517 : &session_options->media_description_options[*audio_index];
4518 cricket::MediaDescriptionOptions* video_media_description_options =
4519 !video_index ? nullptr
4520 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004521
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004522 AddPlanBRtpSenderOptions(GetSendersInternal(),
4523 audio_media_description_options,
4524 video_media_description_options,
4525 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004526}
4527
Steve Antondcc3c022017-12-22 16:02:54 -08004528static cricket::MediaDescriptionOptions
4529GetMediaDescriptionOptionsForTransceiver(
4530 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4531 transceiver,
4532 const std::string& mid) {
4533 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004534 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004535 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004536 media_description_options.codec_preferences =
4537 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004538 // This behavior is specified in JSEP. The gist is that:
4539 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4540 // sendrecv.
4541 // 2. If the MSID is included, then it must be included in any subsequent
4542 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004543 if (transceiver->stopped() ||
4544 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4545 !transceiver->internal()->has_ever_been_used_to_send())) {
4546 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004547 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004548
4549 cricket::SenderOptions sender_options;
4550 sender_options.track_id = transceiver->sender()->id();
4551 sender_options.stream_ids = transceiver->sender()->stream_ids();
4552
4553 // The following sets up RIDs and Simulcast.
4554 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004555 RtpParameters send_parameters =
4556 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004557 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4558 send_parameters.encodings.end(),
4559 [](const RtpEncodingParameters& encoding) {
4560 return !encoding.rid.empty();
4561 });
4562
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004563 std::vector<RidDescription> send_rids;
4564 SimulcastLayerList send_layers;
4565 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4566 if (encoding.rid.empty()) {
4567 continue;
4568 }
4569 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4570 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4571 }
4572
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004573 if (has_rids) {
4574 sender_options.rids = send_rids;
4575 }
4576
4577 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004578 // When RIDs are configured, we must set num_sim_layers to 0 to.
4579 // Otherwise, num_sim_layers must be 1 because either there is no
4580 // simulcast, or simulcast is acheived by munging the SDP.
4581 sender_options.num_sim_layers = has_rids ? 0 : 1;
4582 media_description_options.sender_options.push_back(sender_options);
4583
Steve Antondcc3c022017-12-22 16:02:54 -08004584 return media_description_options;
4585}
4586
Steve Anton5c72e712018-12-10 14:25:30 -08004587// Returns the ContentInfo at mline index |i|, or null if none exists.
4588static const ContentInfo* GetContentByIndex(
4589 const SessionDescriptionInterface* sdesc,
4590 size_t i) {
4591 if (!sdesc) {
4592 return nullptr;
4593 }
4594 const ContentInfos& contents = sdesc->description()->contents();
4595 return (i < contents.size() ? &contents[i] : nullptr);
4596}
4597
Steve Antondcc3c022017-12-22 16:02:54 -08004598void PeerConnection::GetOptionsForUnifiedPlanOffer(
4599 const RTCOfferAnswerOptions& offer_answer_options,
4600 cricket::MediaSessionOptions* session_options) {
4601 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4602 // Offers) and 5.2.2 (Subsequent Offers).
4603 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004604 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004605 const ContentInfos& local_contents =
4606 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004607 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004608 const ContentInfos& remote_contents =
4609 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004610 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004611 // The mline indices that can be recycled. New transceivers should reuse these
4612 // slots first.
4613 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004614 // First, go through each media section that exists in either the local or
4615 // remote description and generate a media section in this offer for the
4616 // associated transceiver. If a media section can be recycled, generate a
4617 // default, rejected media section here that can be later overwritten.
4618 for (size_t i = 0;
4619 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4620 // Either |local_content| or |remote_content| is non-null.
4621 const ContentInfo* local_content =
4622 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004623 const ContentInfo* current_local_content =
4624 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004625 const ContentInfo* remote_content =
4626 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004627 const ContentInfo* current_remote_content =
4628 GetContentByIndex(current_remote_description(), i);
4629 bool had_been_rejected =
4630 (current_local_content && current_local_content->rejected) ||
4631 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004632 const std::string& mid =
4633 (local_content ? local_content->name : remote_content->name);
4634 cricket::MediaType media_type =
4635 (local_content ? local_content->media_description()->type()
4636 : remote_content->media_description()->type());
4637 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4638 media_type == cricket::MEDIA_TYPE_VIDEO) {
4639 auto transceiver = GetAssociatedTransceiver(mid);
4640 RTC_CHECK(transceiver);
4641 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004642 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004643 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004644 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004645 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4646 RtpTransceiverDirection::kInactive,
4647 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004648 recycleable_mline_indices.push(i);
4649 } else {
4650 session_options->media_description_options.push_back(
4651 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4652 // CreateOffer shouldn't really cause any state changes in
4653 // PeerConnection, but we need a way to match new transceivers to new
4654 // media sections in SetLocalDescription and JSEP specifies this is done
4655 // by recording the index of the media section generated for the
4656 // transceiver in the offer.
4657 transceiver->internal()->set_mline_index(i);
4658 }
4659 } else {
4660 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004661 RTC_CHECK(GetDataMid());
4662 if (had_been_rejected || mid != *GetDataMid()) {
4663 session_options->media_description_options.push_back(
4664 GetMediaDescriptionOptionsForRejectedData(mid));
4665 } else {
4666 session_options->media_description_options.push_back(
4667 GetMediaDescriptionOptionsForActiveData(mid));
4668 }
Steve Antondcc3c022017-12-22 16:02:54 -08004669 }
4670 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004671
Steve Antondcc3c022017-12-22 16:02:54 -08004672 // Next, look for transceivers that are newly added (that is, are not stopped
4673 // and not associated). Reuse media sections marked as recyclable first,
4674 // otherwise append to the end of the offer. New media sections should be
4675 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004676 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004677 if (transceiver->mid() || transceiver->stopped()) {
4678 continue;
4679 }
4680 size_t mline_index;
4681 if (!recycleable_mline_indices.empty()) {
4682 mline_index = recycleable_mline_indices.front();
4683 recycleable_mline_indices.pop();
4684 session_options->media_description_options[mline_index] =
4685 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004686 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004687 } else {
4688 mline_index = session_options->media_description_options.size();
4689 session_options->media_description_options.push_back(
4690 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004691 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004692 }
4693 // See comment above for why CreateOffer changes the transceiver's state.
4694 transceiver->internal()->set_mline_index(mline_index);
4695 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004696 // Lastly, add a m-section if we have local data channels and an m section
4697 // does not already exist.
4698 if (!GetDataMid() && HasDataChannels()) {
4699 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004700 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004701 }
Steve Antondcc3c022017-12-22 16:02:54 -08004702}
4703
4704void PeerConnection::GetOptionsForAnswer(
4705 const RTCOfferAnswerOptions& offer_answer_options,
4706 cricket::MediaSessionOptions* session_options) {
4707 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4708
4709 if (IsUnifiedPlan()) {
4710 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4711 } else {
4712 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4713 }
4714
Steve Antonfa2260d2017-12-28 16:38:23 -08004715 // Intentionally unset the data channel type for RTP data channel. Otherwise
4716 // the RTP data channels would be successfully negotiated by default and the
4717 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4718 // We want to leave RTP data channels broken, so people won't try to use them.
4719 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4720 session_options->data_channel_type = data_channel_type();
4721 }
4722
Steve Antondcc3c022017-12-22 16:02:54 -08004723 // Apply ICE renomination flag.
4724 for (auto& options : session_options->media_description_options) {
4725 options.transport_options.enable_ice_renomination =
4726 configuration_.enable_ice_renomination;
4727 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004728
4729 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004730 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004731 session_options->pooled_ice_credentials =
4732 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4733 RTC_FROM_HERE,
4734 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4735 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004736
4737 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004738 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004739 for (auto& options : session_options->media_description_options) {
4740 options.transport_options.opaque_parameters =
4741 transport_controller_->GetTransportParameters(options.mid);
4742 }
4743 }
deadbeefab9b2d12015-10-14 11:33:11 -07004744}
4745
Steve Antondcc3c022017-12-22 16:02:54 -08004746void PeerConnection::GetOptionsForPlanBAnswer(
4747 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004748 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004749 // Figure out transceiver directional preferences.
4750 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4751 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4752
4753 // By default, generate sendrecv/recvonly m= sections. The direction is also
4754 // restricted by the direction in the offer.
4755 bool recv_audio = true;
4756 bool recv_video = true;
4757
4758 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004759 if (offer_answer_options.offer_to_receive_audio !=
4760 RTCOfferAnswerOptions::kUndefined) {
4761 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004762 }
Steve Antondcc3c022017-12-22 16:02:54 -08004763 if (offer_answer_options.offer_to_receive_video !=
4764 RTCOfferAnswerOptions::kUndefined) {
4765 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004766 }
4767
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004768 absl::optional<size_t> audio_index;
4769 absl::optional<size_t> video_index;
4770 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004771
4772 // Generate m= sections that match those in the offer.
4773 // Note that mediasession.cc will handle intersection our preferred
4774 // direction with the offered direction.
4775 GenerateMediaDescriptionOptions(
4776 remote_description(),
4777 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4778 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4779 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004780
4781 cricket::MediaDescriptionOptions* audio_media_description_options =
4782 !audio_index ? nullptr
4783 : &session_options->media_description_options[*audio_index];
4784 cricket::MediaDescriptionOptions* video_media_description_options =
4785 !video_index ? nullptr
4786 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004787
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004788 AddPlanBRtpSenderOptions(GetSendersInternal(),
4789 audio_media_description_options,
4790 video_media_description_options,
4791 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004792}
zhihuangaf388472016-11-02 16:49:48 -07004793
Steve Antondcc3c022017-12-22 16:02:54 -08004794void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4795 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4796 cricket::MediaSessionOptions* session_options) {
4797 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4798 // Answers) and 5.3.2 (Subsequent Answers).
4799 RTC_DCHECK(remote_description());
4800 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4801 for (const ContentInfo& content :
4802 remote_description()->description()->contents()) {
4803 cricket::MediaType media_type = content.media_description()->type();
4804 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4805 media_type == cricket::MEDIA_TYPE_VIDEO) {
4806 auto transceiver = GetAssociatedTransceiver(content.name);
4807 RTC_CHECK(transceiver);
4808 session_options->media_description_options.push_back(
4809 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4810 } else {
4811 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004812 // Reject all data sections if data channels are disabled.
4813 // Reject a data section if it has already been rejected.
4814 // Reject all data sections except for the first one.
4815 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4816 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004817 session_options->media_description_options.push_back(
4818 GetMediaDescriptionOptionsForRejectedData(content.name));
4819 } else {
4820 session_options->media_description_options.push_back(
4821 GetMediaDescriptionOptionsForActiveData(content.name));
4822 }
Steve Antondcc3c022017-12-22 16:02:54 -08004823 }
4824 }
htaa2a49d92016-03-04 02:51:39 -08004825}
4826
zhihuang1c378ed2017-08-17 14:10:50 -07004827void PeerConnection::GenerateMediaDescriptionOptions(
4828 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004829 RtpTransceiverDirection audio_direction,
4830 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004831 absl::optional<size_t>* audio_index,
4832 absl::optional<size_t>* video_index,
4833 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004834 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004835 for (const cricket::ContentInfo& content :
4836 session_desc->description()->contents()) {
4837 if (IsAudioContent(&content)) {
4838 // If we already have an audio m= section, reject this extra one.
4839 if (*audio_index) {
4840 session_options->media_description_options.push_back(
4841 cricket::MediaDescriptionOptions(
4842 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004843 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004844 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004845 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004846 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004847 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4848 content.name, audio_direction,
4849 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004850 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004851 }
4852 } else if (IsVideoContent(&content)) {
4853 // If we already have an video m= section, reject this extra one.
4854 if (*video_index) {
4855 session_options->media_description_options.push_back(
4856 cricket::MediaDescriptionOptions(
4857 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004858 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004859 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004860 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004861 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004862 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4863 content.name, video_direction,
4864 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004865 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004866 }
4867 } else {
4868 RTC_DCHECK(IsDataContent(&content));
4869 // If we already have an data m= section, reject this extra one.
4870 if (*data_index) {
4871 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004872 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004873 } else {
4874 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004875 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004876 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004877 }
4878 }
htaa2a49d92016-03-04 02:51:39 -08004879 }
deadbeefab9b2d12015-10-14 11:33:11 -07004880}
4881
Steve Antonfa2260d2017-12-28 16:38:23 -08004882cricket::MediaDescriptionOptions
4883PeerConnection::GetMediaDescriptionOptionsForActiveData(
4884 const std::string& mid) const {
4885 // Direction for data sections is meaningless, but legacy endpoints might
4886 // expect sendrecv.
4887 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4888 RtpTransceiverDirection::kSendRecv,
4889 /*stopped=*/false);
4890 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4891 return options;
4892}
4893
4894cricket::MediaDescriptionOptions
4895PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4896 const std::string& mid) const {
4897 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4898 RtpTransceiverDirection::kInactive,
4899 /*stopped=*/true);
4900 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4901 return options;
4902}
4903
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004904absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004905 switch (data_channel_type_) {
4906 case cricket::DCT_RTP:
4907 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004908 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004909 }
4910 return rtp_data_channel_->content_name();
4911 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004912 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004913 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
4914 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
4915 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004916 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004917 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004918 }
4919}
4920
Steve Anton4171afb2017-11-20 10:20:22 -08004921void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4922 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4923 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004924 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004925}
4926
Steve Anton4171afb2017-11-20 10:20:22 -08004927void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004928 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004929 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004930 cricket::MediaType media_type,
4931 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004932 RTC_DCHECK(!IsUnifiedPlan());
4933
Steve Anton4171afb2017-11-20 10:20:22 -08004934 std::vector<RtpSenderInfo>* current_senders =
4935 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004936
Steve Anton4171afb2017-11-20 10:20:22 -08004937 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004938 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004939 for (auto sender_it = current_senders->begin();
4940 sender_it != current_senders->end();
4941 /* incremented manually */) {
4942 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004943 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004944 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004945 std::string params_stream_id;
4946 if (params) {
4947 params_stream_id =
4948 (!params->first_stream_id().empty() ? params->first_stream_id()
4949 : kDefaultStreamId);
4950 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004951 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004952 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004953 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004954 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004955 sender_exists) {
4956 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004957 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004958 OnRemoteSenderRemoved(info, media_type);
4959 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004960 }
4961 }
4962
Steve Anton4171afb2017-11-20 10:20:22 -08004963 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004964 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004965 if (!params.has_ssrcs()) {
4966 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4967 // sender, this means it is coming from a Unified Plan endpoint,so we just
4968 // create a default.
4969 default_sender_needed = true;
4970 break;
4971 }
4972
Seth Hampson845e8782018-03-02 11:34:10 -08004973 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004974 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004975 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4976 // not supported in Plan B, we just take the first here and create the
4977 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004978 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004979 (!params.first_stream_id().empty() ? params.first_stream_id()
4980 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004981 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004982 uint32_t ssrc = params.first_ssrc();
4983
4984 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004985 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004986 if (!stream) {
4987 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004988 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004989 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004990 remote_streams_->AddStream(stream);
4991 new_streams->AddStream(stream);
4992 }
4993
Steve Anton4171afb2017-11-20 10:20:22 -08004994 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004995 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004996 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004997 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004998 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004999 }
5000 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005001
Steve Anton4171afb2017-11-20 10:20:22 -08005002 // Add default sender if necessary.
5003 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005004 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005005 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005006 if (!default_stream) {
5007 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005008 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005009 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005010 remote_streams_->AddStream(default_stream);
5011 new_streams->AddStream(default_stream);
5012 }
Steve Anton4171afb2017-11-20 10:20:22 -08005013 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5014 ? kDefaultAudioSenderId
5015 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005016 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005017 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005018 if (!default_sender_info) {
5019 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005020 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005021 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005022 }
5023 }
deadbeefab9b2d12015-10-14 11:33:11 -07005024}
5025
Steve Anton4171afb2017-11-20 10:20:22 -08005026void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5027 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005028 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5029 << " receiver for track_id=" << sender_info.sender_id
5030 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005031
Steve Anton3d954a62018-04-02 11:27:23 -07005032 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005033 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005034 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005035 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005036 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005037 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005038 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005039 }
5040}
5041
Steve Anton4171afb2017-11-20 10:20:22 -08005042void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5043 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005044 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5045 << " receiver for track_id=" << sender_info.sender_id
5046 << " and stream_id=" << sender_info.stream_id;
5047
Seth Hampson845e8782018-03-02 11:34:10 -08005048 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005049
Henrik Boström933d8b02017-10-10 10:05:16 -07005050 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005051 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005052 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5053 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005054 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005055 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005056 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005057 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005058 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005059 }
5060 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005061 // Stopping or destroying a VideoRtpReceiver will end the
5062 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005063 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005064 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005065 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005066 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005067 // There's no guarantee the track is still available, e.g. the track may
5068 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005069 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005070 }
5071 } else {
nisseede5da42017-01-12 05:15:36 -08005072 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005073 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005074 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005075 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005076 }
deadbeefab9b2d12015-10-14 11:33:11 -07005077}
5078
5079void PeerConnection::UpdateEndedRemoteMediaStreams() {
5080 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5081 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5082 MediaStreamInterface* stream = remote_streams_->at(i);
5083 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5084 streams_to_remove.push_back(stream);
5085 }
5086 }
5087
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005088 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005089 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005090 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005091 }
5092}
5093
Steve Anton4171afb2017-11-20 10:20:22 -08005094void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005095 const std::vector<cricket::StreamParams>& streams,
5096 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005097 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005098
Seth Hampson845e8782018-03-02 11:34:10 -08005099 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005100 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005101 for (auto sender_it = current_senders->begin();
5102 sender_it != current_senders->end();
5103 /* incremented manually */) {
5104 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005105 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005106 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5107 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005108 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005109 OnLocalSenderRemoved(info, media_type);
5110 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005111 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005112 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005113 }
5114 }
5115
Steve Anton4171afb2017-11-20 10:20:22 -08005116 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005117 for (const cricket::StreamParams& params : streams) {
5118 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005119 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005120 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005121 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005122 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005123 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005124 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005125 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005126 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005127 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005128 }
5129 }
5130}
5131
Steve Anton4171afb2017-11-20 10:20:22 -08005132void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5133 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005134 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005135 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005136 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005137 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5138 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005139 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005140 return;
5141 }
5142
deadbeeffac06552015-11-25 11:26:01 -08005143 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005144 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005145 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005146 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005147 }
deadbeeffac06552015-11-25 11:26:01 -08005148
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005149 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005150 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005151}
5152
Steve Anton4171afb2017-11-20 10:20:22 -08005153void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5154 cricket::MediaType media_type) {
5155 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005156 if (!sender) {
5157 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005158 // SessionDescriptions has been renegotiated.
5159 return;
5160 }
deadbeeffac06552015-11-25 11:26:01 -08005161
5162 // A sender has been removed from the SessionDescription but it's still
5163 // associated with the PeerConnection. This only occurs if the SDP doesn't
5164 // match with the calls to CreateSender, AddStream and RemoveStream.
5165 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005166 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005167 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005168 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005169 }
deadbeeffac06552015-11-25 11:26:01 -08005170
Steve Anton4171afb2017-11-20 10:20:22 -08005171 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005172}
5173
5174void PeerConnection::UpdateLocalRtpDataChannels(
5175 const cricket::StreamParamsVec& streams) {
5176 std::vector<std::string> existing_channels;
5177
5178 // Find new and active data channels.
5179 for (const cricket::StreamParams& params : streams) {
5180 // |it->sync_label| is actually the data channel label. The reason is that
5181 // we use the same naming of data channels as we do for
5182 // MediaStreams and Tracks.
5183 // For MediaStreams, the sync_label is the MediaStream label and the
5184 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005185 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005186 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005187 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005188 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005189 continue;
5190 }
5191 // Set the SSRC the data channel should use for sending.
5192 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5193 existing_channels.push_back(data_channel_it->first);
5194 }
5195
5196 UpdateClosingRtpDataChannels(existing_channels, true);
5197}
5198
5199void PeerConnection::UpdateRemoteRtpDataChannels(
5200 const cricket::StreamParamsVec& streams) {
5201 std::vector<std::string> existing_channels;
5202
5203 // Find new and active data channels.
5204 for (const cricket::StreamParams& params : streams) {
5205 // The data channel label is either the mslabel or the SSRC if the mslabel
5206 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005207 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005208 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005209 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005210 auto data_channel_it = rtp_data_channels_.find(label);
5211 if (data_channel_it == rtp_data_channels_.end()) {
5212 // This is a new data channel.
5213 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5214 } else {
5215 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5216 }
5217 existing_channels.push_back(label);
5218 }
5219
5220 UpdateClosingRtpDataChannels(existing_channels, false);
5221}
5222
5223void PeerConnection::UpdateClosingRtpDataChannels(
5224 const std::vector<std::string>& active_channels,
5225 bool is_local_update) {
5226 auto it = rtp_data_channels_.begin();
5227 while (it != rtp_data_channels_.end()) {
5228 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005229 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005230 ++it;
5231 continue;
5232 }
5233
5234 if (is_local_update) {
5235 data_channel->SetSendSsrc(0);
5236 } else {
5237 data_channel->RemotePeerRequestClose();
5238 }
5239
5240 if (data_channel->state() == DataChannel::kClosed) {
5241 rtp_data_channels_.erase(it);
5242 it = rtp_data_channels_.begin();
5243 } else {
5244 ++it;
5245 }
5246 }
5247}
5248
5249void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5250 uint32_t remote_ssrc) {
5251 rtc::scoped_refptr<DataChannel> channel(
5252 InternalCreateDataChannel(label, nullptr));
5253 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005254 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005255 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005256 return;
5257 }
5258 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005259 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5260 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005261 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005262}
5263
5264rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5265 const std::string& label,
5266 const InternalDataChannelInit* config) {
5267 if (IsClosed()) {
5268 return nullptr;
5269 }
Steve Anton75737c02017-11-06 10:37:17 -08005270 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005271 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005272 << "InternalCreateDataChannel: Data is not supported in this call.";
5273 return nullptr;
5274 }
5275 InternalDataChannelInit new_config =
5276 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005277 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005278 if (new_config.id < 0) {
5279 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005280 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005281 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005282 RTC_LOG(LS_ERROR)
5283 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005284 return nullptr;
5285 }
5286 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005287 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005288 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005289 return nullptr;
5290 }
5291 }
5292
Steve Anton75737c02017-11-06 10:37:17 -08005293 rtc::scoped_refptr<DataChannel> channel(
5294 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005295 if (!channel) {
5296 sid_allocator_.ReleaseSid(new_config.id);
5297 return nullptr;
5298 }
5299
5300 if (channel->data_channel_type() == cricket::DCT_RTP) {
5301 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005302 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5303 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005304 return nullptr;
5305 }
5306 rtp_data_channels_[channel->label()] = channel;
5307 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005308 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005309 sctp_data_channels_.push_back(channel);
5310 channel->SignalClosed.connect(this,
5311 &PeerConnection::OnSctpDataChannelClosed);
5312 }
5313
Steve Anton2d8609c2018-01-23 16:38:46 -08005314 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005315 return channel;
5316}
5317
5318bool PeerConnection::HasDataChannels() const {
5319 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5320}
5321
5322void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005323 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005324 for (const auto& channel : sctp_data_channels_) {
5325 if (channel->id() < 0) {
5326 int sid;
5327 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005328 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5329 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005330 continue;
5331 }
5332 channel->SetSctpSid(sid);
5333 }
5334 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005335 // Since closing modifies the list of channels, we have to do the actual
5336 // closing outside the loop.
5337 for (const auto& channel : channels_to_close) {
5338 channel->CloseAbruptly();
5339 }
deadbeefab9b2d12015-10-14 11:33:11 -07005340}
5341
5342void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005343 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005344 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5345 ++it) {
5346 if (it->get() == channel) {
5347 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005348 // After the closing procedure is done, it's safe to use this ID for
5349 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005350 sid_allocator_.ReleaseSid(channel->id());
5351 }
deadbeefbd292462015-12-14 18:15:29 -08005352 // Since this method is triggered by a signal from the DataChannel,
5353 // we can't free it directly here; we need to free it asynchronously.
5354 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005355 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005356 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5357 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005358 return;
5359 }
5360 }
5361}
5362
deadbeefab9b2d12015-10-14 11:33:11 -07005363void PeerConnection::OnDataChannelDestroyed() {
5364 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5365 // DataChannel may callback to us and try to modify the list.
5366 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5367 temp_rtp_dcs.swap(rtp_data_channels_);
5368 for (const auto& kv : temp_rtp_dcs) {
5369 kv.second->OnTransportChannelDestroyed();
5370 }
5371
5372 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5373 temp_sctp_dcs.swap(sctp_data_channels_);
5374 for (const auto& channel : temp_sctp_dcs) {
5375 channel->OnTransportChannelDestroyed();
5376 }
5377}
5378
5379void PeerConnection::OnDataChannelOpenMessage(
5380 const std::string& label,
5381 const InternalDataChannelInit& config) {
5382 rtc::scoped_refptr<DataChannel> channel(
5383 InternalCreateDataChannel(label, &config));
5384 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005385 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005386 return;
5387 }
5388
deadbeefa601f5c2016-06-06 14:27:39 -07005389 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5390 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005391 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005392 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005393}
5394
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005395bool PeerConnection::HandleOpenMessage_s(
5396 const cricket::ReceiveDataParams& params,
5397 const rtc::CopyOnWriteBuffer& buffer) {
5398 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5399 // Received OPEN message; parse and signal that a new data channel should
5400 // be created.
5401 std::string label;
5402 InternalDataChannelInit config;
5403 config.id = params.ssrc;
5404 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5405 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5406 << params.ssrc;
5407 return true;
5408 }
5409 config.open_handshake_role = InternalDataChannelInit::kAcker;
5410 OnDataChannelOpenMessage(label, config);
5411 return true;
5412 }
5413 return false;
5414}
5415
Steve Anton4171afb2017-11-20 10:20:22 -08005416rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5417PeerConnection::GetAudioTransceiver() const {
5418 // This method only works with Plan B SDP, where there is a single
5419 // audio/video transceiver.
5420 RTC_DCHECK(!IsUnifiedPlan());
5421 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005422 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005423 return transceiver;
5424 }
5425 }
5426 RTC_NOTREACHED();
5427 return nullptr;
5428}
5429
5430rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5431PeerConnection::GetVideoTransceiver() const {
5432 // This method only works with Plan B SDP, where there is a single
5433 // audio/video transceiver.
5434 RTC_DCHECK(!IsUnifiedPlan());
5435 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005436 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005437 return transceiver;
5438 }
5439 }
5440 RTC_NOTREACHED();
5441 return nullptr;
5442}
5443
5444// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5445// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005446bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005447 switch (type) {
5448 case cricket::MEDIA_TYPE_AUDIO:
5449 return !GetAudioTransceiver()->internal()->senders().empty();
5450 case cricket::MEDIA_TYPE_VIDEO:
5451 return !GetVideoTransceiver()->internal()->senders().empty();
5452 case cricket::MEDIA_TYPE_DATA:
5453 return false;
5454 }
5455 RTC_NOTREACHED();
5456 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005457}
5458
Steve Anton4171afb2017-11-20 10:20:22 -08005459rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5460PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005461 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005462 for (auto sender : transceiver->internal()->senders()) {
5463 if (sender->track() == track) {
5464 return sender;
5465 }
5466 }
5467 }
5468 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005469}
5470
Steve Anton4171afb2017-11-20 10:20:22 -08005471rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5472PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005473 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005474 for (auto sender : transceiver->internal()->senders()) {
5475 if (sender->id() == sender_id) {
5476 return sender;
5477 }
5478 }
5479 }
5480 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005481}
5482
Steve Anton4171afb2017-11-20 10:20:22 -08005483rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5484PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005485 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005486 for (auto receiver : transceiver->internal()->receivers()) {
5487 if (receiver->id() == receiver_id) {
5488 return receiver;
5489 }
5490 }
5491 }
5492 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005493}
5494
Steve Anton4171afb2017-11-20 10:20:22 -08005495std::vector<PeerConnection::RtpSenderInfo>*
5496PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5497 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5498 media_type == cricket::MEDIA_TYPE_VIDEO);
5499 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5500 ? &remote_audio_sender_infos_
5501 : &remote_video_sender_infos_;
5502}
5503
5504std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005505 cricket::MediaType media_type) {
5506 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5507 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005508 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5509 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005510}
5511
Steve Anton4171afb2017-11-20 10:20:22 -08005512const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5513 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005514 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005515 const std::string sender_id) const {
5516 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005517 if (sender_info.stream_id == stream_id &&
5518 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005519 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005520 }
5521 }
5522 return nullptr;
5523}
5524
5525DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5526 for (const auto& channel : sctp_data_channels_) {
5527 if (channel->id() == sid) {
5528 return channel;
5529 }
5530 }
5531 return nullptr;
5532}
5533
Karl Wibergfb3be392019-03-22 14:13:22 +01005534PeerConnection::InitializePortAllocatorResult
5535PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005536 const cricket::ServerAddresses& stun_servers,
5537 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005538 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005539 RTC_DCHECK_RUN_ON(network_thread());
5540
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005541 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005542 // To handle both internal and externally created port allocator, we will
5543 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005544 int port_allocator_flags = port_allocator_->flags();
5545 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5546 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5547 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005548 // If the disable-IPv6 flag was specified, we'll not override it
5549 // by experiment.
5550 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005551 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005552 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5553 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005554 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005555 }
5556
zhihuangb09b3f92017-03-07 14:40:51 -08005557 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005558 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005559 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005560 }
5561
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005562 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005563 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005564 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005565 }
5566
honghaiz60347052016-05-31 18:29:12 -07005567 if (configuration.candidate_network_policy ==
5568 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005569 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005570 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005571 }
5572
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005573 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005574 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005575 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5576 }
5577
Karl Wibergfb3be392019-03-22 14:13:22 +01005578 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005579 // No step delay is used while allocating ports.
5580 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005581 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005582 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005583 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005584
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005585 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005586 for (auto& turn_server : turn_servers_copy) {
5587 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005588 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005589 // Call this last since it may create pooled allocator sessions using the
5590 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005591 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005592 stun_servers, std::move(turn_servers_copy),
5593 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5594 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005595 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005596
5597 InitializePortAllocatorResult res;
5598 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5599 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005600}
5601
deadbeef91dd5672016-05-18 16:55:30 -07005602bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005603 const cricket::ServerAddresses& stun_servers,
5604 const std::vector<cricket::RelayServerConfig>& turn_servers,
5605 IceTransportsType type,
5606 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005607 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005608 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005609 absl::optional<int> stun_candidate_keepalive_interval,
5610 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005611 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005612 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005613 // According to JSEP, after setLocalDescription, changing the candidate pool
5614 // size is not allowed, and changing the set of ICE servers will not result
5615 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005616 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005617 port_allocator_->FreezeCandidatePool();
5618 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005619 // Add the custom tls turn servers if they exist.
5620 auto turn_servers_copy = turn_servers;
5621 for (auto& turn_server : turn_servers_copy) {
5622 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5623 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005624 // Call this last since it may create pooled allocator sessions using the
5625 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005626 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005627 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5628 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005629}
5630
Steve Antonba818672017-11-06 10:21:57 -08005631cricket::ChannelManager* PeerConnection::channel_manager() const {
5632 return factory_->channel_manager();
5633}
5634
Elad Alon99c3fe52017-10-13 16:29:40 +02005635bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005636 std::unique_ptr<RtcEventLogOutput> output,
5637 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005638 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005639 if (!event_log_) {
5640 return false;
5641 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005642 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005643}
5644
5645void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005646 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005647 if (event_log_) {
5648 event_log_->StopLogging();
5649 }
ivoc14d5dbe2016-07-04 07:06:55 -07005650}
nisseeaabdf62017-05-05 02:23:02 -07005651
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005652cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005653 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005654 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005655 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005656 if (channel && channel->content_name() == content_name) {
5657 return channel;
5658 }
Steve Anton75737c02017-11-06 10:37:17 -08005659 }
5660 if (rtp_data_channel() &&
5661 rtp_data_channel()->content_name() == content_name) {
5662 return rtp_data_channel();
5663 }
5664 return nullptr;
5665}
5666
5667bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005668 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005669 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005670 RTC_LOG(LS_INFO)
5671 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005672 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005673 return false;
5674 }
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005675 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005676 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005677 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005678 return false;
5679 }
5680
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005681 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005682 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005683 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005684 if (!dtls_role && is_caller_.has_value()) {
5685 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5686 }
Zhi Huange830e682018-03-30 10:48:35 -07005687 *role = *dtls_role;
5688 return true;
5689 }
5690 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005691}
5692
5693bool PeerConnection::GetSslRole(const std::string& content_name,
5694 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005695 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005696 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005697 RTC_LOG(LS_INFO)
5698 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005699 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005700 return false;
5701 }
5702
Zhi Huange830e682018-03-30 10:48:35 -07005703 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5704 if (dtls_role) {
5705 *role = *dtls_role;
5706 return true;
5707 }
5708 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005709}
5710
Steve Antonf8470812017-12-04 10:46:21 -08005711void PeerConnection::SetSessionError(SessionError error,
5712 const std::string& error_desc) {
5713 RTC_DCHECK_RUN_ON(signaling_thread());
5714 if (error != session_error_) {
5715 session_error_ = error;
5716 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005717 }
5718}
5719
Zhi Huange830e682018-03-30 10:48:35 -07005720RTCError PeerConnection::UpdateSessionState(
5721 SdpType type,
5722 cricket::ContentSource source,
5723 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005724 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005725
5726 // If there's already a pending error then no state transition should happen.
5727 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005728 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005729
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005730 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005731 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005732 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005733 }
5734
5735 // Update the signaling state according to the specified state machine (see
5736 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005737 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005738 ChangeSignalingState(source == cricket::CS_LOCAL
5739 ? PeerConnectionInterface::kHaveLocalOffer
5740 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005741 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005742 ChangeSignalingState(source == cricket::CS_LOCAL
5743 ? PeerConnectionInterface::kHaveLocalPrAnswer
5744 : PeerConnectionInterface::kHaveRemotePrAnswer);
5745 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005746 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005747 ChangeSignalingState(PeerConnectionInterface::kStable);
5748 }
5749
5750 // Update internal objects according to the session description's media
5751 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005752 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005753 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005754 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005755 }
5756
Steve Anton8a006912017-12-04 15:25:56 -08005757 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005758}
5759
Steve Anton8a006912017-12-04 15:25:56 -08005760RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005761 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005762 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005763 const SessionDescriptionInterface* sdesc =
5764 (source == cricket::CS_LOCAL ? local_description()
5765 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005766 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005767
5768 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005769 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005770 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005771 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005772 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005773 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005774 continue;
5775 }
5776 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005777 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005778 if (!content_desc) {
5779 continue;
5780 }
5781 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005782 bool success = (source == cricket::CS_LOCAL)
5783 ? channel->SetLocalContent(content_desc, type, &error)
5784 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005785 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005786 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005787 }
5788 }
5789
5790 // If using the RtpDataChannel, push down the new SDP section for it too.
5791 if (rtp_data_channel_) {
5792 const ContentInfo* data_content =
5793 cricket::GetFirstDataContent(sdesc->description());
5794 if (data_content && !data_content->rejected) {
5795 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005796 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005797 if (data_desc) {
5798 std::string error;
5799 bool success =
5800 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005801 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005802 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005803 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005804 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005805 }
Steve Anton75737c02017-11-06 10:37:17 -08005806 }
5807 }
5808 }
Steve Antoned10bd92017-12-05 10:52:59 -08005809
Steve Anton75737c02017-11-06 10:37:17 -08005810 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5811 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005812 if (sctp_mid_ && local_description() && remote_description()) {
5813 rtc::scoped_refptr<SctpTransport> sctp_transport =
5814 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005815 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5816 local_description()->description());
5817 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5818 remote_description()->description());
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005819 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005820 int max_message_size;
5821 // A remote max message size of zero means "any size supported".
5822 // We configure the connection with our own max message size.
5823 if (remote_sctp_description->max_message_size() == 0) {
5824 max_message_size = local_sctp_description->max_message_size();
5825 } else {
5826 max_message_size =
5827 std::min(local_sctp_description->max_message_size(),
5828 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005829 }
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005830 sctp_transport->Start(local_sctp_description->port(),
5831 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005832 }
Steve Anton75737c02017-11-06 10:37:17 -08005833 }
Steve Antoned10bd92017-12-05 10:52:59 -08005834
Steve Anton8a006912017-12-04 15:25:56 -08005835 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005836}
5837
Steve Anton8a006912017-12-04 15:25:56 -08005838RTCError PeerConnection::PushdownTransportDescription(
5839 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005840 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005841 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005842
Zhi Huange830e682018-03-30 10:48:35 -07005843 if (source == cricket::CS_LOCAL) {
5844 const SessionDescriptionInterface* sdesc = local_description();
5845 RTC_DCHECK(sdesc);
5846 return transport_controller_->SetLocalDescription(type,
5847 sdesc->description());
5848 } else {
5849 const SessionDescriptionInterface* sdesc = remote_description();
5850 RTC_DCHECK(sdesc);
5851 return transport_controller_->SetRemoteDescription(type,
5852 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005853 }
Steve Anton75737c02017-11-06 10:37:17 -08005854}
5855
5856bool PeerConnection::GetTransportDescription(
5857 const SessionDescription* description,
5858 const std::string& content_name,
5859 cricket::TransportDescription* tdesc) {
5860 if (!description || !tdesc) {
5861 return false;
5862 }
5863 const TransportInfo* transport_info =
5864 description->GetTransportInfoByName(content_name);
5865 if (!transport_info) {
5866 return false;
5867 }
5868 *tdesc = transport_info->description;
5869 return true;
5870}
5871
Steve Anton75737c02017-11-06 10:37:17 -08005872cricket::IceConfig PeerConnection::ParseIceConfig(
5873 const PeerConnectionInterface::RTCConfiguration& config) const {
5874 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005875 switch (config.continual_gathering_policy) {
5876 case PeerConnectionInterface::GATHER_ONCE:
5877 gathering_policy = cricket::GATHER_ONCE;
5878 break;
5879 case PeerConnectionInterface::GATHER_CONTINUALLY:
5880 gathering_policy = cricket::GATHER_CONTINUALLY;
5881 break;
5882 default:
5883 RTC_NOTREACHED();
5884 gathering_policy = cricket::GATHER_ONCE;
5885 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005886
Steve Anton75737c02017-11-06 10:37:17 -08005887 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005888 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5889 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005890 ice_config.prioritize_most_likely_candidate_pairs =
5891 config.prioritize_most_likely_ice_candidate_pairs;
5892 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005893 RTCConfigurationToIceConfigOptionalInt(
5894 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005895 ice_config.continual_gathering_policy = gathering_policy;
5896 ice_config.presume_writable_when_fully_relayed =
5897 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005898 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5899 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005900 ice_config.ice_check_interval_strong_connectivity =
5901 config.ice_check_interval_strong_connectivity;
5902 ice_config.ice_check_interval_weak_connectivity =
5903 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005904 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005905 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5906 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005907 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005908 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005909 ice_config.regather_all_networks_interval_range =
5910 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005911 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005912 return ice_config;
5913}
5914
Steve Anton75737c02017-11-06 10:37:17 -08005915bool PeerConnection::SendData(const cricket::SendDataParams& params,
5916 const rtc::CopyOnWriteBuffer& payload,
5917 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005918 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005919 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005920 SendDataParams send_params;
5921 send_params.type = ToWebrtcDataMessageType(params.type);
5922 send_params.ordered = params.ordered;
5923 if (params.max_rtx_count >= 0) {
5924 send_params.max_rtx_count = params.max_rtx_count;
5925 } else if (params.max_rtx_ms >= 0) {
5926 send_params.max_rtx_ms = params.max_rtx_ms;
5927 }
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005928
5929 RTCError error = network_thread()->Invoke<RTCError>(
5930 RTC_FROM_HERE, [this, params, send_params, payload] {
5931 return data_channel_transport_->SendData(params.sid, send_params,
5932 payload);
5933 });
5934
5935 if (error.ok()) {
5936 *result = cricket::SendDataResult::SDR_SUCCESS;
5937 return true;
5938 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
5939 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
5940 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
5941 *result = cricket::SendDataResult::SDR_BLOCK;
5942 return false;
5943 }
5944 *result = cricket::SendDataResult::SDR_ERROR;
5945 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005946 } else if (rtp_data_channel_) {
5947 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005948 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005949 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
5950 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005951}
5952
5953bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005954 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005955 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005956 // Don't log an error here, because DataChannels are expected to call
5957 // ConnectDataChannel in this state. It's the only way to initially tell
5958 // whether or not the underlying transport is ready.
5959 return false;
5960 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005961 if (data_channel_transport_) {
5962 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
5963 &DataChannel::OnChannelReady);
5964 SignalDataChannelTransportReceivedData_s.connect(
5965 webrtc_data_channel, &DataChannel::OnDataReceived);
5966 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005967 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005968 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005969 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005970 }
5971 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005972 rtp_data_channel_->SignalReadyToSendData.connect(
5973 webrtc_data_channel, &DataChannel::OnChannelReady);
5974 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5975 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005976 }
Steve Anton75737c02017-11-06 10:37:17 -08005977 return true;
5978}
5979
5980void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005981 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07005982 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005983 RTC_LOG(LS_ERROR)
5984 << "DisconnectDataChannel called when rtp_data_channel_ and "
5985 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005986 return;
5987 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005988 if (data_channel_transport_) {
5989 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
5990 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
5991 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
5992 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
5993 }
5994 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005995 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5996 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005997 }
Steve Anton75737c02017-11-06 10:37:17 -08005998}
5999
6000void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006001 if (data_channel_transport_) {
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006002 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6003 if (data_channel_transport_) {
6004 data_channel_transport_->OpenChannel(sid);
6005 }
6006 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006007 }
Steve Anton75737c02017-11-06 10:37:17 -08006008}
6009
6010void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006011 if (data_channel_transport_) {
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006012 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6013 if (data_channel_transport_) {
6014 data_channel_transport_->CloseChannel(sid);
6015 }
6016 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006017 }
Steve Anton75737c02017-11-06 10:37:17 -08006018}
6019
6020bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006021 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006022 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006023 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006024}
6025
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006026void PeerConnection::OnDataReceived(int channel_id,
6027 DataMessageType type,
6028 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006029 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006030 cricket::ReceiveDataParams params;
6031 params.sid = channel_id;
6032 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006033 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006034 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6035 RTC_DCHECK_RUN_ON(signaling_thread());
6036 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006037 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006038 }
6039 });
6040}
6041
6042void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006043 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006044 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006045 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6046 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006047 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006048 });
6049}
6050
6051void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006052 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006053 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006054 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6055 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006056 SignalDataChannelTransportChannelClosed_s(channel_id);
6057 });
6058}
6059
6060void PeerConnection::OnReadyToSend() {
6061 RTC_DCHECK_RUN_ON(network_thread());
6062 data_channel_transport_invoker_->AsyncInvoke<void>(
6063 RTC_FROM_HERE, signaling_thread(), [this] {
6064 RTC_DCHECK_RUN_ON(signaling_thread());
6065 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006066 SignalDataChannelTransportWritable_s(
6067 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006068 });
6069}
6070
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006071absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006072 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006073 if (sctp_mid_ && transport_controller_) {
6074 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6075 if (dtls_transport) {
6076 return dtls_transport->transport_name();
6077 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006078 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006079 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006080 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006081}
6082
Qingsi Wang72a43a12018-02-20 16:03:18 -08006083cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6084 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006085 network_thread()->Invoke<void>(
6086 RTC_FROM_HERE,
6087 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6088 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006089 return candidate_states_list;
6090}
6091
Steve Anton5dfde182018-02-06 10:34:40 -08006092std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6093 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006094 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006095 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006096 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006097 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006098 if (channel) {
6099 transport_names_by_mid[channel->content_name()] =
6100 channel->transport_name();
6101 }
Steve Anton75737c02017-11-06 10:37:17 -08006102 }
Steve Anton5dfde182018-02-06 10:34:40 -08006103 if (rtp_data_channel_) {
6104 transport_names_by_mid[rtp_data_channel_->content_name()] =
6105 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006106 }
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006107 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006108 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006109 RTC_DCHECK(transport_name);
6110 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006111 }
Steve Anton5dfde182018-02-06 10:34:40 -08006112 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006113}
6114
Steve Anton5dfde182018-02-06 10:34:40 -08006115std::map<std::string, cricket::TransportStats>
6116PeerConnection::GetTransportStatsByNames(
6117 const std::set<std::string>& transport_names) {
6118 if (!network_thread()->IsCurrent()) {
6119 return network_thread()
6120 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6121 RTC_FROM_HERE,
6122 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006123 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006124 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006125 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6126 for (const std::string& transport_name : transport_names) {
6127 cricket::TransportStats transport_stats;
6128 bool success =
6129 transport_controller_->GetStats(transport_name, &transport_stats);
6130 if (success) {
6131 transport_stats_by_name[transport_name] = std::move(transport_stats);
6132 } else {
6133 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6134 << transport_name;
6135 }
6136 }
6137 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006138}
6139
6140bool PeerConnection::GetLocalCertificate(
6141 const std::string& transport_name,
6142 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006143 if (!certificate) {
6144 return false;
6145 }
6146 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6147 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006148}
6149
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006150std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006151 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006152 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006153}
6154
6155cricket::DataChannelType PeerConnection::data_channel_type() const {
6156 return data_channel_type_;
6157}
6158
6159bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006160 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006161 return pending_ice_restarts_.find(content_name) !=
6162 pending_ice_restarts_.end();
6163}
6164
Steve Anton75737c02017-11-06 10:37:17 -08006165bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6166 return transport_controller_->NeedsIceRestart(content_name);
6167}
6168
6169void PeerConnection::OnCertificateReady(
6170 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6171 transport_controller_->SetLocalCertificate(certificate);
6172}
6173
6174void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006175 SetSessionError(SessionError::kTransport,
6176 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006177}
6178
Alex Loiko9289eda2018-11-23 16:18:59 +00006179void PeerConnection::OnTransportControllerConnectionState(
6180 cricket::IceConnectionState state) {
6181 switch (state) {
6182 case cricket::kIceConnectionConnecting:
6183 // If the current state is Connected or Completed, then there were
6184 // writable channels but now there are not, so the next state must
6185 // be Disconnected.
6186 // kIceConnectionConnecting is currently used as the default,
6187 // un-connected state by the TransportController, so its only use is
6188 // detecting disconnections.
6189 if (ice_connection_state_ ==
6190 PeerConnectionInterface::kIceConnectionConnected ||
6191 ice_connection_state_ ==
6192 PeerConnectionInterface::kIceConnectionCompleted) {
6193 SetIceConnectionState(
6194 PeerConnectionInterface::kIceConnectionDisconnected);
6195 }
6196 break;
6197 case cricket::kIceConnectionFailed:
6198 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6199 break;
6200 case cricket::kIceConnectionConnected:
6201 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6202 "all transports are writable.";
6203 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6204 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6205 break;
6206 case cricket::kIceConnectionCompleted:
6207 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6208 "all transports are complete.";
6209 if (ice_connection_state_ !=
6210 PeerConnectionInterface::kIceConnectionConnected) {
6211 // If jumping directly from "checking" to "connected",
6212 // signal "connected" first.
6213 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6214 }
6215 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6216 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6217 ReportTransportStats();
6218 break;
6219 default:
6220 RTC_NOTREACHED();
6221 }
6222}
6223
Steve Anton75737c02017-11-06 10:37:17 -08006224void PeerConnection::OnTransportControllerCandidatesGathered(
6225 const std::string& transport_name,
6226 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006227 int sdp_mline_index;
6228 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006229 RTC_LOG(LS_ERROR)
6230 << "OnTransportControllerCandidatesGathered: content name "
6231 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006232 return;
6233 }
6234
6235 for (cricket::Candidates::const_iterator citer = candidates.begin();
6236 citer != candidates.end(); ++citer) {
6237 // Use transport_name as the candidate media id.
6238 std::unique_ptr<JsepIceCandidate> candidate(
6239 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6240 if (local_description()) {
6241 mutable_local_description()->AddCandidate(candidate.get());
6242 }
6243 OnIceCandidate(std::move(candidate));
6244 }
6245}
6246
Eldar Relloda13ea22019-06-01 12:23:43 +03006247void PeerConnection::OnTransportControllerCandidateError(
6248 const cricket::IceCandidateErrorEvent& event) {
6249 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6250 event.error_text);
6251}
6252
Steve Anton75737c02017-11-06 10:37:17 -08006253void PeerConnection::OnTransportControllerCandidatesRemoved(
6254 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006255 // Sanity check.
6256 for (const cricket::Candidate& candidate : candidates) {
6257 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006258 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006259 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006260 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006261 return;
6262 }
6263 }
6264
6265 if (local_description()) {
6266 mutable_local_description()->RemoveCandidates(candidates);
6267 }
6268 OnIceCandidatesRemoved(candidates);
6269}
6270
Alex Drake00c7ecf2019-08-06 10:54:47 -07006271void PeerConnection::OnTransportControllerCandidateChanged(
6272 const cricket::CandidatePairChangeEvent& event) {
6273 OnSelectedCandidatePairChanged(event);
6274}
6275
Steve Anton75737c02017-11-06 10:37:17 -08006276void PeerConnection::OnTransportControllerDtlsHandshakeError(
6277 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006278 RTC_HISTOGRAM_ENUMERATION(
6279 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6280 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006281}
6282
Steve Antoned10bd92017-12-05 10:52:59 -08006283void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006284 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006285 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006286 if (channel && !channel->enabled()) {
6287 channel->Enable(true);
6288 }
Steve Anton75737c02017-11-06 10:37:17 -08006289 }
6290
Steve Anton4171afb2017-11-20 10:20:22 -08006291 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006292 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006293 }
Steve Anton75737c02017-11-06 10:37:17 -08006294}
6295
6296// Returns the media index for a local ice candidate given the content name.
6297bool PeerConnection::GetLocalCandidateMediaIndex(
6298 const std::string& content_name,
6299 int* sdp_mline_index) {
6300 if (!local_description() || !sdp_mline_index) {
6301 return false;
6302 }
6303
6304 bool content_found = false;
6305 const ContentInfos& contents = local_description()->description()->contents();
6306 for (size_t index = 0; index < contents.size(); ++index) {
6307 if (contents[index].name == content_name) {
6308 *sdp_mline_index = static_cast<int>(index);
6309 content_found = true;
6310 break;
6311 }
6312 }
6313 return content_found;
6314}
6315
6316bool PeerConnection::UseCandidatesInSessionDescription(
6317 const SessionDescriptionInterface* remote_desc) {
6318 if (!remote_desc) {
6319 return true;
6320 }
6321 bool ret = true;
6322
6323 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6324 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6325 for (size_t n = 0; n < candidates->count(); ++n) {
6326 const IceCandidateInterface* candidate = candidates->at(n);
6327 bool valid = false;
6328 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6329 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006330 RTC_LOG(LS_INFO)
6331 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006332 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006333 }
6334 continue;
6335 }
6336 ret = UseCandidate(candidate);
6337 if (!ret) {
6338 break;
6339 }
6340 }
6341 }
6342 return ret;
6343}
6344
6345bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006346 RTCErrorOr<const cricket::ContentInfo*> result =
6347 FindContentInfo(remote_description(), candidate);
6348 if (!result.ok()) {
6349 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6350 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006351 return false;
6352 }
Steve Anton75737c02017-11-06 10:37:17 -08006353 std::vector<cricket::Candidate> candidates;
6354 candidates.push_back(candidate->candidate());
6355 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006356 RTCError error = transport_controller_->AddRemoteCandidates(
6357 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006358 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006359 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006360 // Candidates successfully submitted for checking.
6361 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6362 ice_connection_state_ ==
6363 PeerConnectionInterface::kIceConnectionDisconnected) {
6364 // If state is New, then the session has just gotten its first remote ICE
6365 // candidates, so go to Checking.
6366 // If state is Disconnected, the session is re-using old candidates or
6367 // receiving additional ones, so go to Checking.
6368 // If state is Connected, stay Connected.
6369 // TODO(bemasc): If state is Connected, and the new candidates are for a
6370 // newly added transport, then the state actually _should_ move to
6371 // checking. Add a way to distinguish that case.
6372 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6373 }
6374 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006375 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006376 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006377 }
6378 return true;
6379}
6380
Guido Urdaneta41633172019-05-23 20:12:29 +02006381RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6382 const SessionDescriptionInterface* description,
6383 const IceCandidateInterface* candidate) {
6384 if (candidate->sdp_mline_index() >= 0) {
6385 size_t mediacontent_index =
6386 static_cast<size_t>(candidate->sdp_mline_index());
6387 size_t content_size = description->description()->contents().size();
6388 if (mediacontent_index < content_size) {
6389 return &description->description()->contents()[mediacontent_index];
6390 } else {
6391 return RTCError(RTCErrorType::INVALID_RANGE,
6392 "Media line index (" +
6393 rtc::ToString(candidate->sdp_mline_index()) +
6394 ") out of range (number of mlines: " +
6395 rtc::ToString(content_size) + ").");
6396 }
6397 } else if (!candidate->sdp_mid().empty()) {
6398 auto& contents = description->description()->contents();
6399 auto it = absl::c_find_if(
6400 contents, [candidate](const cricket::ContentInfo& content_info) {
6401 return content_info.mid() == candidate->sdp_mid();
6402 });
6403 if (it == contents.end()) {
6404 return RTCError(
6405 RTCErrorType::INVALID_PARAMETER,
6406 "Mid " + candidate->sdp_mid() +
6407 " specified but no media section with that mid found.");
6408 } else {
6409 return &*it;
6410 }
6411 }
6412
6413 return RTCError(RTCErrorType::INVALID_PARAMETER,
6414 "Neither sdp_mline_index nor sdp_mid specified.");
6415}
6416
Steve Anton75737c02017-11-06 10:37:17 -08006417void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006418 // Destroy video channel first since it may have a pointer to the
6419 // voice channel.
6420 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006421 if (!video_info || video_info->rejected) {
6422 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006423 }
6424
Steve Anton6fec8802017-12-04 10:37:29 -08006425 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6426 if (!audio_info || audio_info->rejected) {
6427 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006428 }
6429
6430 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6431 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006432 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006433 }
6434}
6435
Steve Antondcc3c022017-12-22 16:02:54 -08006436RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6437 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006438 const cricket::ContentGroup* bundle_group = nullptr;
6439 if (configuration_.bundle_policy ==
6440 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006441 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006442 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006443 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6444 "max-bundle configured but session description "
6445 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006446 }
6447 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006448 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006449}
6450
6451RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006452 // Creating the media channels. Transports should already have been created
6453 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006454 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006455 if (voice && !voice->rejected &&
6456 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006457 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006458 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006459 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6460 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006461 }
6462 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6463 }
6464
Steve Antondcc3c022017-12-22 16:02:54 -08006465 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006466 if (video && !video->rejected &&
6467 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006468 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006469 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006470 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6471 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006472 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006473 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006474 }
6475
Steve Antondcc3c022017-12-22 16:02:54 -08006476 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006477 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006478 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006479 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006480 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6481 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006482 }
6483 }
6484
Steve Anton8a006912017-12-04 15:25:56 -08006485 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006486}
6487
Steve Anton4171afb2017-11-20 10:20:22 -08006488// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006489cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006490 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006491 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006492 MediaTransportConfig media_transport_config =
6493 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006494
Steve Anton75737c02017-11-06 10:37:17 -08006495 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006496 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006497 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6498 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006499 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006500 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006501 }
Steve Anton75737c02017-11-06 10:37:17 -08006502 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6503 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006504 voice_channel->SignalSentPacket.connect(this,
6505 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006506 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006507
Steve Antoneda6ccd2017-12-04 10:21:55 -08006508 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006509}
6510
Steve Anton4171afb2017-11-20 10:20:22 -08006511// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006512cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006513 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006514 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006515 MediaTransportConfig media_transport_config =
6516 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006517
Steve Anton75737c02017-11-06 10:37:17 -08006518 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006519 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006520 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6521 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006522 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006523 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006524 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006525 }
Steve Anton75737c02017-11-06 10:37:17 -08006526 video_channel->SignalDtlsSrtpSetupFailure.connect(
6527 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006528 video_channel->SignalSentPacket.connect(this,
6529 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006530 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006531
Steve Antoneda6ccd2017-12-04 10:21:55 -08006532 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006533}
6534
Zhi Huange830e682018-03-30 10:48:35 -07006535bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006536 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006537 case cricket::DCT_SCTP:
Henrik Boström8b14b0d2019-08-30 12:31:06 +00006538 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Henrik Boström8b14b0d2019-08-30 12:31:06 +00006539 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6540 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006541 if (!network_thread()->Invoke<bool>(
6542 RTC_FROM_HERE,
6543 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6544 mid))) {
Henrik Boström8b14b0d2019-08-30 12:31:06 +00006545 return false;
6546 }
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006547
6548 // All non-RTP data channels must initialize |sctp_data_channels_|.
6549 for (const auto& channel : sctp_data_channels_) {
6550 channel->OnTransportChannelCreated();
6551 }
6552 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006553 case cricket::DCT_RTP:
6554 default:
6555 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6556 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6557 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006558 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006559 if (!rtp_data_channel_) {
6560 return false;
6561 }
6562 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6563 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6564 rtp_data_channel_->SignalSentPacket.connect(
6565 this, &PeerConnection::OnSentPacket_w);
6566 rtp_data_channel_->SetRtpTransport(rtp_transport);
6567 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006568 }
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006569 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006570}
6571
6572Call::Stats PeerConnection::GetCallStats() {
6573 if (!worker_thread()->IsCurrent()) {
6574 return worker_thread()->Invoke<Call::Stats>(
6575 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6576 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006577 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006578 if (call_) {
6579 return call_->GetStats();
6580 } else {
6581 return Call::Stats();
6582 }
6583}
6584
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006585bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006586 DataChannelTransportInterface* transport =
6587 transport_controller_->GetDataChannelTransport(mid);
6588 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006589 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006590 << "Data channel transport is not available for data channels, mid="
6591 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006592 return false;
6593 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006594 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006595
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006596 transport->SetDataSink(this);
6597 data_channel_transport_ = transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006598 data_channel_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006599 sctp_mid_ = mid;
6600 // TODO(mellem): Handling data channel state through media transport is
6601 // deprecated. Delete these lines when downstream implementations call
6602 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006603 transport_controller_->SignalMediaTransportStateChanged.connect(
6604 this, &PeerConnection::OnMediaTransportStateChanged_n);
6605 // Check the initial state right away, in case transport is already writable.
6606 OnMediaTransportStateChanged_n();
6607 return true;
6608}
6609
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006610void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006611 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006612 return;
6613 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006614 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6615 << *sctp_mid_;
6616
6617 // TODO(mellem): Delete this line when downstream implementations call
6618 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006619 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006620 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6621 // it.
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006622 sctp_mid_.reset();
Henrik Boström8b14b0d2019-08-30 12:31:06 +00006623 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006624 if (data_channel_transport_) {
6625 data_channel_transport_->SetDataSink(nullptr);
6626 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006627 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006628}
6629
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006630// TODO(mellem): Handling of data channel state through the media transport
6631// callback is deprecated. This function should be deleted once downstream
6632// implementations call DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006633void PeerConnection::OnMediaTransportStateChanged_n() {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006634 if (!sctp_mid_ || transport_controller_->GetMediaTransportState(*sctp_mid_) !=
6635 MediaTransportState::kWritable) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006636 return;
6637 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006638 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006639 RTC_FROM_HERE, signaling_thread(), [this] {
6640 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006641 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07006642 SignalDataChannelTransportWritable_s(
6643 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006644 });
6645}
6646
Steve Anton75737c02017-11-06 10:37:17 -08006647// Returns false if bundle is enabled and rtcp_mux is disabled.
6648bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6649 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6650 if (!bundle_enabled)
6651 return true;
6652
6653 const cricket::ContentGroup* bundle_group =
6654 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6655 RTC_DCHECK(bundle_group != NULL);
6656
6657 const cricket::ContentInfos& contents = desc->contents();
6658 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6659 citer != contents.end(); ++citer) {
6660 const cricket::ContentInfo* content = (&*citer);
6661 RTC_DCHECK(content != NULL);
6662 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006663 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006664 if (!HasRtcpMuxEnabled(content))
6665 return false;
6666 }
6667 }
6668 // RTCP-MUX is enabled in all the contents.
6669 return true;
6670}
6671
6672bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006673 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006674}
6675
Steve Anton06817cd2018-12-18 15:55:30 -08006676static RTCError ValidateMids(const cricket::SessionDescription& description) {
6677 std::set<std::string> mids;
6678 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006679 if (content.name.empty()) {
6680 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6681 "A media section is missing a MID attribute.");
6682 }
Steve Anton06817cd2018-12-18 15:55:30 -08006683 if (!mids.insert(content.name).second) {
6684 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6685 "Duplicate a=mid value '" + content.name + "'.");
6686 }
6687 }
6688 return RTCError::OK();
6689}
6690
Steve Anton8a006912017-12-04 15:25:56 -08006691RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006692 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006693 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006694 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006695 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006696 }
6697
6698 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006699 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006700 }
6701
Steve Anton3828c062017-12-06 10:34:51 -08006702 SdpType type = sdesc->GetType();
6703 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6704 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006705 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006706 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006707 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006708 }
6709
Steve Anton06817cd2018-12-18 15:55:30 -08006710 RTCError error = ValidateMids(*sdesc->description());
6711 if (!error.ok()) {
6712 return error;
6713 }
6714
Steve Anton75737c02017-11-06 10:37:17 -08006715 // Verify crypto settings.
6716 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006717 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6718 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006719 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006720 if (!crypto_error.ok()) {
6721 return crypto_error;
6722 }
Steve Anton75737c02017-11-06 10:37:17 -08006723 }
6724
6725 // Verify ice-ufrag and ice-pwd.
6726 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6728 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006729 }
6730
6731 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6733 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006734 }
6735
6736 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6737 // m-lines that do not rtcp-mux enabled.
6738
6739 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006740 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006741 // With an answer we want to compare the new answer session description with
6742 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006743 const cricket::SessionDescription* offer_desc =
6744 (source == cricket::CS_LOCAL) ? remote_description()->description()
6745 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006746 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6747 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6748 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6750 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006751 }
6752 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006753 // The re-offers should respect the order of m= sections in current
6754 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006755 // With a re-offer, either the current local or current remote descriptions
6756 // could be the most up to date, so we would like to check against both of
6757 // them if they exist. It could be the case that one of them has a 0 port
6758 // for a media section, but the other does not. This is important to check
6759 // against in the case that we are recycling an m= section.
6760 const cricket::SessionDescription* current_desc = nullptr;
6761 const cricket::SessionDescription* secondary_current_desc = nullptr;
6762 if (local_description()) {
6763 current_desc = local_description()->description();
6764 if (remote_description()) {
6765 secondary_current_desc = remote_description()->description();
6766 }
6767 } else if (remote_description()) {
6768 current_desc = remote_description()->description();
6769 }
Steve Anton75737c02017-11-06 10:37:17 -08006770 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006771 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6772 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006773 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6774 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006775 }
6776 }
6777
Steve Antonba42e992018-04-09 14:10:01 -07006778 if (IsUnifiedPlan()) {
6779 // Ensure that each audio and video media section has at most one
6780 // "StreamParams". This will return an error if receiving a session
6781 // description from a "Plan B" endpoint which adds multiple tracks of the
6782 // same type. With Unified Plan, there can only be at most one track per
6783 // media section.
6784 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006785 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006786 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6787 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6788 desc.streams().size() > 1u) {
6789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6790 "Media section has more than one track specified "
6791 "with a=ssrc lines which is not supported with "
6792 "Unified Plan.");
6793 }
6794 }
6795 }
6796
Steve Anton8a006912017-12-04 15:25:56 -08006797 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006798}
6799
Steve Anton3828c062017-12-06 10:34:51 -08006800bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006801 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006802 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006803 return (state == PeerConnectionInterface::kStable) ||
6804 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006805 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006806 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006807 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6808 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6809 }
6810}
6811
Steve Anton3828c062017-12-06 10:34:51 -08006812bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006813 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006814 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006815 return (state == PeerConnectionInterface::kStable) ||
6816 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006817 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006818 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006819 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6820 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6821 }
6822}
6823
Steve Antonf8470812017-12-04 10:46:21 -08006824const char* PeerConnection::SessionErrorToString(SessionError error) const {
6825 switch (error) {
6826 case SessionError::kNone:
6827 return "ERROR_NONE";
6828 case SessionError::kContent:
6829 return "ERROR_CONTENT";
6830 case SessionError::kTransport:
6831 return "ERROR_TRANSPORT";
6832 }
6833 RTC_NOTREACHED();
6834 return "";
6835}
6836
Steve Anton75737c02017-11-06 10:37:17 -08006837std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006838 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006839 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6840 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006841 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006842}
6843
Steve Anton8e20f172018-03-06 10:55:04 -08006844void PeerConnection::ReportSdpFormatReceived(
6845 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006846 int num_audio_mlines = 0;
6847 int num_video_mlines = 0;
6848 int num_audio_tracks = 0;
6849 int num_video_tracks = 0;
6850 for (const ContentInfo& content : remote_offer.description()->contents()) {
6851 cricket::MediaType media_type = content.media_description()->type();
6852 int num_tracks = std::max(
6853 1, static_cast<int>(content.media_description()->streams().size()));
6854 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6855 num_audio_mlines += 1;
6856 num_audio_tracks += num_tracks;
6857 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6858 num_video_mlines += 1;
6859 num_video_tracks += num_tracks;
6860 }
6861 }
6862 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6863 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6864 format = kSdpFormatReceivedComplexUnifiedPlan;
6865 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6866 format = kSdpFormatReceivedComplexPlanB;
6867 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6868 format = kSdpFormatReceivedSimple;
6869 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006870 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6871 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006872}
6873
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006874void PeerConnection::ReportIceCandidateCollected(
6875 const cricket::Candidate& candidate) {
6876 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
6877 if (candidate.address().IsPrivateIP()) {
6878 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
6879 }
6880 if (candidate.address().IsUnresolvedIP()) {
6881 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
6882 }
6883 if (candidate.address().family() == AF_INET6) {
6884 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
6885 }
6886}
6887
6888void PeerConnection::ReportRemoteIceCandidateAdded(
6889 const cricket::Candidate& candidate) {
6890 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
6891 if (candidate.address().IsPrivateIP()) {
6892 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
6893 }
6894 if (candidate.address().IsUnresolvedIP()) {
6895 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
6896 }
6897 if (candidate.address().family() == AF_INET6) {
6898 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
6899 }
6900}
6901
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006902void PeerConnection::NoteUsageEvent(UsageEvent event) {
6903 RTC_DCHECK_RUN_ON(signaling_thread());
6904 usage_event_accumulator_ |= static_cast<int>(event);
6905}
6906
6907void PeerConnection::ReportUsagePattern() const {
6908 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006909 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6910 usage_event_accumulator_,
6911 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006912 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006913 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006914 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6915 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006916 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006917 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6918 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6919 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6920 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006921 // If called after close(), we can't report, because observer may have
6922 // been deallocated, and therefore pointer is null. Write to log instead.
6923 if (observer_) {
6924 Observer()->OnInterestingUsage(usage_event_accumulator_);
6925 } else {
6926 RTC_LOG(LS_INFO) << "Interesting usage signature "
6927 << usage_event_accumulator_
6928 << " observed after observer shutdown";
6929 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006930 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006931}
6932
Steve Anton0ffaaa22018-02-23 10:31:30 -08006933void PeerConnection::ReportNegotiatedSdpSemantics(
6934 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006935 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006936 switch (answer.description()->msid_signaling()) {
6937 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006938 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006939 break;
6940 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006941 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006942 break;
6943 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006944 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006945 break;
6946 case cricket::kMsidSignalingMediaSection |
6947 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006948 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006949 break;
6950 default:
6951 RTC_NOTREACHED();
6952 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006953 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6954 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006955}
6956
Steve Anton75737c02017-11-06 10:37:17 -08006957// We need to check the local/remote description for the Transport instead of
6958// the session, because a new Transport added during renegotiation may have
6959// them unset while the session has them set from the previous negotiation.
6960// Not doing so may trigger the auto generation of transport description and
6961// mess up DTLS identity information, ICE credential, etc.
6962bool PeerConnection::ReadyToUseRemoteCandidate(
6963 const IceCandidateInterface* candidate,
6964 const SessionDescriptionInterface* remote_desc,
6965 bool* valid) {
6966 *valid = true;
6967
6968 const SessionDescriptionInterface* current_remote_desc =
6969 remote_desc ? remote_desc : remote_description();
6970
6971 if (!current_remote_desc) {
6972 return false;
6973 }
6974
Guido Urdaneta41633172019-05-23 20:12:29 +02006975 RTCErrorOr<const cricket::ContentInfo*> result =
6976 FindContentInfo(current_remote_desc, candidate);
6977 if (!result.ok()) {
6978 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6979 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006980
6981 *valid = false;
6982 return false;
6983 }
6984
Guido Urdaneta41633172019-05-23 20:12:29 +02006985 std::string transport_name = GetTransportName(result.value()->name);
6986 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006987}
6988
6989bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07006990 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006991 (dtls_enabled_ ||
6992 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006993}
6994
6995void PeerConnection::OnTransportControllerGatheringState(
6996 cricket::IceGatheringState state) {
6997 RTC_DCHECK(signaling_thread()->IsCurrent());
6998 if (state == cricket::kIceGatheringGathering) {
6999 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7000 } else if (state == cricket::kIceGatheringComplete) {
7001 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7002 }
7003}
7004
7005void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007006 std::map<std::string, std::set<cricket::MediaType>>
7007 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007008 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007009 if (transceiver->internal()->channel()) {
7010 const std::string& transport_name =
7011 transceiver->internal()->channel()->transport_name();
7012 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007013 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007014 }
Steve Anton75737c02017-11-06 10:37:17 -08007015 }
7016 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007017 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7018 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007019 }
Zhi Huange830e682018-03-30 10:48:35 -07007020
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007021 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007022 if (transport_name) {
7023 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007024 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007025 }
Zhi Huange830e682018-03-30 10:48:35 -07007026
Steve Antonc7b964c2018-02-01 14:39:45 -08007027 for (const auto& entry : media_types_by_transport_name) {
7028 const std::string& transport_name = entry.first;
7029 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007030 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007031 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007032 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007033 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007034 }
7035 }
7036}
7037// Walk through the ConnectionInfos to gather best connection usage
7038// for IPv4 and IPv6.
7039void PeerConnection::ReportBestConnectionState(
7040 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007041 for (const cricket::TransportChannelStats& channel_stats :
7042 stats.channel_stats) {
7043 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007044 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007045 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007046 continue;
7047 }
7048
Steve Antonc7b964c2018-02-01 14:39:45 -08007049 const cricket::Candidate& local = connection_info.local_candidate;
7050 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007051
7052 // Increment the counter for IceCandidatePairType.
7053 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7054 (local.type() == RELAY_PORT_TYPE &&
7055 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007056 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7057 GetIceCandidatePairCounter(local, remote),
7058 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007059 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007060 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7061 GetIceCandidatePairCounter(local, remote),
7062 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007063 } else {
7064 RTC_CHECK(0);
7065 }
Steve Anton75737c02017-11-06 10:37:17 -08007066
7067 // Increment the counter for IP type.
7068 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007069 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7070 kBestConnections_IPv4,
7071 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007072 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007073 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7074 kBestConnections_IPv6,
7075 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007076 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007077 RTC_CHECK(!local.address().hostname().empty() &&
7078 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007079 }
7080
7081 return;
7082 }
7083 }
7084}
7085
7086void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007087 const cricket::TransportStats& stats,
7088 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007089 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7090 return;
7091 }
7092
7093 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7094 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7095 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7096 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7097 return;
7098 }
7099
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007100 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7101 for (cricket::MediaType media_type : media_types) {
7102 switch (media_type) {
7103 case cricket::MEDIA_TYPE_AUDIO:
7104 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7105 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7106 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7107 break;
7108 case cricket::MEDIA_TYPE_VIDEO:
7109 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7110 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7111 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7112 break;
7113 case cricket::MEDIA_TYPE_DATA:
7114 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7115 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7116 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7117 break;
7118 default:
7119 RTC_NOTREACHED();
7120 continue;
7121 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007122 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007123 }
7124
7125 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7126 for (cricket::MediaType media_type : media_types) {
7127 switch (media_type) {
7128 case cricket::MEDIA_TYPE_AUDIO:
7129 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7130 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7131 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7132 break;
7133 case cricket::MEDIA_TYPE_VIDEO:
7134 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7135 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7136 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7137 break;
7138 case cricket::MEDIA_TYPE_DATA:
7139 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7140 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7141 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7142 break;
7143 default:
7144 RTC_NOTREACHED();
7145 continue;
7146 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007147 }
Steve Anton75737c02017-11-06 10:37:17 -08007148 }
7149}
7150
7151void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007152 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007153 RTC_DCHECK(call_);
7154 call_->OnSentPacket(sent_packet);
7155}
7156
7157const std::string PeerConnection::GetTransportName(
7158 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007159 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007160 if (channel) {
7161 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007162 }
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07007163 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007164 RTC_DCHECK(sctp_mid_);
7165 if (content_name == *sctp_mid_) {
7166 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007167 }
7168 }
7169 // Return an empty string if failed to retrieve the transport name.
7170 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007171}
7172
Steve Anton6fec8802017-12-04 10:37:29 -08007173void PeerConnection::DestroyTransceiverChannel(
7174 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7175 transceiver) {
7176 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007177
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007178 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007179 if (channel) {
7180 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007181 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007182 }
7183}
7184
7185void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007186 if (rtp_data_channel_) {
7187 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007188 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007189 rtp_data_channel_ = nullptr;
7190 }
7191
7192 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7193 // grab a reference to this PeerConnection. If this is called from the
7194 // PeerConnection destructor, the RefCountedObject vtable will have already
7195 // been destroyed (since it is a subclass of PeerConnection) and using
7196 // rtc::Bind will cause "Pure virtual function called" error to appear.
7197
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07007198 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007199 OnDataChannelDestroyed();
7200 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7201 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007202 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007203 });
7204 }
Steve Anton6fec8802017-12-04 10:37:29 -08007205}
7206
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007207void PeerConnection::DestroyChannelInterface(
7208 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007209 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007210 switch (channel->media_type()) {
7211 case cricket::MEDIA_TYPE_AUDIO:
7212 channel_manager()->DestroyVoiceChannel(
7213 static_cast<cricket::VoiceChannel*>(channel));
7214 break;
7215 case cricket::MEDIA_TYPE_VIDEO:
7216 channel_manager()->DestroyVideoChannel(
7217 static_cast<cricket::VideoChannel*>(channel));
7218 break;
7219 case cricket::MEDIA_TYPE_DATA:
7220 channel_manager()->DestroyRtpDataChannel(
7221 static_cast<cricket::RtpDataChannel*>(channel));
7222 break;
7223 default:
7224 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7225 break;
7226 }
Zhi Huange830e682018-03-30 10:48:35 -07007227}
Steve Anton6fec8802017-12-04 10:37:29 -08007228
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007229bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007230 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007231 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007232 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007233 MediaTransportInterface* media_transport,
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07007234 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007235 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007236 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007237 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007238 auto base_channel = GetChannel(mid);
7239 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007240 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007241 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007242
Karl Wiberg5966c502019-02-21 23:55:09 +01007243 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007244 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007245 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007246
Bjorn A Mellem487f9a12019-09-09 13:11:49 -07007247 if (data_channel_transport_ && mid == sctp_mid_ &&
7248 data_channel_transport_ != data_channel_transport) {
7249 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7250 // it's bundled).
7251 data_channel_transport_->SetDataSink(nullptr);
7252 data_channel_transport_ = data_channel_transport;
7253 if (data_channel_transport) {
7254 data_channel_transport->SetDataSink(this);
7255
7256 // There's a new data channel transport. This needs to be signaled to the
7257 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7258 // necessary when bundling is applied.
7259 data_channel_transport_invoker_->AsyncInvoke<void>(
7260 RTC_FROM_HERE, signaling_thread(), [this] {
7261 RTC_DCHECK_RUN_ON(signaling_thread());
7262 for (auto channel : sctp_data_channels_) {
7263 channel->OnTransportChannelCreated();
7264 }
7265 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007266 }
7267 }
7268
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007269 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007270}
7271
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007272void PeerConnection::OnSetStreams() {
7273 RTC_DCHECK_RUN_ON(signaling_thread());
7274 if (IsUnifiedPlan())
7275 UpdateNegotiationNeeded();
7276}
7277
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007278PeerConnectionObserver* PeerConnection::Observer() const {
7279 // In earlier production code, the pointer was not cleared on close,
7280 // which might have led to undefined behavior if the observer was not
7281 // deallocated, or strange crashes if it was.
7282 // We use CHECK in order to catch such behavior if it exists.
7283 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7284 RTC_CHECK(observer_);
7285 return observer_;
7286}
7287
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007288CryptoOptions PeerConnection::GetCryptoOptions() {
7289 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7290 // after it has been removed.
7291 return configuration_.crypto_options.has_value()
7292 ? *configuration_.crypto_options
7293 : factory_->options().crypto_options;
7294}
7295
Harald Alvestrand89061872018-01-02 14:08:34 +01007296void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007297 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007298 if (stats_collector_) {
7299 stats_collector_->ClearCachedStatsReport();
7300 }
7301}
7302
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007303void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007304 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7305 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007306}
7307
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007308void PeerConnection::UpdateNegotiationNeeded() {
7309 RTC_DCHECK_RUN_ON(signaling_thread());
7310 if (!IsUnifiedPlan()) {
7311 Observer()->OnRenegotiationNeeded();
7312 return;
7313 }
7314
7315 // If connection's [[IsClosed]] slot is true, abort these steps.
7316 if (IsClosed())
7317 return;
7318
7319 // If connection's signaling state is not "stable", abort these steps.
7320 if (signaling_state() != kStable)
7321 return;
7322
7323 // NOTE
7324 // The negotiation-needed flag will be updated once the state transitions to
7325 // "stable", as part of the steps for setting an RTCSessionDescription.
7326
7327 // If the result of checking if negotiation is needed is false, clear the
7328 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7329 // to false, and abort these steps.
7330 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7331 if (!is_negotiation_needed) {
7332 is_negotiation_needed_ = false;
7333 return;
7334 }
7335
7336 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7337 // steps.
7338 if (is_negotiation_needed_)
7339 return;
7340
7341 // Set connection's [[NegotiationNeeded]] slot to true.
7342 is_negotiation_needed_ = true;
7343
7344 // Queue a task that runs the following steps:
7345 // If connection's [[IsClosed]] slot is true, abort these steps.
7346 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7347 // Fire an event named negotiationneeded at connection.
7348 Observer()->OnRenegotiationNeeded();
7349}
7350
7351bool PeerConnection::CheckIfNegotiationIsNeeded() {
7352 RTC_DCHECK_RUN_ON(signaling_thread());
7353 // 1. If any implementation-specific negotiation is required, as described at
7354 // the start of this section, return true.
7355
Henrik Boström79b69802019-07-18 11:16:56 +02007356 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7357 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7358 return true;
7359 }
7360
7361 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007362 const SessionDescriptionInterface* description = current_local_description();
7363 if (!description)
7364 return true;
7365
Henrik Boström79b69802019-07-18 11:16:56 +02007366 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007367 // description has been negotiated yet for data, return true.
7368 if (!sctp_data_channels_.empty()) {
7369 if (!cricket::GetFirstDataContent(description->description()->contents()))
7370 return true;
7371 }
7372
Henrik Boström79b69802019-07-18 11:16:56 +02007373 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007374 // following checks:
7375 for (const auto& transceiver : transceivers_) {
7376 const ContentInfo* current_local_msection =
7377 FindTransceiverMSection(transceiver.get(), description);
7378
7379 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7380 transceiver.get(), current_remote_description());
7381
Henrik Boström79b69802019-07-18 11:16:56 +02007382 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007383 // but the associated m= section is not yet rejected in
7384 // connection.[[CurrentLocalDescription]] or
7385 // connection.[[CurrentRemoteDescription]], return true.
7386 if (transceiver->stopped()) {
7387 if (current_local_msection && !current_local_msection->rejected &&
7388 ((current_remote_msection && !current_remote_msection->rejected) ||
7389 !current_remote_msection)) {
7390 return true;
7391 }
7392 continue;
7393 }
7394
Henrik Boström79b69802019-07-18 11:16:56 +02007395 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007396 // section in description, return true.
7397 if (!current_local_msection)
7398 return true;
7399
7400 const MediaContentDescription* current_local_media_description =
7401 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007402 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007403 // in description then perform the following checks:
7404
Henrik Boström79b69802019-07-18 11:16:56 +02007405 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007406 // associated m= section in description either doesn't contain a single
7407 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7408 // m= section, or the MSID values themselves, differ from what is in
7409 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7410 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7411 if (current_local_media_description->streams().size() == 0)
7412 return true;
7413
7414 std::vector<std::string> msection_msids;
7415 for (const auto& stream : current_local_media_description->streams()) {
7416 for (const std::string& msid : stream.stream_ids())
7417 msection_msids.push_back(msid);
7418 }
7419
7420 std::vector<std::string> transceiver_msids =
7421 transceiver->sender()->stream_ids();
7422 if (msection_msids.size() != transceiver_msids.size())
7423 return true;
7424
7425 absl::c_sort(transceiver_msids);
7426 absl::c_sort(msection_msids);
7427 if (transceiver_msids != msection_msids)
7428 return true;
7429 }
7430
Henrik Boström79b69802019-07-18 11:16:56 +02007431 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007432 // associated m= section in neither connection.[[CurrentLocalDescription]]
7433 // nor connection.[[CurrentRemoteDescription]] matches
7434 // transceiver.[[Direction]], return true.
7435 if (description->GetType() == SdpType::kOffer) {
7436 if (!current_remote_description())
7437 return true;
7438
7439 if (!current_remote_msection)
7440 return true;
7441
7442 RtpTransceiverDirection current_local_direction =
7443 current_local_media_description->direction();
7444 RtpTransceiverDirection current_remote_direction =
7445 current_remote_msection->media_description()->direction();
7446 if (transceiver->direction() != current_local_direction &&
7447 transceiver->direction() !=
7448 RtpTransceiverDirectionReversed(current_remote_direction)) {
7449 return true;
7450 }
7451 }
7452
Henrik Boström79b69802019-07-18 11:16:56 +02007453 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007454 // associated m= section in the description does not match
7455 // transceiver.[[Direction]] intersected with the offered direction (as
7456 // described in [JSEP] (section 5.3.1.)), return true.
7457 if (description->GetType() == SdpType::kAnswer) {
7458 if (!remote_description())
7459 return true;
7460
7461 const ContentInfo* offered_remote_msection =
7462 FindTransceiverMSection(transceiver.get(), remote_description());
7463
7464 RtpTransceiverDirection offered_direction =
7465 offered_remote_msection
7466 ? offered_remote_msection->media_description()->direction()
7467 : RtpTransceiverDirection::kInactive;
7468
7469 if (current_local_media_description->direction() !=
7470 (RtpTransceiverDirectionIntersection(
7471 transceiver->direction(),
7472 RtpTransceiverDirectionReversed(offered_direction)))) {
7473 return true;
7474 }
7475 }
7476 }
7477
7478 // If all the preceding checks were performed and true was not returned,
7479 // nothing remains to be negotiated; return false.
7480 return false;
7481}
7482
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007483} // namespace webrtc