blob: 09ba63dc333aa6813be310e5ba75b84e2b4ba71b [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 Mellem4c858282019-08-28 15:10:08 -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 Mellem4c858282019-08-28 15:10:08 -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 Mellem4c858282019-08-28 15:10:08 -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
deadbeef293e9262017-01-11 12:28:30 -08003466bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3467 RTCError* error) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003468 RTCError result = SetConfiguration(configuration);
3469 bool success = result.ok();
3470 if (error) {
3471 *error = std::move(result);
3472 }
3473 return success;
3474}
3475
3476RTCError PeerConnection::SetConfiguration(
3477 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003478 RTC_DCHECK_RUN_ON(signaling_thread());
3479 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003480 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003481 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003482 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3483 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003484 }
3485
Qingsi Wanga2d60672018-04-11 16:57:45 -07003486 // According to JSEP, after setLocalDescription, changing the candidate pool
3487 // size is not allowed, and changing the set of ICE servers will not result
3488 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003489 if (local_description() && configuration.ice_candidate_pool_size !=
3490 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003491 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3492 "Can't change candidate pool size after calling "
3493 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003494 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003495
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003496 if (local_description() &&
3497 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3499 "Can't change media_transport after calling "
3500 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003501 }
3502
3503 if (remote_description() &&
3504 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3506 "Can't change media_transport after calling "
3507 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003508 }
3509
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003510 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003511 configuration.use_media_transport_for_data_channels !=
3512 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3514 "Can't change media_transport_for_data_channels "
3515 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003516 }
3517
3518 if (remote_description() &&
3519 configuration.use_media_transport_for_data_channels !=
3520 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003521 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3522 "Can't change media_transport_for_data_channels "
3523 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003524 }
3525
3526 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003527 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003528 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3529 "Can't change crypto_options after calling "
3530 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003531 }
3532
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003533 if (local_description() && configuration.use_datagram_transport !=
3534 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003535 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3536 "Can't change use_datagram_transport "
3537 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003538 }
3539
3540 if (remote_description() && configuration.use_datagram_transport !=
3541 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003542 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3543 "Can't change use_datagram_transport "
3544 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003545 }
3546
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003547 if (local_description() &&
3548 configuration.use_datagram_transport_for_data_channels !=
3549 configuration_.use_datagram_transport_for_data_channels) {
3550 LOG_AND_RETURN_ERROR(
3551 RTCErrorType::INVALID_MODIFICATION,
3552 "Can't change use_datagram_transport_for_data_channels "
3553 "after calling SetLocalDescription.");
3554 }
3555
3556 if (remote_description() &&
3557 configuration.use_datagram_transport_for_data_channels !=
3558 configuration_.use_datagram_transport_for_data_channels) {
3559 LOG_AND_RETURN_ERROR(
3560 RTCErrorType::INVALID_MODIFICATION,
3561 "Can't change use_datagram_transport_for_data_channels "
3562 "after calling SetRemoteDescription.");
3563 }
3564
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003565 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003566 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003567 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003568 *configuration.use_datagram_transport) ||
3569 (configuration.use_datagram_transport_for_data_channels &&
3570 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003571 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3572 << "Media transport requires MaxBundle policy.";
3573 }
3574
deadbeef293e9262017-01-11 12:28:30 -08003575 // The simplest (and most future-compatible) way to tell if the config was
3576 // modified in an invalid way is to copy each property we do support
3577 // modifying, then use operator==. There are far more properties we don't
3578 // support modifying than those we do, and more could be added.
3579 RTCConfiguration modified_config = configuration_;
3580 modified_config.servers = configuration.servers;
3581 modified_config.type = configuration.type;
3582 modified_config.ice_candidate_pool_size =
3583 configuration.ice_candidate_pool_size;
3584 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003585 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3586 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003587 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003588 modified_config.ice_check_interval_strong_connectivity =
3589 configuration.ice_check_interval_strong_connectivity;
3590 modified_config.ice_check_interval_weak_connectivity =
3591 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003592 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3593 modified_config.ice_unwritable_min_checks =
3594 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003595 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003596 modified_config.stun_candidate_keepalive_interval =
3597 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003598 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003599 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003600 modified_config.active_reset_srtp_params =
3601 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003602 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003603 modified_config.use_media_transport_for_data_channels =
3604 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003605 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003606 modified_config.use_datagram_transport_for_data_channels =
3607 configuration.use_datagram_transport_for_data_channels;
Jonas Oreland3c028422019-08-22 16:16:35 +02003608 modified_config.turn_logging_id = configuration.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -08003609 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003610 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3611 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003612 }
3613
Steve Anton038834f2017-07-14 15:59:59 -07003614 // Validate the modified configuration.
3615 RTCError validate_error = ValidateConfiguration(modified_config);
3616 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003617 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003618 }
3619
deadbeef293e9262017-01-11 12:28:30 -08003620 // Note that this isn't possible through chromium, since it's an unsigned
3621 // short in WebIDL.
3622 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003623 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003624 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003625 }
3626
3627 // Parse ICE servers before hopping to network thread.
3628 cricket::ServerAddresses stun_servers;
3629 std::vector<cricket::RelayServerConfig> turn_servers;
3630 RTCErrorType parse_error =
3631 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3632 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003633 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003634 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003635 // Add the turn logging id to all turn servers
3636 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3637 turn_server.turn_logging_id = configuration.turn_logging_id;
3638 }
3639
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003640 // Note if STUN or TURN servers were supplied.
3641 if (!stun_servers.empty()) {
3642 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3643 }
3644 if (!turn_servers.empty()) {
3645 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3646 }
deadbeef293e9262017-01-11 12:28:30 -08003647
3648 // In theory this shouldn't fail.
3649 if (!network_thread()->Invoke<bool>(
3650 RTC_FROM_HERE,
3651 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3652 stun_servers, turn_servers, modified_config.type,
3653 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003654 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003655 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003656 modified_config.stun_candidate_keepalive_interval,
3657 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003658 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3659 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003660 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003661
deadbeefd1a38b52016-12-10 13:15:33 -08003662 // As described in JSEP, calling setConfiguration with new ICE servers or
3663 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3664 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003665 if (modified_config.servers != configuration_.servers ||
3666 modified_config.type != configuration_.type ||
3667 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003668 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003669 }
skvladd1f5fda2017-02-03 16:54:05 -08003670
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003671 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003672
3673 use_datagram_transport_ = datagram_transport_config_.enabled &&
3674 modified_config.use_datagram_transport.value_or(
3675 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003676 use_datagram_transport_for_data_channels_ =
3677 datagram_transport_data_channel_config_.enabled &&
3678 modified_config.use_datagram_transport_for_data_channels.value_or(
3679 datagram_transport_data_channel_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003680 transport_controller_->SetMediaTransportSettings(
3681 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003682 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003683 use_datagram_transport_, use_datagram_transport_for_data_channels_);
skvladd1f5fda2017-02-03 16:54:05 -08003684
Zhi Huangb57e1692018-06-12 11:41:11 -07003685 if (configuration_.active_reset_srtp_params !=
3686 modified_config.active_reset_srtp_params) {
3687 transport_controller_->SetActiveResetSrtpParams(
3688 modified_config.active_reset_srtp_params);
3689 }
3690
deadbeef293e9262017-01-11 12:28:30 -08003691 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003692 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003693 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003694}
3695
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003696bool PeerConnection::AddIceCandidate(
3697 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003698 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003699 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003700 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003701 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003702 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003703 return false;
3704 }
Steve Antond25da372017-11-06 14:50:29 -08003705
3706 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003707 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003708 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003709 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003710 return false;
3711 }
3712
3713 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003714 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003715 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003716 return false;
3717 }
3718
3719 bool valid = false;
3720 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3721 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003722 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003723 return false;
3724 }
3725
3726 // Add this candidate to the remote session description.
3727 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003728 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003729 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003730 return false;
3731 }
3732
3733 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003734 bool result = UseCandidate(ice_candidate);
3735 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003736 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003737 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3738 } else {
3739 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3740 }
3741 return result;
Steve Antond25da372017-11-06 14:50:29 -08003742 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003743 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003744 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003745 return true;
3746 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003747}
3748
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003749bool PeerConnection::RemoveIceCandidates(
3750 const std::vector<cricket::Candidate>& candidates) {
3751 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003752 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003753 if (IsClosed()) {
3754 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3755 return false;
3756 }
3757
Steve Antond25da372017-11-06 14:50:29 -08003758 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003759 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3760 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003761 return false;
3762 }
3763
3764 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003765 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003766 return false;
3767 }
3768
3769 size_t number_removed =
3770 mutable_remote_description()->RemoveCandidates(candidates);
3771 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003772 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003773 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003774 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003775 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003776 }
3777
3778 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003779 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3780 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003781 RTC_LOG(LS_ERROR)
3782 << "RemoveIceCandidates: Error when removing remote candidates: "
3783 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003784 }
3785 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003786}
3787
Niels Möller0c4f7be2018-05-07 14:01:37 +02003788RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003789 if (!worker_thread()->IsCurrent()) {
3790 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003791 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003792 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003793 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003794
Niels Möller0c4f7be2018-05-07 14:01:37 +02003795 const bool has_min = bitrate.min_bitrate_bps.has_value();
3796 const bool has_start = bitrate.start_bitrate_bps.has_value();
3797 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003798 if (has_min && *bitrate.min_bitrate_bps < 0) {
3799 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3800 "min_bitrate_bps <= 0");
3801 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003802 if (has_start) {
3803 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003804 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003805 "start_bitrate_bps < min_bitrate_bps");
3806 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003807 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3808 "curent_bitrate_bps < 0");
3809 }
3810 }
3811 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003812 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003813 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003814 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003815 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3816 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3817 "max_bitrate_bps < min_bitrate_bps");
3818 } else if (*bitrate.max_bitrate_bps < 0) {
3819 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3820 "max_bitrate_bps < 0");
3821 }
3822 }
3823
zstein4b979802017-06-02 14:37:37 -07003824 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003825 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003826
3827 return RTCError::OK();
3828}
3829
henrika5f6bf242017-11-01 11:06:56 +01003830void PeerConnection::SetAudioPlayout(bool playout) {
3831 if (!worker_thread()->IsCurrent()) {
3832 worker_thread()->Invoke<void>(
3833 RTC_FROM_HERE,
3834 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3835 return;
3836 }
3837 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003838 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003839 audio_state->SetPlayout(playout);
3840}
3841
3842void PeerConnection::SetAudioRecording(bool recording) {
3843 if (!worker_thread()->IsCurrent()) {
3844 worker_thread()->Invoke<void>(
3845 RTC_FROM_HERE,
3846 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3847 return;
3848 }
3849 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003850 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003851 audio_state->SetRecording(recording);
3852}
3853
Steve Anton8c0f7a72017-10-03 10:03:10 -07003854std::unique_ptr<rtc::SSLCertificate>
3855PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003856 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3857 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003858 return nullptr;
3859 }
Steve Antonf25303e2018-10-16 15:23:31 -07003860 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003861}
3862
Zhi Huang70b820f2018-01-27 14:16:15 -08003863std::unique_ptr<rtc::SSLCertChain>
3864PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003865 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003866 auto audio_transceiver = GetFirstAudioTransceiver();
3867 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003868 return nullptr;
3869 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003870 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003871 audio_transceiver->internal()->channel()->transport_name());
3872}
3873
3874rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3875PeerConnection::GetFirstAudioTransceiver() const {
3876 for (auto transceiver : transceivers_) {
3877 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3878 return transceiver;
3879 }
3880 }
3881 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003882}
3883
Bjorn Tereliusde939432017-11-20 17:38:14 +01003884bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3885 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003886 // TODO(eladalon): In C++14, this can be done with a lambda.
3887 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003888 bool operator()() {
3889 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3890 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003891 PeerConnection* const pc;
3892 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003893 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003894 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003895 return worker_thread()->Invoke<bool>(
3896 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003897}
3898
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003899bool PeerConnection::StartRtcEventLog(
3900 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003901 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3902 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3903 output_period_ms = 5000;
3904 }
3905 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003906}
3907
ivoc14d5dbe2016-07-04 07:06:55 -07003908void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003909 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003910 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3911}
3912
Harald Alvestrandad88c882018-11-28 16:47:46 +01003913rtc::scoped_refptr<DtlsTransportInterface>
3914PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003915 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003916 return transport_controller_->LookupDtlsTransportByMid(mid);
3917}
3918
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003919rtc::scoped_refptr<DtlsTransport>
3920PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003921 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003922 return transport_controller_->LookupDtlsTransportByMid(mid);
3923}
3924
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003925rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3926 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003927 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem4c858282019-08-28 15:10:08 -07003928 if (!sctp_mid_) {
3929 return nullptr;
3930 }
3931 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003932}
3933
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003934const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003935 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003936 return pending_local_description_ ? pending_local_description_.get()
3937 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003938}
3939
3940const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003941 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003942 return pending_remote_description_ ? pending_remote_description_.get()
3943 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003944}
3945
deadbeeffe4a8a42016-12-20 17:56:17 -08003946const SessionDescriptionInterface* PeerConnection::current_local_description()
3947 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003948 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003949 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003950}
3951
3952const SessionDescriptionInterface* PeerConnection::current_remote_description()
3953 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003954 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003955 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003956}
3957
3958const SessionDescriptionInterface* PeerConnection::pending_local_description()
3959 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003960 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003961 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003962}
3963
3964const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3965 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003966 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003967 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003968}
3969
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003970void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003971 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003972 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003973 // Update stats here so that we have the most recent stats for tracks and
3974 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003975 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003976
Steve Anton75737c02017-11-06 10:37:17 -08003977 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003978 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003979
Mirko Bonadei739baf02019-01-27 17:29:42 +01003980 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003981 transceiver->Stop();
3982 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003983
3984 // Ensure that all asynchronous stats requests are completed before destroying
3985 // the transport controller below.
3986 if (stats_collector_) {
3987 stats_collector_->WaitForPendingRequest();
3988 }
3989
3990 // Don't destroy BaseChannels until after stats has been cleaned up so that
3991 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003992 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003993
Qingsi Wang93a84392018-01-30 17:13:09 -08003994 // The event log is used in the transport controller, which must be outlived
3995 // by the former. CreateOffer by the peer connection is implemented
3996 // asynchronously and if the peer connection is closed without resetting the
3997 // WebRTC session description factory, the session description factory would
3998 // call the transport controller.
3999 webrtc_session_desc_factory_.reset();
4000 transport_controller_.reset();
4001
deadbeef42a42632017-03-10 15:18:00 -08004002 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004003 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4004 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004005
Steve Anton978b8762017-09-29 12:15:02 -07004006 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004007 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004008 call_.reset();
4009 // The event log must outlive call (and any other object that uses it).
4010 event_log_.reset();
4011 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004012 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004013 // The .h file says that observer can be discarded after close() returns.
4014 // Make sure this is true.
4015 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004016}
4017
Steve Antonad182762018-09-05 20:22:40 +00004018void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004019 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004020 switch (msg->message_id) {
4021 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4022 SetSessionDescriptionMsg* param =
4023 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4024 param->observer->OnSuccess();
4025 delete param;
4026 break;
4027 }
4028 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4029 SetSessionDescriptionMsg* param =
4030 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4031 param->observer->OnFailure(std::move(param->error));
4032 delete param;
4033 break;
4034 }
4035 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4036 CreateSessionDescriptionMsg* param =
4037 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4038 param->observer->OnFailure(std::move(param->error));
4039 delete param;
4040 break;
4041 }
4042 case MSG_GETSTATS: {
4043 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4044 StatsReports reports;
4045 stats_->GetStats(param->track, &reports);
4046 param->observer->OnComplete(reports);
4047 delete param;
4048 break;
4049 }
4050 case MSG_FREE_DATACHANNELS: {
4051 sctp_data_channels_to_free_.clear();
4052 break;
4053 }
4054 case MSG_REPORT_USAGE_PATTERN: {
4055 ReportUsagePattern();
4056 break;
4057 }
4058 default:
4059 RTC_NOTREACHED() << "Not implemented";
4060 break;
4061 }
4062}
4063
Steve Antonafb0bb72018-02-20 11:35:37 -08004064cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4065 RTC_DCHECK(!IsUnifiedPlan());
4066 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4067 GetAudioTransceiver()->internal()->channel());
4068 if (voice_channel) {
4069 return voice_channel->media_channel();
4070 } else {
4071 return nullptr;
4072 }
4073}
4074
4075cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4076 RTC_DCHECK(!IsUnifiedPlan());
4077 auto* video_channel = static_cast<cricket::VideoChannel*>(
4078 GetVideoTransceiver()->internal()->channel());
4079 if (video_channel) {
4080 return video_channel->media_channel();
4081 } else {
4082 return nullptr;
4083 }
4084}
4085
Steve Anton4171afb2017-11-20 10:20:22 -08004086void PeerConnection::CreateAudioReceiver(
4087 MediaStreamInterface* stream,
4088 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004089 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4090 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004091 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4092 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004093 auto* audio_receiver = new AudioRtpReceiver(
4094 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004095 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004096 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4097 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4098 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004099 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004100 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004101 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004102}
4103
Steve Anton4171afb2017-11-20 10:20:22 -08004104void PeerConnection::CreateVideoReceiver(
4105 MediaStreamInterface* stream,
4106 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004107 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4108 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004109 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4110 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004111 auto* video_receiver = new VideoRtpReceiver(
4112 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004113 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004114 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4115 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4116 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004117 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004118 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004119 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004120}
4121
deadbeef70ab1a12015-09-28 16:53:55 -07004122// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4123// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004124rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004125 const RtpSenderInfo& remote_sender_info) {
4126 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4127 if (!receiver) {
4128 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4129 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004130 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004131 }
Steve Anton4171afb2017-11-20 10:20:22 -08004132 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4133 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4134 } else {
4135 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4136 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004137 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004138}
4139
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004140void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4141 MediaStreamInterface* stream) {
4142 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004143 RTC_DCHECK(track);
4144 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004145 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004146 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004147 // We already have a sender for this track, so just change the stream_id
4148 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004149 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004150 return;
4151 }
4152
4153 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004154 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004155 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004156 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004157 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004158 // If the sender has already been configured in SDP, we call SetSsrc,
4159 // which will connect the sender to the underlying transport. This can
4160 // occur if a local session description that contains the ID of the sender
4161 // is set before AddStream is called. It can also occur if the local
4162 // session description is not changed and RemoveStream is called, and
4163 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004164 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004165 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004166 if (sender_info) {
4167 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004168 }
4169}
4170
4171// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4172// indefinitely, when we have unified plan SDP.
4173void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4174 MediaStreamInterface* stream) {
4175 RTC_DCHECK(!IsClosed());
4176 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004177 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004178 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4179 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004180 return;
4181 }
Steve Anton4171afb2017-11-20 10:20:22 -08004182 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004183}
4184
4185void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4186 MediaStreamInterface* stream) {
4187 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004188 RTC_DCHECK(track);
4189 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004190 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004191 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004192 // We already have a sender for this track, so just change the stream_id
4193 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004194 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004195 return;
4196 }
4197
4198 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004199 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004200 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004201 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004202 GetVideoTransceiver()->internal()->AddSender(new_sender);
4203 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004204 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004205 if (sender_info) {
4206 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004207 }
4208}
4209
4210void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4211 MediaStreamInterface* stream) {
4212 RTC_DCHECK(!IsClosed());
4213 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004214 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004215 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4216 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004217 return;
4218 }
Steve Anton4171afb2017-11-20 10:20:22 -08004219 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004220}
4221
Steve Antonba818672017-11-06 10:21:57 -08004222void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004223 if (ice_connection_state_ == new_state) {
4224 return;
4225 }
4226
deadbeefcbecd352015-09-23 11:50:27 -07004227 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004228 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004229 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004230 return;
4231 }
Steve Antonba818672017-11-06 10:21:57 -08004232
Mirko Bonadei675513b2017-11-09 11:09:25 +01004233 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4234 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004235 RTC_DCHECK(ice_connection_state_ !=
4236 PeerConnectionInterface::kIceConnectionClosed);
4237
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004238 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004239 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004240}
4241
Alex Loiko9289eda2018-11-23 16:18:59 +00004242void PeerConnection::SetStandardizedIceConnectionState(
4243 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004244 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004245 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004246 }
4247
4248 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004249 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004250 }
4251
4252 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4253 << standardized_ice_connection_state_ << " => " << new_state;
4254
Alex Loiko9289eda2018-11-23 16:18:59 +00004255 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004256 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004257}
4258
Jonas Olsson635474e2018-10-18 15:58:17 +02004259void PeerConnection::SetConnectionState(
4260 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004261 if (connection_state_ == new_state)
4262 return;
4263 if (IsClosed())
4264 return;
4265 connection_state_ = new_state;
4266 Observer()->OnConnectionChange(new_state);
4267}
4268
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004269void PeerConnection::OnIceGatheringChange(
4270 PeerConnectionInterface::IceGatheringState new_state) {
4271 if (IsClosed()) {
4272 return;
4273 }
4274 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004275 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004276}
4277
jbauch81bf7b02017-03-25 08:31:12 -07004278void PeerConnection::OnIceCandidate(
4279 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004280 if (IsClosed()) {
4281 return;
4282 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004283 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004284 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004285}
4286
Eldar Relloda13ea22019-06-01 12:23:43 +03004287void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4288 const std::string& url,
4289 int error_code,
4290 const std::string& error_text) {
4291 if (IsClosed()) {
4292 return;
4293 }
4294 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4295}
4296
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004297void PeerConnection::OnIceCandidatesRemoved(
4298 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004299 if (IsClosed()) {
4300 return;
4301 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004302 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004303}
4304
Alex Drake00c7ecf2019-08-06 10:54:47 -07004305void PeerConnection::OnSelectedCandidatePairChanged(
4306 const cricket::CandidatePairChangeEvent& event) {
4307 if (IsClosed()) {
4308 return;
4309 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004310
Alex Drake00c7ecf2019-08-06 10:54:47 -07004311 Observer()->OnIceSelectedCandidatePairChanged(event);
4312}
4313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004314void PeerConnection::ChangeSignalingState(
4315 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004316 if (signaling_state_ == signaling_state) {
4317 return;
4318 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004319 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4320 << GetSignalingStateString(signaling_state_)
4321 << " New state: "
4322 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004323 signaling_state_ = signaling_state;
4324 if (signaling_state == kClosed) {
4325 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004326 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004327 standardized_ice_connection_state_ =
4328 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004329 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4330 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004331 if (ice_gathering_state_ != kIceGatheringComplete) {
4332 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004333 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004334 }
4335 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004336 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004337}
4338
deadbeefeb459812015-12-15 19:24:43 -08004339void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4340 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004341 if (IsClosed()) {
4342 return;
4343 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004344 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004345 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004346}
4347
deadbeefeb459812015-12-15 19:24:43 -08004348void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4349 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004350 if (IsClosed()) {
4351 return;
4352 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004353 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004354 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004355}
4356
4357void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4358 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004359 if (IsClosed()) {
4360 return;
4361 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004362 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004363 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004364}
4365
4366void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4367 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004368 if (IsClosed()) {
4369 return;
4370 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004371 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004372 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004373}
4374
Henrik Boström31638672017-11-23 17:48:32 +01004375void PeerConnection::PostSetSessionDescriptionSuccess(
4376 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004377 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4378 signaling_thread()->Post(RTC_FROM_HERE, this,
4379 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004380}
4381
deadbeefab9b2d12015-10-14 11:33:11 -07004382void PeerConnection::PostSetSessionDescriptionFailure(
4383 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004384 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004385 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004386 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4387 msg->error = std::move(error);
4388 signaling_thread()->Post(RTC_FROM_HERE, this,
4389 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004390}
4391
4392void PeerConnection::PostCreateSessionDescriptionFailure(
4393 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004394 RTCError error) {
4395 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004396 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4397 msg->error = std::move(error);
4398 signaling_thread()->Post(RTC_FROM_HERE, this,
4399 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004400}
4401
zhihuang1c378ed2017-08-17 14:10:50 -07004402void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004403 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004404 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004405 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004406
Steve Antondcc3c022017-12-22 16:02:54 -08004407 if (IsUnifiedPlan()) {
4408 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4409 } else {
4410 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4411 }
4412
Steve Antonfa2260d2017-12-28 16:38:23 -08004413 // Intentionally unset the data channel type for RTP data channel with the
4414 // second condition. Otherwise the RTP data channels would be successfully
4415 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4416 // when building with chromium. We want to leave RTP data channels broken, so
4417 // people won't try to use them.
4418 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4419 session_options->data_channel_type = data_channel_type();
4420 }
4421
Steve Antondcc3c022017-12-22 16:02:54 -08004422 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004423 bool ice_restart = offer_answer_options.ice_restart ||
4424 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004425 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004426 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004427 options.transport_options.enable_ice_renomination =
4428 configuration_.enable_ice_renomination;
4429 }
4430
4431 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004432 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004433 session_options->pooled_ice_credentials =
4434 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4435 RTC_FROM_HERE,
4436 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4437 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004438 session_options->offer_extmap_allow_mixed =
4439 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004440
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004441 if (configuration_.use_media_transport ||
4442 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004443 session_options->media_transport_settings =
4444 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4445 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004446
4447 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004448 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004449 for (auto& options : session_options->media_description_options) {
4450 options.transport_options.opaque_parameters =
4451 transport_controller_->GetTransportParameters(options.mid);
4452 }
4453 }
4454
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004455 // Allow fallback for using obsolete SCTP syntax.
4456 // Note that the default in |session_options| is true, while
4457 // the default in |options| is false.
4458 session_options->use_obsolete_sctp_sdp =
4459 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004460}
4461
4462void PeerConnection::GetOptionsForPlanBOffer(
4463 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4464 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004465 // Figure out transceiver directional preferences.
4466 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4467 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4468
4469 // By default, generate sendrecv/recvonly m= sections.
4470 bool recv_audio = true;
4471 bool recv_video = true;
4472
4473 // By default, only offer a new m= section if we have media to send with it.
4474 bool offer_new_audio_description = send_audio;
4475 bool offer_new_video_description = send_video;
4476 bool offer_new_data_description = HasDataChannels();
4477
4478 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004479 if (offer_answer_options.offer_to_receive_audio !=
4480 RTCOfferAnswerOptions::kUndefined) {
4481 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004482 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004483 offer_new_audio_description ||
4484 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004485 }
Steve Antondcc3c022017-12-22 16:02:54 -08004486 if (offer_answer_options.offer_to_receive_video !=
4487 RTCOfferAnswerOptions::kUndefined) {
4488 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004489 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004490 offer_new_video_description ||
4491 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004492 }
4493
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004494 absl::optional<size_t> audio_index;
4495 absl::optional<size_t> video_index;
4496 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004497 // If a current description exists, generate m= sections in the same order,
4498 // using the first audio/video/data section that appears and rejecting
4499 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004500 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004501 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004502 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004503 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4504 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4505 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004506 }
4507
zhihuang1c378ed2017-08-17 14:10:50 -07004508 // Add audio/video/data m= sections to the end if needed.
4509 if (!audio_index && offer_new_audio_description) {
4510 session_options->media_description_options.push_back(
4511 cricket::MediaDescriptionOptions(
4512 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004513 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4514 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004515 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004516 }
zhihuang1c378ed2017-08-17 14:10:50 -07004517 if (!video_index && offer_new_video_description) {
4518 session_options->media_description_options.push_back(
4519 cricket::MediaDescriptionOptions(
4520 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004521 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4522 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004523 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004524 }
zhihuang1c378ed2017-08-17 14:10:50 -07004525 if (!data_index && offer_new_data_description) {
4526 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004527 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004528 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004529 }
4530
4531 cricket::MediaDescriptionOptions* audio_media_description_options =
4532 !audio_index ? nullptr
4533 : &session_options->media_description_options[*audio_index];
4534 cricket::MediaDescriptionOptions* video_media_description_options =
4535 !video_index ? nullptr
4536 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004537
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004538 AddPlanBRtpSenderOptions(GetSendersInternal(),
4539 audio_media_description_options,
4540 video_media_description_options,
4541 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004542}
4543
Steve Antondcc3c022017-12-22 16:02:54 -08004544static cricket::MediaDescriptionOptions
4545GetMediaDescriptionOptionsForTransceiver(
4546 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4547 transceiver,
4548 const std::string& mid) {
4549 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004550 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004551 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004552 media_description_options.codec_preferences =
4553 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004554 // This behavior is specified in JSEP. The gist is that:
4555 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4556 // sendrecv.
4557 // 2. If the MSID is included, then it must be included in any subsequent
4558 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004559 if (transceiver->stopped() ||
4560 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4561 !transceiver->internal()->has_ever_been_used_to_send())) {
4562 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004563 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004564
4565 cricket::SenderOptions sender_options;
4566 sender_options.track_id = transceiver->sender()->id();
4567 sender_options.stream_ids = transceiver->sender()->stream_ids();
4568
4569 // The following sets up RIDs and Simulcast.
4570 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004571 RtpParameters send_parameters =
4572 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004573 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4574 send_parameters.encodings.end(),
4575 [](const RtpEncodingParameters& encoding) {
4576 return !encoding.rid.empty();
4577 });
4578
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004579 std::vector<RidDescription> send_rids;
4580 SimulcastLayerList send_layers;
4581 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4582 if (encoding.rid.empty()) {
4583 continue;
4584 }
4585 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4586 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4587 }
4588
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004589 if (has_rids) {
4590 sender_options.rids = send_rids;
4591 }
4592
4593 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004594 // When RIDs are configured, we must set num_sim_layers to 0 to.
4595 // Otherwise, num_sim_layers must be 1 because either there is no
4596 // simulcast, or simulcast is acheived by munging the SDP.
4597 sender_options.num_sim_layers = has_rids ? 0 : 1;
4598 media_description_options.sender_options.push_back(sender_options);
4599
Steve Antondcc3c022017-12-22 16:02:54 -08004600 return media_description_options;
4601}
4602
Steve Anton5c72e712018-12-10 14:25:30 -08004603// Returns the ContentInfo at mline index |i|, or null if none exists.
4604static const ContentInfo* GetContentByIndex(
4605 const SessionDescriptionInterface* sdesc,
4606 size_t i) {
4607 if (!sdesc) {
4608 return nullptr;
4609 }
4610 const ContentInfos& contents = sdesc->description()->contents();
4611 return (i < contents.size() ? &contents[i] : nullptr);
4612}
4613
Steve Antondcc3c022017-12-22 16:02:54 -08004614void PeerConnection::GetOptionsForUnifiedPlanOffer(
4615 const RTCOfferAnswerOptions& offer_answer_options,
4616 cricket::MediaSessionOptions* session_options) {
4617 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4618 // Offers) and 5.2.2 (Subsequent Offers).
4619 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004620 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004621 const ContentInfos& local_contents =
4622 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004623 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004624 const ContentInfos& remote_contents =
4625 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004626 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004627 // The mline indices that can be recycled. New transceivers should reuse these
4628 // slots first.
4629 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004630 // First, go through each media section that exists in either the local or
4631 // remote description and generate a media section in this offer for the
4632 // associated transceiver. If a media section can be recycled, generate a
4633 // default, rejected media section here that can be later overwritten.
4634 for (size_t i = 0;
4635 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4636 // Either |local_content| or |remote_content| is non-null.
4637 const ContentInfo* local_content =
4638 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004639 const ContentInfo* current_local_content =
4640 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004641 const ContentInfo* remote_content =
4642 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004643 const ContentInfo* current_remote_content =
4644 GetContentByIndex(current_remote_description(), i);
4645 bool had_been_rejected =
4646 (current_local_content && current_local_content->rejected) ||
4647 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004648 const std::string& mid =
4649 (local_content ? local_content->name : remote_content->name);
4650 cricket::MediaType media_type =
4651 (local_content ? local_content->media_description()->type()
4652 : remote_content->media_description()->type());
4653 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4654 media_type == cricket::MEDIA_TYPE_VIDEO) {
4655 auto transceiver = GetAssociatedTransceiver(mid);
4656 RTC_CHECK(transceiver);
4657 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004658 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004659 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004660 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004661 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4662 RtpTransceiverDirection::kInactive,
4663 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004664 recycleable_mline_indices.push(i);
4665 } else {
4666 session_options->media_description_options.push_back(
4667 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4668 // CreateOffer shouldn't really cause any state changes in
4669 // PeerConnection, but we need a way to match new transceivers to new
4670 // media sections in SetLocalDescription and JSEP specifies this is done
4671 // by recording the index of the media section generated for the
4672 // transceiver in the offer.
4673 transceiver->internal()->set_mline_index(i);
4674 }
4675 } else {
4676 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004677 RTC_CHECK(GetDataMid());
4678 if (had_been_rejected || mid != *GetDataMid()) {
4679 session_options->media_description_options.push_back(
4680 GetMediaDescriptionOptionsForRejectedData(mid));
4681 } else {
4682 session_options->media_description_options.push_back(
4683 GetMediaDescriptionOptionsForActiveData(mid));
4684 }
Steve Antondcc3c022017-12-22 16:02:54 -08004685 }
4686 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004687
Steve Antondcc3c022017-12-22 16:02:54 -08004688 // Next, look for transceivers that are newly added (that is, are not stopped
4689 // and not associated). Reuse media sections marked as recyclable first,
4690 // otherwise append to the end of the offer. New media sections should be
4691 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004692 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004693 if (transceiver->mid() || transceiver->stopped()) {
4694 continue;
4695 }
4696 size_t mline_index;
4697 if (!recycleable_mline_indices.empty()) {
4698 mline_index = recycleable_mline_indices.front();
4699 recycleable_mline_indices.pop();
4700 session_options->media_description_options[mline_index] =
4701 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004702 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004703 } else {
4704 mline_index = session_options->media_description_options.size();
4705 session_options->media_description_options.push_back(
4706 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004707 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004708 }
4709 // See comment above for why CreateOffer changes the transceiver's state.
4710 transceiver->internal()->set_mline_index(mline_index);
4711 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004712 // Lastly, add a m-section if we have local data channels and an m section
4713 // does not already exist.
4714 if (!GetDataMid() && HasDataChannels()) {
4715 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004716 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004717 }
Steve Antondcc3c022017-12-22 16:02:54 -08004718}
4719
4720void PeerConnection::GetOptionsForAnswer(
4721 const RTCOfferAnswerOptions& offer_answer_options,
4722 cricket::MediaSessionOptions* session_options) {
4723 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4724
4725 if (IsUnifiedPlan()) {
4726 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4727 } else {
4728 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4729 }
4730
Steve Antonfa2260d2017-12-28 16:38:23 -08004731 // Intentionally unset the data channel type for RTP data channel. Otherwise
4732 // the RTP data channels would be successfully negotiated by default and the
4733 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4734 // We want to leave RTP data channels broken, so people won't try to use them.
4735 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4736 session_options->data_channel_type = data_channel_type();
4737 }
4738
Steve Antondcc3c022017-12-22 16:02:54 -08004739 // Apply ICE renomination flag.
4740 for (auto& options : session_options->media_description_options) {
4741 options.transport_options.enable_ice_renomination =
4742 configuration_.enable_ice_renomination;
4743 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004744
4745 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004746 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004747 session_options->pooled_ice_credentials =
4748 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4749 RTC_FROM_HERE,
4750 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4751 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004752
4753 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004754 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004755 for (auto& options : session_options->media_description_options) {
4756 options.transport_options.opaque_parameters =
4757 transport_controller_->GetTransportParameters(options.mid);
4758 }
4759 }
deadbeefab9b2d12015-10-14 11:33:11 -07004760}
4761
Steve Antondcc3c022017-12-22 16:02:54 -08004762void PeerConnection::GetOptionsForPlanBAnswer(
4763 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004764 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004765 // Figure out transceiver directional preferences.
4766 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4767 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4768
4769 // By default, generate sendrecv/recvonly m= sections. The direction is also
4770 // restricted by the direction in the offer.
4771 bool recv_audio = true;
4772 bool recv_video = true;
4773
4774 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004775 if (offer_answer_options.offer_to_receive_audio !=
4776 RTCOfferAnswerOptions::kUndefined) {
4777 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004778 }
Steve Antondcc3c022017-12-22 16:02:54 -08004779 if (offer_answer_options.offer_to_receive_video !=
4780 RTCOfferAnswerOptions::kUndefined) {
4781 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004782 }
4783
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004784 absl::optional<size_t> audio_index;
4785 absl::optional<size_t> video_index;
4786 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004787
4788 // Generate m= sections that match those in the offer.
4789 // Note that mediasession.cc will handle intersection our preferred
4790 // direction with the offered direction.
4791 GenerateMediaDescriptionOptions(
4792 remote_description(),
4793 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4794 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4795 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004796
4797 cricket::MediaDescriptionOptions* audio_media_description_options =
4798 !audio_index ? nullptr
4799 : &session_options->media_description_options[*audio_index];
4800 cricket::MediaDescriptionOptions* video_media_description_options =
4801 !video_index ? nullptr
4802 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004803
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004804 AddPlanBRtpSenderOptions(GetSendersInternal(),
4805 audio_media_description_options,
4806 video_media_description_options,
4807 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004808}
zhihuangaf388472016-11-02 16:49:48 -07004809
Steve Antondcc3c022017-12-22 16:02:54 -08004810void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4811 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4812 cricket::MediaSessionOptions* session_options) {
4813 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4814 // Answers) and 5.3.2 (Subsequent Answers).
4815 RTC_DCHECK(remote_description());
4816 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4817 for (const ContentInfo& content :
4818 remote_description()->description()->contents()) {
4819 cricket::MediaType media_type = content.media_description()->type();
4820 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4821 media_type == cricket::MEDIA_TYPE_VIDEO) {
4822 auto transceiver = GetAssociatedTransceiver(content.name);
4823 RTC_CHECK(transceiver);
4824 session_options->media_description_options.push_back(
4825 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4826 } else {
4827 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004828 // Reject all data sections if data channels are disabled.
4829 // Reject a data section if it has already been rejected.
4830 // Reject all data sections except for the first one.
4831 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4832 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004833 session_options->media_description_options.push_back(
4834 GetMediaDescriptionOptionsForRejectedData(content.name));
4835 } else {
4836 session_options->media_description_options.push_back(
4837 GetMediaDescriptionOptionsForActiveData(content.name));
4838 }
Steve Antondcc3c022017-12-22 16:02:54 -08004839 }
4840 }
htaa2a49d92016-03-04 02:51:39 -08004841}
4842
zhihuang1c378ed2017-08-17 14:10:50 -07004843void PeerConnection::GenerateMediaDescriptionOptions(
4844 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004845 RtpTransceiverDirection audio_direction,
4846 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004847 absl::optional<size_t>* audio_index,
4848 absl::optional<size_t>* video_index,
4849 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004850 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004851 for (const cricket::ContentInfo& content :
4852 session_desc->description()->contents()) {
4853 if (IsAudioContent(&content)) {
4854 // If we already have an audio m= section, reject this extra one.
4855 if (*audio_index) {
4856 session_options->media_description_options.push_back(
4857 cricket::MediaDescriptionOptions(
4858 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004859 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004860 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004861 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004862 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004863 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4864 content.name, audio_direction,
4865 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004866 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004867 }
4868 } else if (IsVideoContent(&content)) {
4869 // If we already have an video m= section, reject this extra one.
4870 if (*video_index) {
4871 session_options->media_description_options.push_back(
4872 cricket::MediaDescriptionOptions(
4873 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004874 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004875 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004876 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004877 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004878 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4879 content.name, video_direction,
4880 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004881 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004882 }
4883 } else {
4884 RTC_DCHECK(IsDataContent(&content));
4885 // If we already have an data m= section, reject this extra one.
4886 if (*data_index) {
4887 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004888 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004889 } else {
4890 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004891 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004892 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004893 }
4894 }
htaa2a49d92016-03-04 02:51:39 -08004895 }
deadbeefab9b2d12015-10-14 11:33:11 -07004896}
4897
Steve Antonfa2260d2017-12-28 16:38:23 -08004898cricket::MediaDescriptionOptions
4899PeerConnection::GetMediaDescriptionOptionsForActiveData(
4900 const std::string& mid) const {
4901 // Direction for data sections is meaningless, but legacy endpoints might
4902 // expect sendrecv.
4903 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4904 RtpTransceiverDirection::kSendRecv,
4905 /*stopped=*/false);
4906 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4907 return options;
4908}
4909
4910cricket::MediaDescriptionOptions
4911PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4912 const std::string& mid) const {
4913 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4914 RtpTransceiverDirection::kInactive,
4915 /*stopped=*/true);
4916 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4917 return options;
4918}
4919
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004920absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004921 switch (data_channel_type_) {
4922 case cricket::DCT_RTP:
4923 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004924 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004925 }
4926 return rtp_data_channel_->content_name();
4927 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004928 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004929 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
4930 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
4931 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004932 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004933 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004934 }
4935}
4936
Steve Anton4171afb2017-11-20 10:20:22 -08004937void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4938 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4939 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004940 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004941}
4942
Steve Anton4171afb2017-11-20 10:20:22 -08004943void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004944 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004945 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004946 cricket::MediaType media_type,
4947 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004948 RTC_DCHECK(!IsUnifiedPlan());
4949
Steve Anton4171afb2017-11-20 10:20:22 -08004950 std::vector<RtpSenderInfo>* current_senders =
4951 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004952
Steve Anton4171afb2017-11-20 10:20:22 -08004953 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004954 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004955 for (auto sender_it = current_senders->begin();
4956 sender_it != current_senders->end();
4957 /* incremented manually */) {
4958 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004959 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004960 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004961 std::string params_stream_id;
4962 if (params) {
4963 params_stream_id =
4964 (!params->first_stream_id().empty() ? params->first_stream_id()
4965 : kDefaultStreamId);
4966 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004967 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004968 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004969 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004970 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004971 sender_exists) {
4972 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004973 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004974 OnRemoteSenderRemoved(info, media_type);
4975 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004976 }
4977 }
4978
Steve Anton4171afb2017-11-20 10:20:22 -08004979 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004980 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004981 if (!params.has_ssrcs()) {
4982 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4983 // sender, this means it is coming from a Unified Plan endpoint,so we just
4984 // create a default.
4985 default_sender_needed = true;
4986 break;
4987 }
4988
Seth Hampson845e8782018-03-02 11:34:10 -08004989 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004990 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004991 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4992 // not supported in Plan B, we just take the first here and create the
4993 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004994 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004995 (!params.first_stream_id().empty() ? params.first_stream_id()
4996 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004997 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004998 uint32_t ssrc = params.first_ssrc();
4999
5000 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005001 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005002 if (!stream) {
5003 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005004 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005005 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005006 remote_streams_->AddStream(stream);
5007 new_streams->AddStream(stream);
5008 }
5009
Steve Anton4171afb2017-11-20 10:20:22 -08005010 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005011 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005012 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005013 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005014 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005015 }
5016 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005017
Steve Anton4171afb2017-11-20 10:20:22 -08005018 // Add default sender if necessary.
5019 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005020 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005021 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005022 if (!default_stream) {
5023 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005024 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005025 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005026 remote_streams_->AddStream(default_stream);
5027 new_streams->AddStream(default_stream);
5028 }
Steve Anton4171afb2017-11-20 10:20:22 -08005029 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5030 ? kDefaultAudioSenderId
5031 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005032 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005033 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005034 if (!default_sender_info) {
5035 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005036 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005037 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005038 }
5039 }
deadbeefab9b2d12015-10-14 11:33:11 -07005040}
5041
Steve Anton4171afb2017-11-20 10:20:22 -08005042void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5043 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005044 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5045 << " receiver for track_id=" << sender_info.sender_id
5046 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005047
Steve Anton3d954a62018-04-02 11:27:23 -07005048 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005049 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005050 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005051 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005052 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005053 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005054 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005055 }
5056}
5057
Steve Anton4171afb2017-11-20 10:20:22 -08005058void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5059 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005060 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5061 << " receiver for track_id=" << sender_info.sender_id
5062 << " and stream_id=" << sender_info.stream_id;
5063
Seth Hampson845e8782018-03-02 11:34:10 -08005064 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005065
Henrik Boström933d8b02017-10-10 10:05:16 -07005066 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005067 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005068 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5069 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005070 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005071 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005072 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005073 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005074 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005075 }
5076 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005077 // Stopping or destroying a VideoRtpReceiver will end the
5078 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005079 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005080 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005081 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005082 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005083 // There's no guarantee the track is still available, e.g. the track may
5084 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005085 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005086 }
5087 } else {
nisseede5da42017-01-12 05:15:36 -08005088 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005089 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005090 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005091 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005092 }
deadbeefab9b2d12015-10-14 11:33:11 -07005093}
5094
5095void PeerConnection::UpdateEndedRemoteMediaStreams() {
5096 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5097 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5098 MediaStreamInterface* stream = remote_streams_->at(i);
5099 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5100 streams_to_remove.push_back(stream);
5101 }
5102 }
5103
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005104 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005105 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005106 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005107 }
5108}
5109
Steve Anton4171afb2017-11-20 10:20:22 -08005110void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005111 const std::vector<cricket::StreamParams>& streams,
5112 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005113 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005114
Seth Hampson845e8782018-03-02 11:34:10 -08005115 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005116 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005117 for (auto sender_it = current_senders->begin();
5118 sender_it != current_senders->end();
5119 /* incremented manually */) {
5120 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005121 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005122 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5123 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005124 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005125 OnLocalSenderRemoved(info, media_type);
5126 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005127 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005128 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005129 }
5130 }
5131
Steve Anton4171afb2017-11-20 10:20:22 -08005132 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005133 for (const cricket::StreamParams& params : streams) {
5134 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005135 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005136 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005137 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005138 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005139 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005140 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005141 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005142 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005143 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005144 }
5145 }
5146}
5147
Steve Anton4171afb2017-11-20 10:20:22 -08005148void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5149 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005150 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005151 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005152 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005153 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5154 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005155 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005156 return;
5157 }
5158
deadbeeffac06552015-11-25 11:26:01 -08005159 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005161 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005162 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005163 }
deadbeeffac06552015-11-25 11:26:01 -08005164
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005165 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005166 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005167}
5168
Steve Anton4171afb2017-11-20 10:20:22 -08005169void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5170 cricket::MediaType media_type) {
5171 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005172 if (!sender) {
5173 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005174 // SessionDescriptions has been renegotiated.
5175 return;
5176 }
deadbeeffac06552015-11-25 11:26:01 -08005177
5178 // A sender has been removed from the SessionDescription but it's still
5179 // associated with the PeerConnection. This only occurs if the SDP doesn't
5180 // match with the calls to CreateSender, AddStream and RemoveStream.
5181 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005182 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005183 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005184 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005185 }
deadbeeffac06552015-11-25 11:26:01 -08005186
Steve Anton4171afb2017-11-20 10:20:22 -08005187 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005188}
5189
5190void PeerConnection::UpdateLocalRtpDataChannels(
5191 const cricket::StreamParamsVec& streams) {
5192 std::vector<std::string> existing_channels;
5193
5194 // Find new and active data channels.
5195 for (const cricket::StreamParams& params : streams) {
5196 // |it->sync_label| is actually the data channel label. The reason is that
5197 // we use the same naming of data channels as we do for
5198 // MediaStreams and Tracks.
5199 // For MediaStreams, the sync_label is the MediaStream label and the
5200 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005201 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005202 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005203 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005204 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005205 continue;
5206 }
5207 // Set the SSRC the data channel should use for sending.
5208 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5209 existing_channels.push_back(data_channel_it->first);
5210 }
5211
5212 UpdateClosingRtpDataChannels(existing_channels, true);
5213}
5214
5215void PeerConnection::UpdateRemoteRtpDataChannels(
5216 const cricket::StreamParamsVec& streams) {
5217 std::vector<std::string> existing_channels;
5218
5219 // Find new and active data channels.
5220 for (const cricket::StreamParams& params : streams) {
5221 // The data channel label is either the mslabel or the SSRC if the mslabel
5222 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005223 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005224 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005225 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005226 auto data_channel_it = rtp_data_channels_.find(label);
5227 if (data_channel_it == rtp_data_channels_.end()) {
5228 // This is a new data channel.
5229 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5230 } else {
5231 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5232 }
5233 existing_channels.push_back(label);
5234 }
5235
5236 UpdateClosingRtpDataChannels(existing_channels, false);
5237}
5238
5239void PeerConnection::UpdateClosingRtpDataChannels(
5240 const std::vector<std::string>& active_channels,
5241 bool is_local_update) {
5242 auto it = rtp_data_channels_.begin();
5243 while (it != rtp_data_channels_.end()) {
5244 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005245 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005246 ++it;
5247 continue;
5248 }
5249
5250 if (is_local_update) {
5251 data_channel->SetSendSsrc(0);
5252 } else {
5253 data_channel->RemotePeerRequestClose();
5254 }
5255
5256 if (data_channel->state() == DataChannel::kClosed) {
5257 rtp_data_channels_.erase(it);
5258 it = rtp_data_channels_.begin();
5259 } else {
5260 ++it;
5261 }
5262 }
5263}
5264
5265void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5266 uint32_t remote_ssrc) {
5267 rtc::scoped_refptr<DataChannel> channel(
5268 InternalCreateDataChannel(label, nullptr));
5269 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005270 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005271 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005272 return;
5273 }
5274 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005275 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5276 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005277 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005278}
5279
5280rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5281 const std::string& label,
5282 const InternalDataChannelInit* config) {
5283 if (IsClosed()) {
5284 return nullptr;
5285 }
Steve Anton75737c02017-11-06 10:37:17 -08005286 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005287 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005288 << "InternalCreateDataChannel: Data is not supported in this call.";
5289 return nullptr;
5290 }
5291 InternalDataChannelInit new_config =
5292 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005293 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005294 if (new_config.id < 0) {
5295 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005296 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005297 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005298 RTC_LOG(LS_ERROR)
5299 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005300 return nullptr;
5301 }
5302 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005303 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005304 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005305 return nullptr;
5306 }
5307 }
5308
Steve Anton75737c02017-11-06 10:37:17 -08005309 rtc::scoped_refptr<DataChannel> channel(
5310 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005311 if (!channel) {
5312 sid_allocator_.ReleaseSid(new_config.id);
5313 return nullptr;
5314 }
5315
5316 if (channel->data_channel_type() == cricket::DCT_RTP) {
5317 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005318 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5319 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005320 return nullptr;
5321 }
5322 rtp_data_channels_[channel->label()] = channel;
5323 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005324 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005325 sctp_data_channels_.push_back(channel);
5326 channel->SignalClosed.connect(this,
5327 &PeerConnection::OnSctpDataChannelClosed);
5328 }
5329
Steve Anton2d8609c2018-01-23 16:38:46 -08005330 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005331 return channel;
5332}
5333
5334bool PeerConnection::HasDataChannels() const {
5335 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5336}
5337
5338void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005339 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005340 for (const auto& channel : sctp_data_channels_) {
5341 if (channel->id() < 0) {
5342 int sid;
5343 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005344 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5345 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005346 continue;
5347 }
5348 channel->SetSctpSid(sid);
5349 }
5350 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005351 // Since closing modifies the list of channels, we have to do the actual
5352 // closing outside the loop.
5353 for (const auto& channel : channels_to_close) {
5354 channel->CloseAbruptly();
5355 }
deadbeefab9b2d12015-10-14 11:33:11 -07005356}
5357
5358void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005359 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005360 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5361 ++it) {
5362 if (it->get() == channel) {
5363 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005364 // After the closing procedure is done, it's safe to use this ID for
5365 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005366 sid_allocator_.ReleaseSid(channel->id());
5367 }
deadbeefbd292462015-12-14 18:15:29 -08005368 // Since this method is triggered by a signal from the DataChannel,
5369 // we can't free it directly here; we need to free it asynchronously.
5370 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005371 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005372 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5373 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005374 return;
5375 }
5376 }
5377}
5378
deadbeefab9b2d12015-10-14 11:33:11 -07005379void PeerConnection::OnDataChannelDestroyed() {
5380 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5381 // DataChannel may callback to us and try to modify the list.
5382 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5383 temp_rtp_dcs.swap(rtp_data_channels_);
5384 for (const auto& kv : temp_rtp_dcs) {
5385 kv.second->OnTransportChannelDestroyed();
5386 }
5387
5388 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5389 temp_sctp_dcs.swap(sctp_data_channels_);
5390 for (const auto& channel : temp_sctp_dcs) {
5391 channel->OnTransportChannelDestroyed();
5392 }
5393}
5394
5395void PeerConnection::OnDataChannelOpenMessage(
5396 const std::string& label,
5397 const InternalDataChannelInit& config) {
5398 rtc::scoped_refptr<DataChannel> channel(
5399 InternalCreateDataChannel(label, &config));
5400 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005401 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005402 return;
5403 }
5404
deadbeefa601f5c2016-06-06 14:27:39 -07005405 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5406 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005407 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005408 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005409}
5410
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005411bool PeerConnection::HandleOpenMessage_s(
5412 const cricket::ReceiveDataParams& params,
5413 const rtc::CopyOnWriteBuffer& buffer) {
5414 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5415 // Received OPEN message; parse and signal that a new data channel should
5416 // be created.
5417 std::string label;
5418 InternalDataChannelInit config;
5419 config.id = params.ssrc;
5420 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5421 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5422 << params.ssrc;
5423 return true;
5424 }
5425 config.open_handshake_role = InternalDataChannelInit::kAcker;
5426 OnDataChannelOpenMessage(label, config);
5427 return true;
5428 }
5429 return false;
5430}
5431
Steve Anton4171afb2017-11-20 10:20:22 -08005432rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5433PeerConnection::GetAudioTransceiver() const {
5434 // This method only works with Plan B SDP, where there is a single
5435 // audio/video transceiver.
5436 RTC_DCHECK(!IsUnifiedPlan());
5437 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005438 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005439 return transceiver;
5440 }
5441 }
5442 RTC_NOTREACHED();
5443 return nullptr;
5444}
5445
5446rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5447PeerConnection::GetVideoTransceiver() const {
5448 // This method only works with Plan B SDP, where there is a single
5449 // audio/video transceiver.
5450 RTC_DCHECK(!IsUnifiedPlan());
5451 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005452 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005453 return transceiver;
5454 }
5455 }
5456 RTC_NOTREACHED();
5457 return nullptr;
5458}
5459
5460// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5461// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005462bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005463 switch (type) {
5464 case cricket::MEDIA_TYPE_AUDIO:
5465 return !GetAudioTransceiver()->internal()->senders().empty();
5466 case cricket::MEDIA_TYPE_VIDEO:
5467 return !GetVideoTransceiver()->internal()->senders().empty();
5468 case cricket::MEDIA_TYPE_DATA:
5469 return false;
5470 }
5471 RTC_NOTREACHED();
5472 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005473}
5474
Steve Anton4171afb2017-11-20 10:20:22 -08005475rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5476PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005477 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005478 for (auto sender : transceiver->internal()->senders()) {
5479 if (sender->track() == track) {
5480 return sender;
5481 }
5482 }
5483 }
5484 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005485}
5486
Steve Anton4171afb2017-11-20 10:20:22 -08005487rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5488PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005489 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005490 for (auto sender : transceiver->internal()->senders()) {
5491 if (sender->id() == sender_id) {
5492 return sender;
5493 }
5494 }
5495 }
5496 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005497}
5498
Steve Anton4171afb2017-11-20 10:20:22 -08005499rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5500PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005501 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005502 for (auto receiver : transceiver->internal()->receivers()) {
5503 if (receiver->id() == receiver_id) {
5504 return receiver;
5505 }
5506 }
5507 }
5508 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005509}
5510
Steve Anton4171afb2017-11-20 10:20:22 -08005511std::vector<PeerConnection::RtpSenderInfo>*
5512PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5513 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5514 media_type == cricket::MEDIA_TYPE_VIDEO);
5515 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5516 ? &remote_audio_sender_infos_
5517 : &remote_video_sender_infos_;
5518}
5519
5520std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005521 cricket::MediaType media_type) {
5522 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5523 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005524 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5525 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005526}
5527
Steve Anton4171afb2017-11-20 10:20:22 -08005528const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5529 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005530 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005531 const std::string sender_id) const {
5532 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005533 if (sender_info.stream_id == stream_id &&
5534 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005535 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005536 }
5537 }
5538 return nullptr;
5539}
5540
5541DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5542 for (const auto& channel : sctp_data_channels_) {
5543 if (channel->id() == sid) {
5544 return channel;
5545 }
5546 }
5547 return nullptr;
5548}
5549
Karl Wibergfb3be392019-03-22 14:13:22 +01005550PeerConnection::InitializePortAllocatorResult
5551PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005552 const cricket::ServerAddresses& stun_servers,
5553 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005554 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005555 RTC_DCHECK_RUN_ON(network_thread());
5556
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005557 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005558 // To handle both internal and externally created port allocator, we will
5559 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005560 int port_allocator_flags = port_allocator_->flags();
5561 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5562 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5563 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005564 // If the disable-IPv6 flag was specified, we'll not override it
5565 // by experiment.
5566 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005567 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005568 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5569 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005570 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005571 }
5572
zhihuangb09b3f92017-03-07 14:40:51 -08005573 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005574 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005575 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005576 }
5577
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005578 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005579 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005580 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005581 }
5582
honghaiz60347052016-05-31 18:29:12 -07005583 if (configuration.candidate_network_policy ==
5584 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005585 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005586 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005587 }
5588
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005589 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005590 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005591 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5592 }
5593
Karl Wibergfb3be392019-03-22 14:13:22 +01005594 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005595 // No step delay is used while allocating ports.
5596 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005597 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005598 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005599 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005600
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005601 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005602 for (auto& turn_server : turn_servers_copy) {
5603 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005604 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005605 // Call this last since it may create pooled allocator sessions using the
5606 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005607 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005608 stun_servers, std::move(turn_servers_copy),
5609 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5610 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005611 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005612
5613 InitializePortAllocatorResult res;
5614 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5615 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005616}
5617
deadbeef91dd5672016-05-18 16:55:30 -07005618bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005619 const cricket::ServerAddresses& stun_servers,
5620 const std::vector<cricket::RelayServerConfig>& turn_servers,
5621 IceTransportsType type,
5622 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005623 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005624 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005625 absl::optional<int> stun_candidate_keepalive_interval,
5626 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005627 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005628 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005629 // According to JSEP, after setLocalDescription, changing the candidate pool
5630 // size is not allowed, and changing the set of ICE servers will not result
5631 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005632 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005633 port_allocator_->FreezeCandidatePool();
5634 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005635 // Add the custom tls turn servers if they exist.
5636 auto turn_servers_copy = turn_servers;
5637 for (auto& turn_server : turn_servers_copy) {
5638 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5639 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005640 // Call this last since it may create pooled allocator sessions using the
5641 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005642 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005643 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5644 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005645}
5646
Steve Antonba818672017-11-06 10:21:57 -08005647cricket::ChannelManager* PeerConnection::channel_manager() const {
5648 return factory_->channel_manager();
5649}
5650
Elad Alon99c3fe52017-10-13 16:29:40 +02005651bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005652 std::unique_ptr<RtcEventLogOutput> output,
5653 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005654 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005655 if (!event_log_) {
5656 return false;
5657 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005658 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005659}
5660
5661void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005662 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005663 if (event_log_) {
5664 event_log_->StopLogging();
5665 }
ivoc14d5dbe2016-07-04 07:06:55 -07005666}
nisseeaabdf62017-05-05 02:23:02 -07005667
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005668cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005669 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005670 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005671 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005672 if (channel && channel->content_name() == content_name) {
5673 return channel;
5674 }
Steve Anton75737c02017-11-06 10:37:17 -08005675 }
5676 if (rtp_data_channel() &&
5677 rtp_data_channel()->content_name() == content_name) {
5678 return rtp_data_channel();
5679 }
5680 return nullptr;
5681}
5682
5683bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005684 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005685 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005686 RTC_LOG(LS_INFO)
5687 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005688 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005689 return false;
5690 }
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005691 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005692 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005693 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005694 return false;
5695 }
5696
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005697 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005698 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005699 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005700 if (!dtls_role && is_caller_.has_value()) {
5701 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5702 }
Zhi Huange830e682018-03-30 10:48:35 -07005703 *role = *dtls_role;
5704 return true;
5705 }
5706 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005707}
5708
5709bool PeerConnection::GetSslRole(const std::string& content_name,
5710 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005711 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005712 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005713 RTC_LOG(LS_INFO)
5714 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005715 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005716 return false;
5717 }
5718
Zhi Huange830e682018-03-30 10:48:35 -07005719 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5720 if (dtls_role) {
5721 *role = *dtls_role;
5722 return true;
5723 }
5724 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005725}
5726
Steve Antonf8470812017-12-04 10:46:21 -08005727void PeerConnection::SetSessionError(SessionError error,
5728 const std::string& error_desc) {
5729 RTC_DCHECK_RUN_ON(signaling_thread());
5730 if (error != session_error_) {
5731 session_error_ = error;
5732 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005733 }
5734}
5735
Zhi Huange830e682018-03-30 10:48:35 -07005736RTCError PeerConnection::UpdateSessionState(
5737 SdpType type,
5738 cricket::ContentSource source,
5739 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005740 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005741
5742 // If there's already a pending error then no state transition should happen.
5743 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005744 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005745
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005746 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005747 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005748 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005749 }
5750
5751 // Update the signaling state according to the specified state machine (see
5752 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005753 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005754 ChangeSignalingState(source == cricket::CS_LOCAL
5755 ? PeerConnectionInterface::kHaveLocalOffer
5756 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005757 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005758 ChangeSignalingState(source == cricket::CS_LOCAL
5759 ? PeerConnectionInterface::kHaveLocalPrAnswer
5760 : PeerConnectionInterface::kHaveRemotePrAnswer);
5761 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005762 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005763 ChangeSignalingState(PeerConnectionInterface::kStable);
5764 }
5765
5766 // Update internal objects according to the session description's media
5767 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005768 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005769 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005770 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005771 }
5772
Steve Anton8a006912017-12-04 15:25:56 -08005773 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005774}
5775
Steve Anton8a006912017-12-04 15:25:56 -08005776RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005777 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005778 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005779 const SessionDescriptionInterface* sdesc =
5780 (source == cricket::CS_LOCAL ? local_description()
5781 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005782 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005783
5784 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005785 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005786 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005787 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005788 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005789 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005790 continue;
5791 }
5792 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005793 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005794 if (!content_desc) {
5795 continue;
5796 }
5797 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005798 bool success = (source == cricket::CS_LOCAL)
5799 ? channel->SetLocalContent(content_desc, type, &error)
5800 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005801 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005802 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005803 }
5804 }
5805
5806 // If using the RtpDataChannel, push down the new SDP section for it too.
5807 if (rtp_data_channel_) {
5808 const ContentInfo* data_content =
5809 cricket::GetFirstDataContent(sdesc->description());
5810 if (data_content && !data_content->rejected) {
5811 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005812 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005813 if (data_desc) {
5814 std::string error;
5815 bool success =
5816 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005817 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005818 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005819 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005820 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005821 }
Steve Anton75737c02017-11-06 10:37:17 -08005822 }
5823 }
5824 }
Steve Antoned10bd92017-12-05 10:52:59 -08005825
Steve Anton75737c02017-11-06 10:37:17 -08005826 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5827 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005828 if (sctp_mid_ && local_description() && remote_description()) {
5829 rtc::scoped_refptr<SctpTransport> sctp_transport =
5830 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005831 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5832 local_description()->description());
5833 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5834 remote_description()->description());
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005835 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005836 int max_message_size;
5837 // A remote max message size of zero means "any size supported".
5838 // We configure the connection with our own max message size.
5839 if (remote_sctp_description->max_message_size() == 0) {
5840 max_message_size = local_sctp_description->max_message_size();
5841 } else {
5842 max_message_size =
5843 std::min(local_sctp_description->max_message_size(),
5844 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005845 }
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005846 sctp_transport->Start(local_sctp_description->port(),
5847 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005848 }
Steve Anton75737c02017-11-06 10:37:17 -08005849 }
Steve Antoned10bd92017-12-05 10:52:59 -08005850
Steve Anton8a006912017-12-04 15:25:56 -08005851 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005852}
5853
Steve Anton8a006912017-12-04 15:25:56 -08005854RTCError PeerConnection::PushdownTransportDescription(
5855 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005856 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005857 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005858
Zhi Huange830e682018-03-30 10:48:35 -07005859 if (source == cricket::CS_LOCAL) {
5860 const SessionDescriptionInterface* sdesc = local_description();
5861 RTC_DCHECK(sdesc);
5862 return transport_controller_->SetLocalDescription(type,
5863 sdesc->description());
5864 } else {
5865 const SessionDescriptionInterface* sdesc = remote_description();
5866 RTC_DCHECK(sdesc);
5867 return transport_controller_->SetRemoteDescription(type,
5868 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005869 }
Steve Anton75737c02017-11-06 10:37:17 -08005870}
5871
5872bool PeerConnection::GetTransportDescription(
5873 const SessionDescription* description,
5874 const std::string& content_name,
5875 cricket::TransportDescription* tdesc) {
5876 if (!description || !tdesc) {
5877 return false;
5878 }
5879 const TransportInfo* transport_info =
5880 description->GetTransportInfoByName(content_name);
5881 if (!transport_info) {
5882 return false;
5883 }
5884 *tdesc = transport_info->description;
5885 return true;
5886}
5887
Steve Anton75737c02017-11-06 10:37:17 -08005888cricket::IceConfig PeerConnection::ParseIceConfig(
5889 const PeerConnectionInterface::RTCConfiguration& config) const {
5890 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005891 switch (config.continual_gathering_policy) {
5892 case PeerConnectionInterface::GATHER_ONCE:
5893 gathering_policy = cricket::GATHER_ONCE;
5894 break;
5895 case PeerConnectionInterface::GATHER_CONTINUALLY:
5896 gathering_policy = cricket::GATHER_CONTINUALLY;
5897 break;
5898 default:
5899 RTC_NOTREACHED();
5900 gathering_policy = cricket::GATHER_ONCE;
5901 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005902
Steve Anton75737c02017-11-06 10:37:17 -08005903 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005904 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5905 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005906 ice_config.prioritize_most_likely_candidate_pairs =
5907 config.prioritize_most_likely_ice_candidate_pairs;
5908 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005909 RTCConfigurationToIceConfigOptionalInt(
5910 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005911 ice_config.continual_gathering_policy = gathering_policy;
5912 ice_config.presume_writable_when_fully_relayed =
5913 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005914 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5915 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005916 ice_config.ice_check_interval_strong_connectivity =
5917 config.ice_check_interval_strong_connectivity;
5918 ice_config.ice_check_interval_weak_connectivity =
5919 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005920 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005921 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5922 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005923 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005924 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005925 ice_config.regather_all_networks_interval_range =
5926 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005927 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005928 return ice_config;
5929}
5930
Steve Anton75737c02017-11-06 10:37:17 -08005931bool PeerConnection::SendData(const cricket::SendDataParams& params,
5932 const rtc::CopyOnWriteBuffer& payload,
5933 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005934 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005935 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005936 SendDataParams send_params;
5937 send_params.type = ToWebrtcDataMessageType(params.type);
5938 send_params.ordered = params.ordered;
5939 if (params.max_rtx_count >= 0) {
5940 send_params.max_rtx_count = params.max_rtx_count;
5941 } else if (params.max_rtx_ms >= 0) {
5942 send_params.max_rtx_ms = params.max_rtx_ms;
5943 }
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005944
5945 RTCError error = network_thread()->Invoke<RTCError>(
5946 RTC_FROM_HERE, [this, params, send_params, payload] {
5947 return data_channel_transport_->SendData(params.sid, send_params,
5948 payload);
5949 });
5950
5951 if (error.ok()) {
5952 *result = cricket::SendDataResult::SDR_SUCCESS;
5953 return true;
5954 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
5955 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
5956 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
5957 *result = cricket::SendDataResult::SDR_BLOCK;
5958 return false;
5959 }
5960 *result = cricket::SendDataResult::SDR_ERROR;
5961 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005962 } else if (rtp_data_channel_) {
5963 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005964 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005965 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
5966 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005967}
5968
5969bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005970 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005971 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005972 // Don't log an error here, because DataChannels are expected to call
5973 // ConnectDataChannel in this state. It's the only way to initially tell
5974 // whether or not the underlying transport is ready.
5975 return false;
5976 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005977 if (data_channel_transport_) {
5978 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
5979 &DataChannel::OnChannelReady);
5980 SignalDataChannelTransportReceivedData_s.connect(
5981 webrtc_data_channel, &DataChannel::OnDataReceived);
5982 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005983 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005984 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005985 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005986 }
5987 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005988 rtp_data_channel_->SignalReadyToSendData.connect(
5989 webrtc_data_channel, &DataChannel::OnChannelReady);
5990 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5991 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005992 }
Steve Anton75737c02017-11-06 10:37:17 -08005993 return true;
5994}
5995
5996void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005997 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellem4c858282019-08-28 15:10:08 -07005998 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005999 RTC_LOG(LS_ERROR)
6000 << "DisconnectDataChannel called when rtp_data_channel_ and "
6001 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006002 return;
6003 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006004 if (data_channel_transport_) {
6005 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6006 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6007 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6008 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6009 }
6010 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006011 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6012 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006013 }
Steve Anton75737c02017-11-06 10:37:17 -08006014}
6015
6016void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006017 if (data_channel_transport_) {
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006018 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6019 if (data_channel_transport_) {
6020 data_channel_transport_->OpenChannel(sid);
6021 }
6022 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006023 }
Steve Anton75737c02017-11-06 10:37:17 -08006024}
6025
6026void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006027 if (data_channel_transport_) {
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006028 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6029 if (data_channel_transport_) {
6030 data_channel_transport_->CloseChannel(sid);
6031 }
6032 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006033 }
Steve Anton75737c02017-11-06 10:37:17 -08006034}
6035
6036bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006037 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006038 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006039 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006040}
6041
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006042void PeerConnection::OnDataReceived(int channel_id,
6043 DataMessageType type,
6044 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006045 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006046 cricket::ReceiveDataParams params;
6047 params.sid = channel_id;
6048 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006049 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006050 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6051 RTC_DCHECK_RUN_ON(signaling_thread());
6052 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006053 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006054 }
6055 });
6056}
6057
6058void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006059 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006060 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006061 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6062 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006063 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006064 });
6065}
6066
6067void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006068 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006069 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006070 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6071 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006072 SignalDataChannelTransportChannelClosed_s(channel_id);
6073 });
6074}
6075
6076void PeerConnection::OnReadyToSend() {
6077 RTC_DCHECK_RUN_ON(network_thread());
6078 data_channel_transport_invoker_->AsyncInvoke<void>(
6079 RTC_FROM_HERE, signaling_thread(), [this] {
6080 RTC_DCHECK_RUN_ON(signaling_thread());
6081 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006082 SignalDataChannelTransportWritable_s(
6083 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006084 });
6085}
6086
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006087absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006088 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006089 if (sctp_mid_ && transport_controller_) {
6090 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6091 if (dtls_transport) {
6092 return dtls_transport->transport_name();
6093 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006094 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006095 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006096 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006097}
6098
Qingsi Wang72a43a12018-02-20 16:03:18 -08006099cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6100 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006101 network_thread()->Invoke<void>(
6102 RTC_FROM_HERE,
6103 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6104 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006105 return candidate_states_list;
6106}
6107
Steve Anton5dfde182018-02-06 10:34:40 -08006108std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6109 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006110 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006111 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006112 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006113 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006114 if (channel) {
6115 transport_names_by_mid[channel->content_name()] =
6116 channel->transport_name();
6117 }
Steve Anton75737c02017-11-06 10:37:17 -08006118 }
Steve Anton5dfde182018-02-06 10:34:40 -08006119 if (rtp_data_channel_) {
6120 transport_names_by_mid[rtp_data_channel_->content_name()] =
6121 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006122 }
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006123 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006124 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006125 RTC_DCHECK(transport_name);
6126 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006127 }
Steve Anton5dfde182018-02-06 10:34:40 -08006128 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006129}
6130
Steve Anton5dfde182018-02-06 10:34:40 -08006131std::map<std::string, cricket::TransportStats>
6132PeerConnection::GetTransportStatsByNames(
6133 const std::set<std::string>& transport_names) {
6134 if (!network_thread()->IsCurrent()) {
6135 return network_thread()
6136 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6137 RTC_FROM_HERE,
6138 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006139 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006140 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006141 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6142 for (const std::string& transport_name : transport_names) {
6143 cricket::TransportStats transport_stats;
6144 bool success =
6145 transport_controller_->GetStats(transport_name, &transport_stats);
6146 if (success) {
6147 transport_stats_by_name[transport_name] = std::move(transport_stats);
6148 } else {
6149 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6150 << transport_name;
6151 }
6152 }
6153 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006154}
6155
6156bool PeerConnection::GetLocalCertificate(
6157 const std::string& transport_name,
6158 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006159 if (!certificate) {
6160 return false;
6161 }
6162 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6163 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006164}
6165
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006166std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006167 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006168 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006169}
6170
6171cricket::DataChannelType PeerConnection::data_channel_type() const {
6172 return data_channel_type_;
6173}
6174
6175bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006176 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006177 return pending_ice_restarts_.find(content_name) !=
6178 pending_ice_restarts_.end();
6179}
6180
Steve Anton75737c02017-11-06 10:37:17 -08006181bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6182 return transport_controller_->NeedsIceRestart(content_name);
6183}
6184
6185void PeerConnection::OnCertificateReady(
6186 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6187 transport_controller_->SetLocalCertificate(certificate);
6188}
6189
6190void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006191 SetSessionError(SessionError::kTransport,
6192 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006193}
6194
Alex Loiko9289eda2018-11-23 16:18:59 +00006195void PeerConnection::OnTransportControllerConnectionState(
6196 cricket::IceConnectionState state) {
6197 switch (state) {
6198 case cricket::kIceConnectionConnecting:
6199 // If the current state is Connected or Completed, then there were
6200 // writable channels but now there are not, so the next state must
6201 // be Disconnected.
6202 // kIceConnectionConnecting is currently used as the default,
6203 // un-connected state by the TransportController, so its only use is
6204 // detecting disconnections.
6205 if (ice_connection_state_ ==
6206 PeerConnectionInterface::kIceConnectionConnected ||
6207 ice_connection_state_ ==
6208 PeerConnectionInterface::kIceConnectionCompleted) {
6209 SetIceConnectionState(
6210 PeerConnectionInterface::kIceConnectionDisconnected);
6211 }
6212 break;
6213 case cricket::kIceConnectionFailed:
6214 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6215 break;
6216 case cricket::kIceConnectionConnected:
6217 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6218 "all transports are writable.";
6219 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6220 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6221 break;
6222 case cricket::kIceConnectionCompleted:
6223 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6224 "all transports are complete.";
6225 if (ice_connection_state_ !=
6226 PeerConnectionInterface::kIceConnectionConnected) {
6227 // If jumping directly from "checking" to "connected",
6228 // signal "connected" first.
6229 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6230 }
6231 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6232 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6233 ReportTransportStats();
6234 break;
6235 default:
6236 RTC_NOTREACHED();
6237 }
6238}
6239
Steve Anton75737c02017-11-06 10:37:17 -08006240void PeerConnection::OnTransportControllerCandidatesGathered(
6241 const std::string& transport_name,
6242 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006243 int sdp_mline_index;
6244 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006245 RTC_LOG(LS_ERROR)
6246 << "OnTransportControllerCandidatesGathered: content name "
6247 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006248 return;
6249 }
6250
6251 for (cricket::Candidates::const_iterator citer = candidates.begin();
6252 citer != candidates.end(); ++citer) {
6253 // Use transport_name as the candidate media id.
6254 std::unique_ptr<JsepIceCandidate> candidate(
6255 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6256 if (local_description()) {
6257 mutable_local_description()->AddCandidate(candidate.get());
6258 }
6259 OnIceCandidate(std::move(candidate));
6260 }
6261}
6262
Eldar Relloda13ea22019-06-01 12:23:43 +03006263void PeerConnection::OnTransportControllerCandidateError(
6264 const cricket::IceCandidateErrorEvent& event) {
6265 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6266 event.error_text);
6267}
6268
Steve Anton75737c02017-11-06 10:37:17 -08006269void PeerConnection::OnTransportControllerCandidatesRemoved(
6270 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006271 // Sanity check.
6272 for (const cricket::Candidate& candidate : candidates) {
6273 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006274 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006275 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006276 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006277 return;
6278 }
6279 }
6280
6281 if (local_description()) {
6282 mutable_local_description()->RemoveCandidates(candidates);
6283 }
6284 OnIceCandidatesRemoved(candidates);
6285}
6286
Alex Drake00c7ecf2019-08-06 10:54:47 -07006287void PeerConnection::OnTransportControllerCandidateChanged(
6288 const cricket::CandidatePairChangeEvent& event) {
6289 OnSelectedCandidatePairChanged(event);
6290}
6291
Steve Anton75737c02017-11-06 10:37:17 -08006292void PeerConnection::OnTransportControllerDtlsHandshakeError(
6293 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006294 RTC_HISTOGRAM_ENUMERATION(
6295 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6296 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006297}
6298
Steve Antoned10bd92017-12-05 10:52:59 -08006299void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006300 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006301 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006302 if (channel && !channel->enabled()) {
6303 channel->Enable(true);
6304 }
Steve Anton75737c02017-11-06 10:37:17 -08006305 }
6306
Steve Anton4171afb2017-11-20 10:20:22 -08006307 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006308 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006309 }
Steve Anton75737c02017-11-06 10:37:17 -08006310}
6311
6312// Returns the media index for a local ice candidate given the content name.
6313bool PeerConnection::GetLocalCandidateMediaIndex(
6314 const std::string& content_name,
6315 int* sdp_mline_index) {
6316 if (!local_description() || !sdp_mline_index) {
6317 return false;
6318 }
6319
6320 bool content_found = false;
6321 const ContentInfos& contents = local_description()->description()->contents();
6322 for (size_t index = 0; index < contents.size(); ++index) {
6323 if (contents[index].name == content_name) {
6324 *sdp_mline_index = static_cast<int>(index);
6325 content_found = true;
6326 break;
6327 }
6328 }
6329 return content_found;
6330}
6331
6332bool PeerConnection::UseCandidatesInSessionDescription(
6333 const SessionDescriptionInterface* remote_desc) {
6334 if (!remote_desc) {
6335 return true;
6336 }
6337 bool ret = true;
6338
6339 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6340 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6341 for (size_t n = 0; n < candidates->count(); ++n) {
6342 const IceCandidateInterface* candidate = candidates->at(n);
6343 bool valid = false;
6344 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6345 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006346 RTC_LOG(LS_INFO)
6347 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006348 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006349 }
6350 continue;
6351 }
6352 ret = UseCandidate(candidate);
6353 if (!ret) {
6354 break;
6355 }
6356 }
6357 }
6358 return ret;
6359}
6360
6361bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006362 RTCErrorOr<const cricket::ContentInfo*> result =
6363 FindContentInfo(remote_description(), candidate);
6364 if (!result.ok()) {
6365 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6366 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006367 return false;
6368 }
Steve Anton75737c02017-11-06 10:37:17 -08006369 std::vector<cricket::Candidate> candidates;
6370 candidates.push_back(candidate->candidate());
6371 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006372 RTCError error = transport_controller_->AddRemoteCandidates(
6373 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006374 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006375 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006376 // Candidates successfully submitted for checking.
6377 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6378 ice_connection_state_ ==
6379 PeerConnectionInterface::kIceConnectionDisconnected) {
6380 // If state is New, then the session has just gotten its first remote ICE
6381 // candidates, so go to Checking.
6382 // If state is Disconnected, the session is re-using old candidates or
6383 // receiving additional ones, so go to Checking.
6384 // If state is Connected, stay Connected.
6385 // TODO(bemasc): If state is Connected, and the new candidates are for a
6386 // newly added transport, then the state actually _should_ move to
6387 // checking. Add a way to distinguish that case.
6388 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6389 }
6390 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006391 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006392 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006393 }
6394 return true;
6395}
6396
Guido Urdaneta41633172019-05-23 20:12:29 +02006397RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6398 const SessionDescriptionInterface* description,
6399 const IceCandidateInterface* candidate) {
6400 if (candidate->sdp_mline_index() >= 0) {
6401 size_t mediacontent_index =
6402 static_cast<size_t>(candidate->sdp_mline_index());
6403 size_t content_size = description->description()->contents().size();
6404 if (mediacontent_index < content_size) {
6405 return &description->description()->contents()[mediacontent_index];
6406 } else {
6407 return RTCError(RTCErrorType::INVALID_RANGE,
6408 "Media line index (" +
6409 rtc::ToString(candidate->sdp_mline_index()) +
6410 ") out of range (number of mlines: " +
6411 rtc::ToString(content_size) + ").");
6412 }
6413 } else if (!candidate->sdp_mid().empty()) {
6414 auto& contents = description->description()->contents();
6415 auto it = absl::c_find_if(
6416 contents, [candidate](const cricket::ContentInfo& content_info) {
6417 return content_info.mid() == candidate->sdp_mid();
6418 });
6419 if (it == contents.end()) {
6420 return RTCError(
6421 RTCErrorType::INVALID_PARAMETER,
6422 "Mid " + candidate->sdp_mid() +
6423 " specified but no media section with that mid found.");
6424 } else {
6425 return &*it;
6426 }
6427 }
6428
6429 return RTCError(RTCErrorType::INVALID_PARAMETER,
6430 "Neither sdp_mline_index nor sdp_mid specified.");
6431}
6432
Steve Anton75737c02017-11-06 10:37:17 -08006433void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006434 // Destroy video channel first since it may have a pointer to the
6435 // voice channel.
6436 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006437 if (!video_info || video_info->rejected) {
6438 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006439 }
6440
Steve Anton6fec8802017-12-04 10:37:29 -08006441 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6442 if (!audio_info || audio_info->rejected) {
6443 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006444 }
6445
6446 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6447 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006448 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006449 }
6450}
6451
Steve Antondcc3c022017-12-22 16:02:54 -08006452RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6453 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006454 const cricket::ContentGroup* bundle_group = nullptr;
6455 if (configuration_.bundle_policy ==
6456 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006457 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006458 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006459 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6460 "max-bundle configured but session description "
6461 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006462 }
6463 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006464 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006465}
6466
6467RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006468 // Creating the media channels. Transports should already have been created
6469 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006470 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006471 if (voice && !voice->rejected &&
6472 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006473 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006474 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006475 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6476 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006477 }
6478 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6479 }
6480
Steve Antondcc3c022017-12-22 16:02:54 -08006481 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006482 if (video && !video->rejected &&
6483 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006484 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006485 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006486 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6487 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006488 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006489 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006490 }
6491
Steve Antondcc3c022017-12-22 16:02:54 -08006492 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006493 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006494 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006495 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006496 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6497 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006498 }
6499 }
6500
Steve Anton8a006912017-12-04 15:25:56 -08006501 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006502}
6503
Steve Anton4171afb2017-11-20 10:20:22 -08006504// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006505cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006506 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006507 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006508 MediaTransportConfig media_transport_config =
6509 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006510
Steve Anton75737c02017-11-06 10:37:17 -08006511 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006512 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006513 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6514 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006515 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006516 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006517 }
Steve Anton75737c02017-11-06 10:37:17 -08006518 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6519 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006520 voice_channel->SignalSentPacket.connect(this,
6521 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006522 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006523
Steve Antoneda6ccd2017-12-04 10:21:55 -08006524 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006525}
6526
Steve Anton4171afb2017-11-20 10:20:22 -08006527// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006528cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006529 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006530 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006531 MediaTransportConfig media_transport_config =
6532 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006533
Steve Anton75737c02017-11-06 10:37:17 -08006534 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006535 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006536 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6537 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006538 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006539 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006540 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006541 }
Steve Anton75737c02017-11-06 10:37:17 -08006542 video_channel->SignalDtlsSrtpSetupFailure.connect(
6543 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006544 video_channel->SignalSentPacket.connect(this,
6545 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006546 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006547
Steve Antoneda6ccd2017-12-04 10:21:55 -08006548 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006549}
6550
Zhi Huange830e682018-03-30 10:48:35 -07006551bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006552 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006553 case cricket::DCT_SCTP:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006554 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006555 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6556 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006557 if (!network_thread()->Invoke<bool>(
6558 RTC_FROM_HERE,
6559 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6560 mid))) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006561 return false;
6562 }
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006563
6564 // All non-RTP data channels must initialize |sctp_data_channels_|.
6565 for (const auto& channel : sctp_data_channels_) {
6566 channel->OnTransportChannelCreated();
6567 }
6568 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006569 case cricket::DCT_RTP:
6570 default:
6571 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6572 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6573 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006574 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006575 if (!rtp_data_channel_) {
6576 return false;
6577 }
6578 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6579 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6580 rtp_data_channel_->SignalSentPacket.connect(
6581 this, &PeerConnection::OnSentPacket_w);
6582 rtp_data_channel_->SetRtpTransport(rtp_transport);
6583 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006584 }
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006585 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006586}
6587
6588Call::Stats PeerConnection::GetCallStats() {
6589 if (!worker_thread()->IsCurrent()) {
6590 return worker_thread()->Invoke<Call::Stats>(
6591 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6592 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006593 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006594 if (call_) {
6595 return call_->GetStats();
6596 } else {
6597 return Call::Stats();
6598 }
6599}
6600
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006601bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006602 DataChannelTransportInterface* transport =
6603 transport_controller_->GetDataChannelTransport(mid);
6604 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006605 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006606 << "Data channel transport is not available for data channels, mid="
6607 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006608 return false;
6609 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006610 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006611
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006612 transport->SetDataSink(this);
6613 data_channel_transport_ = transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006614 data_channel_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006615 sctp_mid_ = mid;
6616 // TODO(mellem): Handling data channel state through media transport is
6617 // deprecated. Delete these lines when downstream implementations call
6618 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006619 transport_controller_->SignalMediaTransportStateChanged.connect(
6620 this, &PeerConnection::OnMediaTransportStateChanged_n);
6621 // Check the initial state right away, in case transport is already writable.
6622 OnMediaTransportStateChanged_n();
6623 return true;
6624}
6625
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006626void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006627 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006628 return;
6629 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006630 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6631 << *sctp_mid_;
6632
6633 // TODO(mellem): Delete this line when downstream implementations call
6634 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006635 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006636 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6637 // it.
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006638 sctp_mid_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006639 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006640 if (data_channel_transport_) {
6641 data_channel_transport_->SetDataSink(nullptr);
6642 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006643 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006644}
6645
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006646// TODO(mellem): Handling of data channel state through the media transport
6647// callback is deprecated. This function should be deleted once downstream
6648// implementations call DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006649void PeerConnection::OnMediaTransportStateChanged_n() {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006650 if (!sctp_mid_ || transport_controller_->GetMediaTransportState(*sctp_mid_) !=
6651 MediaTransportState::kWritable) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006652 return;
6653 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006654 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006655 RTC_FROM_HERE, signaling_thread(), [this] {
6656 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006657 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellem4c858282019-08-28 15:10:08 -07006658 SignalDataChannelTransportWritable_s(
6659 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006660 });
6661}
6662
Steve Anton75737c02017-11-06 10:37:17 -08006663// Returns false if bundle is enabled and rtcp_mux is disabled.
6664bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6665 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6666 if (!bundle_enabled)
6667 return true;
6668
6669 const cricket::ContentGroup* bundle_group =
6670 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6671 RTC_DCHECK(bundle_group != NULL);
6672
6673 const cricket::ContentInfos& contents = desc->contents();
6674 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6675 citer != contents.end(); ++citer) {
6676 const cricket::ContentInfo* content = (&*citer);
6677 RTC_DCHECK(content != NULL);
6678 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006679 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006680 if (!HasRtcpMuxEnabled(content))
6681 return false;
6682 }
6683 }
6684 // RTCP-MUX is enabled in all the contents.
6685 return true;
6686}
6687
6688bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006689 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006690}
6691
Steve Anton06817cd2018-12-18 15:55:30 -08006692static RTCError ValidateMids(const cricket::SessionDescription& description) {
6693 std::set<std::string> mids;
6694 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006695 if (content.name.empty()) {
6696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6697 "A media section is missing a MID attribute.");
6698 }
Steve Anton06817cd2018-12-18 15:55:30 -08006699 if (!mids.insert(content.name).second) {
6700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6701 "Duplicate a=mid value '" + content.name + "'.");
6702 }
6703 }
6704 return RTCError::OK();
6705}
6706
Steve Anton8a006912017-12-04 15:25:56 -08006707RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006708 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006709 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006710 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006711 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006712 }
6713
6714 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006715 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006716 }
6717
Steve Anton3828c062017-12-06 10:34:51 -08006718 SdpType type = sdesc->GetType();
6719 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6720 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006721 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006722 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006723 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006724 }
6725
Steve Anton06817cd2018-12-18 15:55:30 -08006726 RTCError error = ValidateMids(*sdesc->description());
6727 if (!error.ok()) {
6728 return error;
6729 }
6730
Steve Anton75737c02017-11-06 10:37:17 -08006731 // Verify crypto settings.
6732 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006733 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6734 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006735 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006736 if (!crypto_error.ok()) {
6737 return crypto_error;
6738 }
Steve Anton75737c02017-11-06 10:37:17 -08006739 }
6740
6741 // Verify ice-ufrag and ice-pwd.
6742 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006743 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6744 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006745 }
6746
6747 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006748 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6749 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006750 }
6751
6752 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6753 // m-lines that do not rtcp-mux enabled.
6754
6755 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006756 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006757 // With an answer we want to compare the new answer session description with
6758 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006759 const cricket::SessionDescription* offer_desc =
6760 (source == cricket::CS_LOCAL) ? remote_description()->description()
6761 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006762 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6763 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6764 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006765 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6766 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006767 }
6768 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006769 // The re-offers should respect the order of m= sections in current
6770 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006771 // With a re-offer, either the current local or current remote descriptions
6772 // could be the most up to date, so we would like to check against both of
6773 // them if they exist. It could be the case that one of them has a 0 port
6774 // for a media section, but the other does not. This is important to check
6775 // against in the case that we are recycling an m= section.
6776 const cricket::SessionDescription* current_desc = nullptr;
6777 const cricket::SessionDescription* secondary_current_desc = nullptr;
6778 if (local_description()) {
6779 current_desc = local_description()->description();
6780 if (remote_description()) {
6781 secondary_current_desc = remote_description()->description();
6782 }
6783 } else if (remote_description()) {
6784 current_desc = remote_description()->description();
6785 }
Steve Anton75737c02017-11-06 10:37:17 -08006786 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006787 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6788 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6790 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006791 }
6792 }
6793
Steve Antonba42e992018-04-09 14:10:01 -07006794 if (IsUnifiedPlan()) {
6795 // Ensure that each audio and video media section has at most one
6796 // "StreamParams". This will return an error if receiving a session
6797 // description from a "Plan B" endpoint which adds multiple tracks of the
6798 // same type. With Unified Plan, there can only be at most one track per
6799 // media section.
6800 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006801 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006802 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6803 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6804 desc.streams().size() > 1u) {
6805 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6806 "Media section has more than one track specified "
6807 "with a=ssrc lines which is not supported with "
6808 "Unified Plan.");
6809 }
6810 }
6811 }
6812
Steve Anton8a006912017-12-04 15:25:56 -08006813 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006814}
6815
Steve Anton3828c062017-12-06 10:34:51 -08006816bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006817 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006818 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006819 return (state == PeerConnectionInterface::kStable) ||
6820 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006821 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006822 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006823 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6824 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6825 }
6826}
6827
Steve Anton3828c062017-12-06 10:34:51 -08006828bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006829 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006830 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006831 return (state == PeerConnectionInterface::kStable) ||
6832 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006833 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006834 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006835 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6836 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6837 }
6838}
6839
Steve Antonf8470812017-12-04 10:46:21 -08006840const char* PeerConnection::SessionErrorToString(SessionError error) const {
6841 switch (error) {
6842 case SessionError::kNone:
6843 return "ERROR_NONE";
6844 case SessionError::kContent:
6845 return "ERROR_CONTENT";
6846 case SessionError::kTransport:
6847 return "ERROR_TRANSPORT";
6848 }
6849 RTC_NOTREACHED();
6850 return "";
6851}
6852
Steve Anton75737c02017-11-06 10:37:17 -08006853std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006854 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006855 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6856 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006857 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006858}
6859
Steve Anton8e20f172018-03-06 10:55:04 -08006860void PeerConnection::ReportSdpFormatReceived(
6861 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006862 int num_audio_mlines = 0;
6863 int num_video_mlines = 0;
6864 int num_audio_tracks = 0;
6865 int num_video_tracks = 0;
6866 for (const ContentInfo& content : remote_offer.description()->contents()) {
6867 cricket::MediaType media_type = content.media_description()->type();
6868 int num_tracks = std::max(
6869 1, static_cast<int>(content.media_description()->streams().size()));
6870 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6871 num_audio_mlines += 1;
6872 num_audio_tracks += num_tracks;
6873 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6874 num_video_mlines += 1;
6875 num_video_tracks += num_tracks;
6876 }
6877 }
6878 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6879 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6880 format = kSdpFormatReceivedComplexUnifiedPlan;
6881 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6882 format = kSdpFormatReceivedComplexPlanB;
6883 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6884 format = kSdpFormatReceivedSimple;
6885 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006886 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6887 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006888}
6889
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006890void PeerConnection::ReportIceCandidateCollected(
6891 const cricket::Candidate& candidate) {
6892 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
6893 if (candidate.address().IsPrivateIP()) {
6894 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
6895 }
6896 if (candidate.address().IsUnresolvedIP()) {
6897 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
6898 }
6899 if (candidate.address().family() == AF_INET6) {
6900 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
6901 }
6902}
6903
6904void PeerConnection::ReportRemoteIceCandidateAdded(
6905 const cricket::Candidate& candidate) {
6906 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
6907 if (candidate.address().IsPrivateIP()) {
6908 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
6909 }
6910 if (candidate.address().IsUnresolvedIP()) {
6911 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
6912 }
6913 if (candidate.address().family() == AF_INET6) {
6914 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
6915 }
6916}
6917
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006918void PeerConnection::NoteUsageEvent(UsageEvent event) {
6919 RTC_DCHECK_RUN_ON(signaling_thread());
6920 usage_event_accumulator_ |= static_cast<int>(event);
6921}
6922
6923void PeerConnection::ReportUsagePattern() const {
6924 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006925 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6926 usage_event_accumulator_,
6927 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006928 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006929 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006930 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6931 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006932 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006933 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6934 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6935 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6936 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006937 // If called after close(), we can't report, because observer may have
6938 // been deallocated, and therefore pointer is null. Write to log instead.
6939 if (observer_) {
6940 Observer()->OnInterestingUsage(usage_event_accumulator_);
6941 } else {
6942 RTC_LOG(LS_INFO) << "Interesting usage signature "
6943 << usage_event_accumulator_
6944 << " observed after observer shutdown";
6945 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006946 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006947}
6948
Steve Anton0ffaaa22018-02-23 10:31:30 -08006949void PeerConnection::ReportNegotiatedSdpSemantics(
6950 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006951 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006952 switch (answer.description()->msid_signaling()) {
6953 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006954 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006955 break;
6956 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006957 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006958 break;
6959 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006960 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006961 break;
6962 case cricket::kMsidSignalingMediaSection |
6963 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006964 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006965 break;
6966 default:
6967 RTC_NOTREACHED();
6968 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006969 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6970 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006971}
6972
Steve Anton75737c02017-11-06 10:37:17 -08006973// We need to check the local/remote description for the Transport instead of
6974// the session, because a new Transport added during renegotiation may have
6975// them unset while the session has them set from the previous negotiation.
6976// Not doing so may trigger the auto generation of transport description and
6977// mess up DTLS identity information, ICE credential, etc.
6978bool PeerConnection::ReadyToUseRemoteCandidate(
6979 const IceCandidateInterface* candidate,
6980 const SessionDescriptionInterface* remote_desc,
6981 bool* valid) {
6982 *valid = true;
6983
6984 const SessionDescriptionInterface* current_remote_desc =
6985 remote_desc ? remote_desc : remote_description();
6986
6987 if (!current_remote_desc) {
6988 return false;
6989 }
6990
Guido Urdaneta41633172019-05-23 20:12:29 +02006991 RTCErrorOr<const cricket::ContentInfo*> result =
6992 FindContentInfo(current_remote_desc, candidate);
6993 if (!result.ok()) {
6994 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6995 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006996
6997 *valid = false;
6998 return false;
6999 }
7000
Guido Urdaneta41633172019-05-23 20:12:29 +02007001 std::string transport_name = GetTransportName(result.value()->name);
7002 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007003}
7004
7005bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007006 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007007 (dtls_enabled_ ||
7008 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007009}
7010
7011void PeerConnection::OnTransportControllerGatheringState(
7012 cricket::IceGatheringState state) {
7013 RTC_DCHECK(signaling_thread()->IsCurrent());
7014 if (state == cricket::kIceGatheringGathering) {
7015 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7016 } else if (state == cricket::kIceGatheringComplete) {
7017 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7018 }
7019}
7020
7021void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007022 std::map<std::string, std::set<cricket::MediaType>>
7023 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007024 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007025 if (transceiver->internal()->channel()) {
7026 const std::string& transport_name =
7027 transceiver->internal()->channel()->transport_name();
7028 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007029 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007030 }
Steve Anton75737c02017-11-06 10:37:17 -08007031 }
7032 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007033 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7034 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007035 }
Zhi Huange830e682018-03-30 10:48:35 -07007036
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007037 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007038 if (transport_name) {
7039 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007040 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007041 }
Zhi Huange830e682018-03-30 10:48:35 -07007042
Steve Antonc7b964c2018-02-01 14:39:45 -08007043 for (const auto& entry : media_types_by_transport_name) {
7044 const std::string& transport_name = entry.first;
7045 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007046 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007047 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007048 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007049 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007050 }
7051 }
7052}
7053// Walk through the ConnectionInfos to gather best connection usage
7054// for IPv4 and IPv6.
7055void PeerConnection::ReportBestConnectionState(
7056 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007057 for (const cricket::TransportChannelStats& channel_stats :
7058 stats.channel_stats) {
7059 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007060 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007061 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007062 continue;
7063 }
7064
Steve Antonc7b964c2018-02-01 14:39:45 -08007065 const cricket::Candidate& local = connection_info.local_candidate;
7066 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007067
7068 // Increment the counter for IceCandidatePairType.
7069 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7070 (local.type() == RELAY_PORT_TYPE &&
7071 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007072 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7073 GetIceCandidatePairCounter(local, remote),
7074 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007075 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007076 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7077 GetIceCandidatePairCounter(local, remote),
7078 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007079 } else {
7080 RTC_CHECK(0);
7081 }
Steve Anton75737c02017-11-06 10:37:17 -08007082
7083 // Increment the counter for IP type.
7084 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007085 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7086 kBestConnections_IPv4,
7087 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007088 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007089 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7090 kBestConnections_IPv6,
7091 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007092 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007093 RTC_CHECK(!local.address().hostname().empty() &&
7094 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007095 }
7096
7097 return;
7098 }
7099 }
7100}
7101
7102void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007103 const cricket::TransportStats& stats,
7104 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007105 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7106 return;
7107 }
7108
7109 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7110 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7111 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7112 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7113 return;
7114 }
7115
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007116 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7117 for (cricket::MediaType media_type : media_types) {
7118 switch (media_type) {
7119 case cricket::MEDIA_TYPE_AUDIO:
7120 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7121 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7122 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7123 break;
7124 case cricket::MEDIA_TYPE_VIDEO:
7125 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7126 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7127 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7128 break;
7129 case cricket::MEDIA_TYPE_DATA:
7130 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7131 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7132 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7133 break;
7134 default:
7135 RTC_NOTREACHED();
7136 continue;
7137 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007138 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007139 }
7140
7141 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7142 for (cricket::MediaType media_type : media_types) {
7143 switch (media_type) {
7144 case cricket::MEDIA_TYPE_AUDIO:
7145 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7146 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7147 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7148 break;
7149 case cricket::MEDIA_TYPE_VIDEO:
7150 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7151 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7152 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7153 break;
7154 case cricket::MEDIA_TYPE_DATA:
7155 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7156 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7157 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7158 break;
7159 default:
7160 RTC_NOTREACHED();
7161 continue;
7162 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007163 }
Steve Anton75737c02017-11-06 10:37:17 -08007164 }
7165}
7166
7167void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007168 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007169 RTC_DCHECK(call_);
7170 call_->OnSentPacket(sent_packet);
7171}
7172
7173const std::string PeerConnection::GetTransportName(
7174 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007175 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007176 if (channel) {
7177 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007178 }
Bjorn A Mellem4c858282019-08-28 15:10:08 -07007179 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007180 RTC_DCHECK(sctp_mid_);
7181 if (content_name == *sctp_mid_) {
7182 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007183 }
7184 }
7185 // Return an empty string if failed to retrieve the transport name.
7186 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007187}
7188
Steve Anton6fec8802017-12-04 10:37:29 -08007189void PeerConnection::DestroyTransceiverChannel(
7190 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7191 transceiver) {
7192 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007193
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007194 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007195 if (channel) {
7196 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007197 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007198 }
7199}
7200
7201void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007202 if (rtp_data_channel_) {
7203 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007204 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007205 rtp_data_channel_ = nullptr;
7206 }
7207
7208 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7209 // grab a reference to this PeerConnection. If this is called from the
7210 // PeerConnection destructor, the RefCountedObject vtable will have already
7211 // been destroyed (since it is a subclass of PeerConnection) and using
7212 // rtc::Bind will cause "Pure virtual function called" error to appear.
7213
Bjorn A Mellem4c858282019-08-28 15:10:08 -07007214 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007215 OnDataChannelDestroyed();
7216 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7217 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007218 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007219 });
7220 }
Steve Anton6fec8802017-12-04 10:37:29 -08007221}
7222
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007223void PeerConnection::DestroyChannelInterface(
7224 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007225 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007226 switch (channel->media_type()) {
7227 case cricket::MEDIA_TYPE_AUDIO:
7228 channel_manager()->DestroyVoiceChannel(
7229 static_cast<cricket::VoiceChannel*>(channel));
7230 break;
7231 case cricket::MEDIA_TYPE_VIDEO:
7232 channel_manager()->DestroyVideoChannel(
7233 static_cast<cricket::VideoChannel*>(channel));
7234 break;
7235 case cricket::MEDIA_TYPE_DATA:
7236 channel_manager()->DestroyRtpDataChannel(
7237 static_cast<cricket::RtpDataChannel*>(channel));
7238 break;
7239 default:
7240 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7241 break;
7242 }
Zhi Huange830e682018-03-30 10:48:35 -07007243}
Steve Anton6fec8802017-12-04 10:37:29 -08007244
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007245bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007246 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007247 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007248 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007249 MediaTransportInterface* media_transport,
Bjorn A Mellem4c858282019-08-28 15:10:08 -07007250 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007251 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007252 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007253 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007254 auto base_channel = GetChannel(mid);
7255 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007256 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007257 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007258
Karl Wiberg5966c502019-02-21 23:55:09 +01007259 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007260 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007261 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007262
Bjorn A Mellem4c858282019-08-28 15:10:08 -07007263 if (data_channel_transport_ && mid == sctp_mid_ &&
7264 data_channel_transport_ != data_channel_transport) {
7265 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7266 // it's bundled).
7267 data_channel_transport_->SetDataSink(nullptr);
7268 data_channel_transport_ = data_channel_transport;
7269 if (data_channel_transport) {
7270 data_channel_transport->SetDataSink(this);
7271
7272 // There's a new data channel transport. This needs to be signaled to the
7273 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7274 // necessary when bundling is applied.
7275 data_channel_transport_invoker_->AsyncInvoke<void>(
7276 RTC_FROM_HERE, signaling_thread(), [this] {
7277 RTC_DCHECK_RUN_ON(signaling_thread());
7278 for (auto channel : sctp_data_channels_) {
7279 channel->OnTransportChannelCreated();
7280 }
7281 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007282 }
7283 }
7284
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007285 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007286}
7287
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007288void PeerConnection::OnSetStreams() {
7289 RTC_DCHECK_RUN_ON(signaling_thread());
7290 if (IsUnifiedPlan())
7291 UpdateNegotiationNeeded();
7292}
7293
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007294PeerConnectionObserver* PeerConnection::Observer() const {
7295 // In earlier production code, the pointer was not cleared on close,
7296 // which might have led to undefined behavior if the observer was not
7297 // deallocated, or strange crashes if it was.
7298 // We use CHECK in order to catch such behavior if it exists.
7299 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7300 RTC_CHECK(observer_);
7301 return observer_;
7302}
7303
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007304CryptoOptions PeerConnection::GetCryptoOptions() {
7305 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7306 // after it has been removed.
7307 return configuration_.crypto_options.has_value()
7308 ? *configuration_.crypto_options
7309 : factory_->options().crypto_options;
7310}
7311
Harald Alvestrand89061872018-01-02 14:08:34 +01007312void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007313 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007314 if (stats_collector_) {
7315 stats_collector_->ClearCachedStatsReport();
7316 }
7317}
7318
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007319void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007320 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7321 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007322}
7323
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007324void PeerConnection::UpdateNegotiationNeeded() {
7325 RTC_DCHECK_RUN_ON(signaling_thread());
7326 if (!IsUnifiedPlan()) {
7327 Observer()->OnRenegotiationNeeded();
7328 return;
7329 }
7330
7331 // If connection's [[IsClosed]] slot is true, abort these steps.
7332 if (IsClosed())
7333 return;
7334
7335 // If connection's signaling state is not "stable", abort these steps.
7336 if (signaling_state() != kStable)
7337 return;
7338
7339 // NOTE
7340 // The negotiation-needed flag will be updated once the state transitions to
7341 // "stable", as part of the steps for setting an RTCSessionDescription.
7342
7343 // If the result of checking if negotiation is needed is false, clear the
7344 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7345 // to false, and abort these steps.
7346 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7347 if (!is_negotiation_needed) {
7348 is_negotiation_needed_ = false;
7349 return;
7350 }
7351
7352 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7353 // steps.
7354 if (is_negotiation_needed_)
7355 return;
7356
7357 // Set connection's [[NegotiationNeeded]] slot to true.
7358 is_negotiation_needed_ = true;
7359
7360 // Queue a task that runs the following steps:
7361 // If connection's [[IsClosed]] slot is true, abort these steps.
7362 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7363 // Fire an event named negotiationneeded at connection.
7364 Observer()->OnRenegotiationNeeded();
7365}
7366
7367bool PeerConnection::CheckIfNegotiationIsNeeded() {
7368 RTC_DCHECK_RUN_ON(signaling_thread());
7369 // 1. If any implementation-specific negotiation is required, as described at
7370 // the start of this section, return true.
7371
Henrik Boström79b69802019-07-18 11:16:56 +02007372 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7373 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7374 return true;
7375 }
7376
7377 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007378 const SessionDescriptionInterface* description = current_local_description();
7379 if (!description)
7380 return true;
7381
Henrik Boström79b69802019-07-18 11:16:56 +02007382 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007383 // description has been negotiated yet for data, return true.
7384 if (!sctp_data_channels_.empty()) {
7385 if (!cricket::GetFirstDataContent(description->description()->contents()))
7386 return true;
7387 }
7388
Henrik Boström79b69802019-07-18 11:16:56 +02007389 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007390 // following checks:
7391 for (const auto& transceiver : transceivers_) {
7392 const ContentInfo* current_local_msection =
7393 FindTransceiverMSection(transceiver.get(), description);
7394
7395 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7396 transceiver.get(), current_remote_description());
7397
Henrik Boström79b69802019-07-18 11:16:56 +02007398 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007399 // but the associated m= section is not yet rejected in
7400 // connection.[[CurrentLocalDescription]] or
7401 // connection.[[CurrentRemoteDescription]], return true.
7402 if (transceiver->stopped()) {
7403 if (current_local_msection && !current_local_msection->rejected &&
7404 ((current_remote_msection && !current_remote_msection->rejected) ||
7405 !current_remote_msection)) {
7406 return true;
7407 }
7408 continue;
7409 }
7410
Henrik Boström79b69802019-07-18 11:16:56 +02007411 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007412 // section in description, return true.
7413 if (!current_local_msection)
7414 return true;
7415
7416 const MediaContentDescription* current_local_media_description =
7417 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007418 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007419 // in description then perform the following checks:
7420
Henrik Boström79b69802019-07-18 11:16:56 +02007421 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007422 // associated m= section in description either doesn't contain a single
7423 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7424 // m= section, or the MSID values themselves, differ from what is in
7425 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7426 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7427 if (current_local_media_description->streams().size() == 0)
7428 return true;
7429
7430 std::vector<std::string> msection_msids;
7431 for (const auto& stream : current_local_media_description->streams()) {
7432 for (const std::string& msid : stream.stream_ids())
7433 msection_msids.push_back(msid);
7434 }
7435
7436 std::vector<std::string> transceiver_msids =
7437 transceiver->sender()->stream_ids();
7438 if (msection_msids.size() != transceiver_msids.size())
7439 return true;
7440
7441 absl::c_sort(transceiver_msids);
7442 absl::c_sort(msection_msids);
7443 if (transceiver_msids != msection_msids)
7444 return true;
7445 }
7446
Henrik Boström79b69802019-07-18 11:16:56 +02007447 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007448 // associated m= section in neither connection.[[CurrentLocalDescription]]
7449 // nor connection.[[CurrentRemoteDescription]] matches
7450 // transceiver.[[Direction]], return true.
7451 if (description->GetType() == SdpType::kOffer) {
7452 if (!current_remote_description())
7453 return true;
7454
7455 if (!current_remote_msection)
7456 return true;
7457
7458 RtpTransceiverDirection current_local_direction =
7459 current_local_media_description->direction();
7460 RtpTransceiverDirection current_remote_direction =
7461 current_remote_msection->media_description()->direction();
7462 if (transceiver->direction() != current_local_direction &&
7463 transceiver->direction() !=
7464 RtpTransceiverDirectionReversed(current_remote_direction)) {
7465 return true;
7466 }
7467 }
7468
Henrik Boström79b69802019-07-18 11:16:56 +02007469 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007470 // associated m= section in the description does not match
7471 // transceiver.[[Direction]] intersected with the offered direction (as
7472 // described in [JSEP] (section 5.3.1.)), return true.
7473 if (description->GetType() == SdpType::kAnswer) {
7474 if (!remote_description())
7475 return true;
7476
7477 const ContentInfo* offered_remote_msection =
7478 FindTransceiverMSection(transceiver.get(), remote_description());
7479
7480 RtpTransceiverDirection offered_direction =
7481 offered_remote_msection
7482 ? offered_remote_msection->media_description()->direction()
7483 : RtpTransceiverDirection::kInactive;
7484
7485 if (current_local_media_description->direction() !=
7486 (RtpTransceiverDirectionIntersection(
7487 transceiver->direction(),
7488 RtpTransceiverDirectionReversed(offered_direction)))) {
7489 return true;
7490 }
7491 }
7492 }
7493
7494 // If all the preceding checks were performed and true was not returned,
7495 // nothing remains to be negotiated; return false.
7496 return false;
7497}
7498
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007499} // namespace webrtc