blob: 0f7970c53695c7037c683c8a3411c78a0a7bf2bd [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020028#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020029#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070030#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "logging/rtc_event_log/ice_logger.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Bjorn A Mellemb689af42019-08-21 10:44:59 -070059#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/trace_event.h"
61#include "system_wrappers/include/clock.h"
62#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070063#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080071using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080072using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080074using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080075using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080076using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080079using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070080using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080082
Steve Antonba818672017-11-06 10:21:57 -080083namespace webrtc {
84
Steve Anton75737c02017-11-06 10:37:17 -080085// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080089const char kInvalidCandidates[] = "Description contains invalid candidates.";
90const char kInvalidSdp[] = "Invalid session description.";
91const char kMlineMismatchInAnswer[] =
92 "The order of m-lines in answer doesn't match order in offer. Rejecting "
93 "answer.";
94const char kMlineMismatchInSubsequentOffer[] =
95 "The order of m-lines in subsequent offer doesn't match order from "
96 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080097const char kSdpWithoutDtlsFingerprint[] =
98 "Called with SDP without DTLS fingerprint.";
99const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
100const char kSdpWithoutIceUfragPwd[] =
101 "Called with SDP without ice-ufrag and ice-pwd.";
102const char kSessionError[] = "Session error code: ";
103const char kSessionErrorDesc[] = "Session error description: ";
104const char kDtlsSrtpSetupFailureRtp[] =
105 "Couldn't set up DTLS-SRTP on RTP channel.";
106const char kDtlsSrtpSetupFailureRtcp[] =
107 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108
Steve Anton75737c02017-11-06 10:37:17 -0800109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700111// Field trials.
112// Controls datagram transport support.
113const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700114// Controls datagram transport data channel support.
115const char kDatagramTransportDataChannelFieldTrial[] =
116 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700117
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800118// UMA metric names.
119const char kSimulcastVersionApplyLocalDescription[] =
120 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
121const char kSimulcastVersionApplyRemoteDescription[] =
122 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
123const char kSimulcastNumberOfEncodings[] =
124 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
125const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
126
Seth Hampson845e8782018-03-02 11:34:10 -0800127static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800128static const char kDefaultAudioSenderId[] = "defaulta0";
129static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700130
zhihuang8f65cdf2016-05-06 18:40:30 -0700131// The length of RTCP CNAMEs.
132static const int kRtcpCnameLength = 16;
133
Steve Antonad182762018-09-05 20:22:40 +0000134enum {
135 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
136 MSG_SET_SESSIONDESCRIPTION_FAILED,
137 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
138 MSG_GETSTATS,
139 MSG_FREE_DATACHANNELS,
140 MSG_REPORT_USAGE_PATTERN,
141};
142
Harald Alvestrand19793842018-06-25 12:03:50 +0200143static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
144
Steve Antonad182762018-09-05 20:22:40 +0000145struct SetSessionDescriptionMsg : public rtc::MessageData {
146 explicit SetSessionDescriptionMsg(
147 webrtc::SetSessionDescriptionObserver* observer)
148 : observer(observer) {}
149
150 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
151 RTCError error;
152};
153
154struct CreateSessionDescriptionMsg : public rtc::MessageData {
155 explicit CreateSessionDescriptionMsg(
156 webrtc::CreateSessionDescriptionObserver* observer)
157 : observer(observer) {}
158
159 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
160 RTCError error;
161};
162
163struct GetStatsMsg : public rtc::MessageData {
164 GetStatsMsg(webrtc::StatsObserver* observer,
165 webrtc::MediaStreamTrackInterface* track)
166 : observer(observer), track(track) {}
167 rtc::scoped_refptr<webrtc::StatsObserver> observer;
168 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
169};
170
deadbeefab9b2d12015-10-14 11:33:11 -0700171// Check if we can send |new_stream| on a PeerConnection.
172bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
173 webrtc::MediaStreamInterface* new_stream) {
174 if (!new_stream || !current_streams) {
175 return false;
176 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700177 if (current_streams->find(new_stream->id()) != nullptr) {
178 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700180 return false;
181 }
182 return true;
183}
184
deadbeef5e97fb52015-10-15 12:49:08 -0700185// If the direction is "recvonly" or "inactive", treat the description
186// as containing no streams.
187// See: https://code.google.com/p/webrtc/issues/detail?id=5054
188std::vector<cricket::StreamParams> GetActiveStreams(
189 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800190 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700191 ? desc->streams()
192 : std::vector<cricket::StreamParams>();
193}
194
deadbeefab9b2d12015-10-14 11:33:11 -0700195bool IsValidOfferToReceiveMedia(int value) {
196 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
197 return (value >= Options::kUndefined) &&
198 (value <= Options::kMaxOfferToReceiveMedia);
199}
200
zhihuang1c378ed2017-08-17 14:10:50 -0700201// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800202void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700203 const std::vector<rtc::scoped_refptr<
204 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700205 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200206 cricket::MediaDescriptionOptions* video_media_description_options,
207 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700208 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
210 if (audio_media_description_options) {
211 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700212 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 } else {
215 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
216 if (video_media_description_options) {
217 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800218 sender->id(), sender->internal()->stream_ids(), {},
219 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700220 }
221 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700222 }
zhihuang1c378ed2017-08-17 14:10:50 -0700223}
olka3c747662017-08-17 06:50:32 -0700224
zhihuang1c378ed2017-08-17 14:10:50 -0700225// Add options to |session_options| from |rtp_data_channels|.
226void AddRtpDataChannelOptions(
227 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
228 rtp_data_channels,
229 cricket::MediaDescriptionOptions* data_media_description_options) {
230 if (!data_media_description_options) {
231 return;
232 }
deadbeefab9b2d12015-10-14 11:33:11 -0700233 // Check for data channels.
234 for (const auto& kv : rtp_data_channels) {
235 const DataChannel* channel = kv.second;
236 if (channel->state() == DataChannel::kConnecting ||
237 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700238 // Legacy RTP data channels are signaled with the track/stream ID set to
239 // the data channel's label.
240 data_media_description_options->AddRtpDataChannel(channel->label(),
241 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700242 }
243 }
244}
245
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246uint32_t ConvertIceTransportTypeToCandidateFilter(
247 PeerConnectionInterface::IceTransportsType type) {
248 switch (type) {
249 case PeerConnectionInterface::kNone:
250 return cricket::CF_NONE;
251 case PeerConnectionInterface::kRelay:
252 return cricket::CF_RELAY;
253 case PeerConnectionInterface::kNoHost:
254 return (cricket::CF_ALL & ~cricket::CF_HOST);
255 case PeerConnectionInterface::kAll:
256 return cricket::CF_ALL;
257 default:
nissec80e7412017-01-11 05:56:46 -0800258 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700259 }
260 return cricket::CF_NONE;
261}
262
Steve Antonba818672017-11-06 10:21:57 -0800263std::string GetSignalingStateString(
264 PeerConnectionInterface::SignalingState state) {
265 switch (state) {
266 case PeerConnectionInterface::kStable:
267 return "kStable";
268 case PeerConnectionInterface::kHaveLocalOffer:
269 return "kHaveLocalOffer";
270 case PeerConnectionInterface::kHaveLocalPrAnswer:
271 return "kHavePrAnswer";
272 case PeerConnectionInterface::kHaveRemoteOffer:
273 return "kHaveRemoteOffer";
274 case PeerConnectionInterface::kHaveRemotePrAnswer:
275 return "kHaveRemotePrAnswer";
276 case PeerConnectionInterface::kClosed:
277 return "kClosed";
278 }
279 RTC_NOTREACHED();
280 return "";
281}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282
Steve Anton75737c02017-11-06 10:37:17 -0800283IceCandidatePairType GetIceCandidatePairCounter(
284 const cricket::Candidate& local,
285 const cricket::Candidate& remote) {
286 const auto& l = local.type();
287 const auto& r = remote.type();
288 const auto& host = LOCAL_PORT_TYPE;
289 const auto& srflx = STUN_PORT_TYPE;
290 const auto& relay = RELAY_PORT_TYPE;
291 const auto& prflx = PRFLX_PORT_TYPE;
292 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 bool local_hostname =
294 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
295 bool remote_hostname = !remote.address().hostname().empty() &&
296 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800297 bool local_private = IPIsPrivate(local.address().ipaddr());
298 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800299 if (local_hostname) {
300 if (remote_hostname) {
301 return kIceCandidatePairHostNameHostName;
302 } else if (remote_private) {
303 return kIceCandidatePairHostNameHostPrivate;
304 } else {
305 return kIceCandidatePairHostNameHostPublic;
306 }
307 } else if (local_private) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostPrivateHostName;
310 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800311 return kIceCandidatePairHostPrivateHostPrivate;
312 } else {
313 return kIceCandidatePairHostPrivateHostPublic;
314 }
315 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800316 if (remote_hostname) {
317 return kIceCandidatePairHostPublicHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPublicHostPrivate;
320 } else {
321 return kIceCandidatePairHostPublicHostPublic;
322 }
323 }
324 }
325 if (l == host && r == srflx)
326 return kIceCandidatePairHostSrflx;
327 if (l == host && r == relay)
328 return kIceCandidatePairHostRelay;
329 if (l == host && r == prflx)
330 return kIceCandidatePairHostPrflx;
331 if (l == srflx && r == host)
332 return kIceCandidatePairSrflxHost;
333 if (l == srflx && r == srflx)
334 return kIceCandidatePairSrflxSrflx;
335 if (l == srflx && r == relay)
336 return kIceCandidatePairSrflxRelay;
337 if (l == srflx && r == prflx)
338 return kIceCandidatePairSrflxPrflx;
339 if (l == relay && r == host)
340 return kIceCandidatePairRelayHost;
341 if (l == relay && r == srflx)
342 return kIceCandidatePairRelaySrflx;
343 if (l == relay && r == relay)
344 return kIceCandidatePairRelayRelay;
345 if (l == relay && r == prflx)
346 return kIceCandidatePairRelayPrflx;
347 if (l == prflx && r == host)
348 return kIceCandidatePairPrflxHost;
349 if (l == prflx && r == srflx)
350 return kIceCandidatePairPrflxSrflx;
351 if (l == prflx && r == relay)
352 return kIceCandidatePairPrflxRelay;
353 return kIceCandidatePairMax;
354}
355
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800356// Logic to decide if an m= section can be recycled. This means that the new
357// m= section is not rejected, but the old local or remote m= section is
358// rejected. |old_content_one| and |old_content_two| refer to the m= section
359// of the old remote and old local descriptions in no particular order.
360// We need to check both the old local and remote because either
361// could be the most current from the latest negotation.
362bool IsMediaSectionBeingRecycled(SdpType type,
363 const ContentInfo& content,
364 const ContentInfo* old_content_one,
365 const ContentInfo* old_content_two) {
366 return type == SdpType::kOffer && !content.rejected &&
367 ((old_content_one && old_content_one->rejected) ||
368 (old_content_two && old_content_two->rejected));
369}
370
Steve Anton75737c02017-11-06 10:37:17 -0800371// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372// |current_desc|. The number of m= sections in |new_desc| should be no
373// less than |current_desc|. In the case of checking an answer's
374// |new_desc|, the |current_desc| is the last offer that was set as the
375// local or remote. In the case of checking an offer's |new_desc| we
376// check against the local and remote descriptions stored from the last
377// negotiation, because either of these could be the most up to date for
378// possible rejected m sections. These are the |current_desc| and
379// |secondary_current_desc|.
380bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
381 const SessionDescription* secondary_current_desc,
382 const SessionDescription& new_desc,
383 const SdpType type) {
384 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800385 return false;
386 }
387
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
389 const cricket::ContentInfo* secondary_content_info = nullptr;
390 if (secondary_current_desc &&
391 i < secondary_current_desc->contents().size()) {
392 secondary_content_info = &secondary_current_desc->contents()[i];
393 }
394 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
395 &current_desc.contents()[i],
396 secondary_content_info)) {
397 // For new offer descriptions, if the media section can be recycled, it's
398 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800399 continue;
400 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800402 return false;
403 }
404 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800405 new_desc.contents()[i].media_description();
406 const MediaContentDescription* current_desc_mdesc =
407 current_desc.contents()[i].media_description();
408 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800409 return false;
410 }
411 }
412 return true;
413}
414
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800415bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
416 const SessionDescription& desc2) {
417 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800418}
419
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700420void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
421 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200422 // Array of structs needed to map {KeyExchangeProtocolType,
423 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
424 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
425 static constexpr struct {
426 KeyExchangeProtocolType protocol_type;
427 cricket::MediaType media_type;
428 KeyExchangeProtocolMedia protocol_media;
429 } kEnumCounterKeyProtocolMediaMap[] = {
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
434 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeDtlsData},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
437 kEnumCounterKeyProtocolMediaTypeSdesAudio},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
439 kEnumCounterKeyProtocolMediaTypeSdesVideo},
440 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
441 kEnumCounterKeyProtocolMediaTypeSdesData},
442 };
443
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
445 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100446
Mirko Bonadeiab499822018-09-11 10:43:20 +0200447 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
448 if (i.protocol_type == protocol_type && i.media_type == media_type) {
449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
450 i.protocol_media,
451 kEnumCounterKeyProtocolMediaTypeMax);
452 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100453 }
454}
455
Harald Alvestrand76829d72018-07-18 23:24:36 +0200456void NoteAddIceCandidateResult(int result) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
458 kAddIceCandidateMax);
459}
460
Steve Anton75737c02017-11-06 10:37:17 -0800461// Checks that each non-rejected content has SDES crypto keys or a DTLS
462// fingerprint, unless it's in a BUNDLE group, in which case only the
463// BUNDLE-tag section (first media section/description in the BUNDLE group)
464// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
465// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
466// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700467RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 const cricket::ContentGroup* bundle =
469 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800470 for (const cricket::ContentInfo& content_info : desc->contents()) {
471 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800472 continue;
473 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100474 // Note what media is used with each crypto protocol, for all sections.
475 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
476 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700477 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800478 const std::string& mid = content_info.name;
479 if (bundle && bundle->HasContentName(mid) &&
480 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 // This isn't the first media section in the BUNDLE group, so it's not
482 // required to have crypto attributes, since only the crypto attributes
483 // from the first section actually get used.
484 continue;
485 }
486
487 // If the content isn't rejected or bundled into another m= section, crypto
488 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800489 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800490 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (!media || !tinfo) {
492 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800494 }
495 if (dtls_enabled) {
496 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_WARNING)
498 << "Session description must have DTLS fingerprint if "
499 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError(RTCErrorType::INVALID_PARAMETER,
501 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 } else {
504 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800506 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800507 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800508 }
509 }
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800512}
513
514// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
515// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
516// media section/description in the BUNDLE group) needs a ufrag and pwd.
517bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
518 const cricket::ContentGroup* bundle =
519 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800520 for (const cricket::ContentInfo& content_info : desc->contents()) {
521 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 continue;
523 }
Steve Anton8a006912017-12-04 15:25:56 -0800524 const std::string& mid = content_info.name;
525 if (bundle && bundle->HasContentName(mid) &&
526 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 // This isn't the first media section in the BUNDLE group, so it's not
528 // required to have ufrag/password, since only the ufrag/password from
529 // the first section actually get used.
530 continue;
531 }
532
533 // If the content isn't rejected or bundled into another m= section,
534 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800535 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800536 if (!tinfo) {
537 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 if (tinfo->description.ice_ufrag.empty() ||
542 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 }
547 return true;
548}
549
Steve Anton75737c02017-11-06 10:37:17 -0800550// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
551bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
552 const SessionDescriptionInterface* new_desc,
553 const std::string& content_name) {
554 if (!old_desc) {
555 return false;
556 }
557 const SessionDescription* new_sd = new_desc->description();
558 const SessionDescription* old_sd = old_desc->description();
559 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
560 if (!cinfo || cinfo->rejected) {
561 return false;
562 }
563 // If the content isn't rejected, check if ufrag and password has changed.
564 const cricket::TransportDescription* new_transport_desc =
565 new_sd->GetTransportDescriptionByName(content_name);
566 const cricket::TransportDescription* old_transport_desc =
567 old_sd->GetTransportDescriptionByName(content_name);
568 if (!new_transport_desc || !old_transport_desc) {
569 // No transport description exists. This is not an ICE restart.
570 return false;
571 }
572 if (cricket::IceCredentialsChanged(
573 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
574 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
576 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800577 return true;
578 }
579 return false;
580}
581
Steve Anton80dd7b52018-02-16 17:08:42 -0800582// Generates a string error message for SetLocalDescription/SetRemoteDescription
583// from an RTCError.
584std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
585 SdpType type,
586 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200587 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800588 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
589 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200590 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800591}
592
Seth Hampson5b4f0752018-04-02 16:31:36 -0700593std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
594 std::string output = "streams=[";
595 const char* separator = "";
596 for (const auto& stream_id : stream_ids) {
597 output.append(separator).append(stream_id);
598 separator = ", ";
599 }
600 output.append("]");
601 return output;
602}
603
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200604absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700605 int rtc_configuration_parameter) {
606 if (rtc_configuration_parameter ==
607 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200608 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700609 }
610 return rtc_configuration_parameter;
611}
612
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800613cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
614 switch (type) {
615 case DataMessageType::kText:
616 return cricket::DMT_TEXT;
617 case DataMessageType::kBinary:
618 return cricket::DMT_BINARY;
619 case DataMessageType::kControl:
620 return cricket::DMT_CONTROL;
621 default:
622 return cricket::DMT_NONE;
623 }
624 return cricket::DMT_NONE;
625}
626
627DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
628 switch (type) {
629 case cricket::DMT_TEXT:
630 return DataMessageType::kText;
631 case cricket::DMT_BINARY:
632 return DataMessageType::kBinary;
633 case cricket::DMT_CONTROL:
634 return DataMessageType::kControl;
635 case cricket::DMT_NONE:
636 default:
637 RTC_NOTREACHED();
638 }
639 return DataMessageType::kControl;
640}
641
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800642void ReportSimulcastApiVersion(const char* name,
643 const SessionDescription& session) {
644 bool has_legacy = false;
645 bool has_spec_compliant = false;
646 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200647 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800648 continue;
649 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200650 has_spec_compliant |= content.media_description()->HasSimulcast();
651 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800652 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
653 }
654 }
655
656 if (has_legacy) {
657 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
658 kSimulcastApiVersionMax);
659 }
660 if (has_spec_compliant) {
661 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
662 kSimulcastApiVersionMax);
663 }
664 if (!has_legacy && !has_spec_compliant) {
665 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
666 kSimulcastApiVersionMax);
667 }
668}
669
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200670const ContentInfo* FindTransceiverMSection(
671 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
672 const SessionDescriptionInterface* session_description) {
673 return transceiver->mid()
674 ? session_description->description()->GetContentByName(
675 *transceiver->mid())
676 : nullptr;
677}
678
Steve Anton75737c02017-11-06 10:37:17 -0800679} // namespace
680
Henrik Boström79b69802019-07-18 11:16:56 +0200681class PeerConnection::LocalIceCredentialsToReplace {
682 public:
683 // Sets the ICE credentials that need restarting to the ICE credentials of
684 // the current and pending descriptions.
685 void SetIceCredentialsFromLocalDescriptions(
686 const SessionDescriptionInterface* current_local_description,
687 const SessionDescriptionInterface* pending_local_description) {
688 ice_credentials_.clear();
689 if (current_local_description) {
690 AppendIceCredentialsFromSessionDescription(*current_local_description);
691 }
692 if (pending_local_description) {
693 AppendIceCredentialsFromSessionDescription(*pending_local_description);
694 }
695 }
696
697 void ClearIceCredentials() { ice_credentials_.clear(); }
698
699 // Returns true if we have ICE credentials that need restarting.
700 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
701
702 // Returns true if |local_description| shares no ICE credentials with the
703 // ICE credentials that need restarting.
704 bool SatisfiesIceRestart(
705 const SessionDescriptionInterface& local_description) const {
706 for (const auto& transport_info :
707 local_description.description()->transport_infos()) {
708 if (ice_credentials_.find(std::make_pair(
709 transport_info.description.ice_ufrag,
710 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
711 return false;
712 }
713 }
714 return true;
715 }
716
717 private:
718 void AppendIceCredentialsFromSessionDescription(
719 const SessionDescriptionInterface& desc) {
720 for (const auto& transport_info : desc.description()->transport_infos()) {
721 ice_credentials_.insert(
722 std::make_pair(transport_info.description.ice_ufrag,
723 transport_info.description.ice_pwd));
724 }
725 }
726
727 std::set<std::pair<std::string, std::string>> ice_credentials_;
728};
729
Henrik Boström31638672017-11-23 17:48:32 +0100730// Upon completion, posts a task to execute the callback of the
731// SetSessionDescriptionObserver asynchronously on the same thread. At this
732// point, the state of the peer connection might no longer reflect the effects
733// of the SetRemoteDescription operation, as the peer connection could have been
734// modified during the post.
735// TODO(hbos): Remove this class once we remove the version of
736// PeerConnectionInterface::SetRemoteDescription() that takes a
737// SetSessionDescriptionObserver as an argument.
738class PeerConnection::SetRemoteDescriptionObserverAdapter
739 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
740 public:
741 SetRemoteDescriptionObserverAdapter(
742 rtc::scoped_refptr<PeerConnection> pc,
743 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
744 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
745
746 // SetRemoteDescriptionObserverInterface implementation.
747 void OnSetRemoteDescriptionComplete(RTCError error) override {
748 if (error.ok())
749 pc_->PostSetSessionDescriptionSuccess(wrapper_);
750 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100751 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100752 }
753
754 private:
755 rtc::scoped_refptr<PeerConnection> pc_;
756 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
757};
758
deadbeef293e9262017-01-11 12:28:30 -0800759bool PeerConnectionInterface::RTCConfiguration::operator==(
760 const PeerConnectionInterface::RTCConfiguration& o) const {
761 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700762 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800763 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000764 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700765 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800766 BundlePolicy bundle_policy;
767 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700768 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
769 int ice_candidate_pool_size;
770 bool disable_ipv6;
771 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700772 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100773 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700774 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200775 absl::optional<int> screencast_min_bitrate;
776 absl::optional<bool> combined_audio_video_bwe;
777 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800778 TcpCandidatePolicy tcp_candidate_policy;
779 CandidateNetworkPolicy candidate_network_policy;
780 int audio_jitter_buffer_max_packets;
781 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100782 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100783 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800784 int ice_connection_receiving_timeout;
785 int ice_backup_candidate_pair_ping_interval;
786 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800787 bool prioritize_most_likely_ice_candidate_pairs;
788 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800789 bool prune_turn_ports;
790 bool presume_writable_when_fully_relayed;
791 bool enable_ice_renomination;
792 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700793 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200794 absl::optional<int> ice_check_interval_strong_connectivity;
795 absl::optional<int> ice_check_interval_weak_connectivity;
796 absl::optional<int> ice_check_min_interval;
797 absl::optional<int> ice_unwritable_timeout;
798 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800799 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200800 absl::optional<int> stun_candidate_keepalive_interval;
801 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200802 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800803 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200804 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700805 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700806 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700807 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700808 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700809 absl::optional<bool> use_datagram_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700810 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100811 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800812 };
813 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
814 "Did you add something to RTCConfiguration and forget to "
815 "update operator==?");
816 return type == o.type && servers == o.servers &&
817 bundle_policy == o.bundle_policy &&
818 rtcp_mux_policy == o.rtcp_mux_policy &&
819 tcp_candidate_policy == o.tcp_candidate_policy &&
820 candidate_network_policy == o.candidate_network_policy &&
821 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
822 audio_jitter_buffer_fast_accelerate ==
823 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100824 audio_jitter_buffer_min_delay_ms ==
825 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100826 audio_jitter_buffer_enable_rtx_handling ==
827 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800828 ice_connection_receiving_timeout ==
829 o.ice_connection_receiving_timeout &&
830 ice_backup_candidate_pair_ping_interval ==
831 o.ice_backup_candidate_pair_ping_interval &&
832 continual_gathering_policy == o.continual_gathering_policy &&
833 certificates == o.certificates &&
834 prioritize_most_likely_ice_candidate_pairs ==
835 o.prioritize_most_likely_ice_candidate_pairs &&
836 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800837 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700838 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100839 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800840 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800841 screencast_min_bitrate == o.screencast_min_bitrate &&
842 combined_audio_video_bwe == o.combined_audio_video_bwe &&
843 enable_dtls_srtp == o.enable_dtls_srtp &&
844 ice_candidate_pool_size == o.ice_candidate_pool_size &&
845 prune_turn_ports == o.prune_turn_ports &&
846 presume_writable_when_fully_relayed ==
847 o.presume_writable_when_fully_relayed &&
848 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800849 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700850 surface_ice_candidates_on_ice_transport_type_changed ==
851 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800852 ice_check_interval_strong_connectivity ==
853 o.ice_check_interval_strong_connectivity &&
854 ice_check_interval_weak_connectivity ==
855 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700856 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700857 ice_unwritable_timeout == o.ice_unwritable_timeout &&
858 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800859 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800860 stun_candidate_keepalive_interval ==
861 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200862 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800863 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800864 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700865 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700866 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700867 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700868 use_media_transport_for_data_channels ==
869 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700870 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700871 use_datagram_transport_for_data_channels ==
872 o.use_datagram_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100873 crypto_options == o.crypto_options &&
874 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800875}
876
877bool PeerConnectionInterface::RTCConfiguration::operator!=(
878 const PeerConnectionInterface::RTCConfiguration& o) const {
879 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800880}
881
zhihuang8f65cdf2016-05-06 18:40:30 -0700882// Generate a RTCP CNAME when a PeerConnection is created.
883std::string GenerateRtcpCname() {
884 std::string cname;
885 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100886 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800887 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700888 }
889 return cname;
890}
891
zhihuang1c378ed2017-08-17 14:10:50 -0700892bool ValidateOfferAnswerOptions(
893 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
894 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
895 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700896}
897
zhihuang1c378ed2017-08-17 14:10:50 -0700898// From |rtc_options|, fill parts of |session_options| shared by all generated
899// m= sections (in other words, nothing that involves a map/array).
900void ExtractSharedMediaSessionOptions(
901 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
902 cricket::MediaSessionOptions* session_options) {
903 session_options->vad_enabled = rtc_options.voice_activity_detection;
904 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200905 session_options->raw_packetization_for_video =
906 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700907}
zhihuanga77e6bb2017-08-14 18:17:48 -0700908
zhihuang38ede132017-06-15 12:52:32 -0700909PeerConnection::PeerConnection(PeerConnectionFactory* factory,
910 std::unique_ptr<RtcEventLog> event_log,
911 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000912 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700913 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100914 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700915 datagram_transport_config_(
916 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700917 datagram_transport_data_channel_config_(
918 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700919 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700920 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700921 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100922 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200923 call_ptr_(call_.get()),
924 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925
926PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100927 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800928 RTC_DCHECK_RUN_ON(signaling_thread());
929
Steve Anton8af21862017-12-15 11:20:13 -0800930 // Need to stop transceivers before destroying the stats collector because
931 // AudioRtpSender has a reference to the StatsCollector it will update when
932 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100933 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800934 transceiver->Stop();
935 }
Steve Anton4171afb2017-11-20 10:20:22 -0800936
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700937 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800938 if (stats_collector_) {
939 stats_collector_->WaitForPendingRequest();
940 stats_collector_ = nullptr;
941 }
Steve Anton75737c02017-11-06 10:37:17 -0800942
Steve Anton8af21862017-12-15 11:20:13 -0800943 // Don't destroy BaseChannels until after stats has been cleaned up so that
944 // the last stats request can still read from the channels.
945 DestroyAllChannels();
946
Mirko Bonadei675513b2017-11-09 11:09:25 +0100947 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800948
949 webrtc_session_desc_factory_.reset();
950 sctp_invoker_.reset();
951 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700952 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800953 transport_controller_.reset();
954
deadbeef91dd5672016-05-18 16:55:30 -0700955 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100956 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
957 RTC_DCHECK_RUN_ON(network_thread());
958 port_allocator_.reset();
959 });
eladalon248fd4f2017-09-06 05:18:15 -0700960 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700961 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100962 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700963 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800964 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700965 event_log_.reset();
966 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967}
968
Steve Anton8af21862017-12-15 11:20:13 -0800969void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800970 // Destroy video channels first since they may have a pointer to a voice
971 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100972 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800973 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800974 DestroyTransceiverChannel(transceiver);
975 }
976 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100977 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800978 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800979 DestroyTransceiverChannel(transceiver);
980 }
981 }
982 DestroyDataChannel();
983}
984
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000986 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700987 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100988 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100989 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100990 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700991
992 RTCError config_error = ValidateConfiguration(configuration);
993 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100994 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700995 return false;
996 }
997
Benjamin Wrightcab58882018-05-02 15:12:47 -0700998 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100999 RTC_LOG(LS_ERROR)
1000 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001001 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001002 return false;
1003 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001004
Benjamin Wrightcab58882018-05-02 15:12:47 -07001005 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001006 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001007 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001008 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001009 return false;
1010 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001011
Benjamin Wrightcab58882018-05-02 15:12:47 -07001012 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001013 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001014 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001015 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001016
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001017 cricket::ServerAddresses stun_servers;
1018 std::vector<cricket::RelayServerConfig> turn_servers;
1019
1020 RTCErrorType parse_error =
1021 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1022 if (parse_error != RTCErrorType::NONE) {
1023 return false;
1024 }
1025
deadbeef91dd5672016-05-18 16:55:30 -07001026 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001027 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001028 const auto pa_result =
1029 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001030 RTC_FROM_HERE,
1031 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001032 stun_servers, turn_servers, configuration));
1033
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001034 // If initialization was successful, note if STUN or TURN servers
1035 // were supplied.
1036 if (!stun_servers.empty()) {
1037 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1038 }
1039 if (!turn_servers.empty()) {
1040 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1041 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001043 // Send information about IPv4/IPv6 status.
1044 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001045 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001046 address_family = kPeerConnection_IPv6;
1047 } else {
1048 address_family = kPeerConnection_IPv4;
1049 }
1050 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1051 kPeerConnectionAddressFamilyCounter_Max);
1052
Zhi Huange830e682018-03-30 10:48:35 -07001053 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1054
Steve Anton75737c02017-11-06 10:37:17 -08001055 // RFC 3264: The numeric value of the session id and version in the
1056 // o line MUST be representable with a "64 bit signed integer".
1057 // Due to this constraint session id |session_id_| is max limited to
1058 // LLONG_MAX.
1059 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001060 JsepTransportController::Config config;
1061 config.redetermine_role_on_ice_restart =
1062 configuration.redetermine_role_on_ice_restart;
1063 config.ssl_max_version = factory_->options().ssl_max_version;
1064 config.disable_encryption = options.disable_encryption;
1065 config.bundle_policy = configuration.bundle_policy;
1066 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001067 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1068 // stub.
1069 config.crypto_options = configuration.crypto_options.has_value()
1070 ? *configuration.crypto_options
1071 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001072 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001073 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001074#if defined(ENABLE_EXTERNAL_AUTH)
1075 config.enable_external_auth = true;
1076#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001077 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001078
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001079 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001080 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001081 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001082 use_datagram_transport_for_data_channels_ =
1083 datagram_transport_data_channel_config_.enabled &&
1084 configuration.use_datagram_transport_for_data_channels.value_or(
1085 datagram_transport_data_channel_config_.default_value);
1086 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1087 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001088 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001089 if (!factory_->media_transport_factory()) {
1090 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001091 << "PeerConnecton is initialized with use_media_transport = true or "
1092 << "use_media_transport_for_data_channels = true "
1093 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001094 return false;
1095 }
1096
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001097 if (configuration.use_media_transport ||
1098 configuration.use_media_transport_for_data_channels) {
1099 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1100 // RTP media transport is introduced. But until then, we require SDES to
1101 // be enabled.
1102 if (configuration.enable_dtls_srtp.has_value() &&
1103 configuration.enable_dtls_srtp.value()) {
1104 RTC_LOG(LS_WARNING)
1105 << "When media transport is used, SDES must be enabled. Set "
1106 "configuration.enable_dtls_srtp to false. use_media_transport="
1107 << configuration.use_media_transport
1108 << ", use_media_transport_for_data_channels="
1109 << configuration.use_media_transport_for_data_channels;
1110 return false;
1111 }
1112 }
1113
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001114 config.use_media_transport_for_media = configuration.use_media_transport;
1115 config.use_media_transport_for_data_channels =
1116 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001117 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001118 config.use_datagram_transport_for_data_channels =
1119 use_datagram_transport_for_data_channels_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001120 config.media_transport_factory = factory_->media_transport_factory();
1121 }
1122
Zhi Huange830e682018-03-30 10:48:35 -07001123 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001124 signaling_thread(), network_thread(), port_allocator_.get(),
1125 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001126 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001127 this, &PeerConnection::OnTransportControllerConnectionState);
1128 transport_controller_->SignalStandardizedIceConnectionState.connect(
1129 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001130 transport_controller_->SignalConnectionState.connect(
1131 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001132 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001133 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001134 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001135 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001136 transport_controller_->SignalIceCandidateError.connect(
1137 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001138 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001139 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1140 transport_controller_->SignalDtlsHandshakeError.connect(
1141 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001142 transport_controller_->SignalIceCandidatePairChanged.connect(
1143 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001144
1145 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001146
deadbeefab9b2d12015-10-14 11:33:11 -07001147 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001148 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001149
Steve Antonba818672017-11-06 10:21:57 -08001150 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001151 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001152
Steve Anton75737c02017-11-06 10:37:17 -08001153 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1154 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1155 if (!configuration.certificates.empty()) {
1156 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1157 // just picking the first one. The decision should be made based on the DTLS
1158 // handshake. The DTLS negotiations need to know about all certificates.
1159 certificate = configuration.certificates[0];
1160 }
1161
Steve Antond25da372017-11-06 14:50:29 -08001162 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001163
1164 if (options.disable_encryption) {
1165 dtls_enabled_ = false;
1166 } else {
1167 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001168 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001169 // |configuration| can override the default |dtls_enabled_| value.
1170 if (configuration.enable_dtls_srtp) {
1171 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1172 }
1173 }
1174
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001175 if (use_datagram_transport_for_data_channels_) {
1176 if (configuration.enable_rtp_data_channel) {
1177 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1178 "use_datagram_transport_for_data_channels are "
1179 "incompatible and cannot both be set to true";
1180 return false;
1181 }
1182 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1183 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1184 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1185 } else {
1186 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1187 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1188 }
1189 } else if (configuration.use_media_transport_for_data_channels) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001190 if (configuration.enable_rtp_data_channel) {
1191 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1192 "use_media_transport_for_data_channels are "
1193 "incompatible and cannot both be set to true";
1194 return false;
1195 }
1196 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1197 } else if (configuration.enable_rtp_data_channel) {
1198 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1199 // set. It takes precendence over the disable_sctp_data_channels
1200 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001201 data_channel_type_ = cricket::DCT_RTP;
1202 } else {
1203 // DTLS has to be enabled to use SCTP.
1204 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1205 data_channel_type_ = cricket::DCT_SCTP;
1206 }
1207 }
1208
1209 video_options_.screencast_min_bitrate_kbps =
1210 configuration.screencast_min_bitrate;
1211 audio_options_.combined_audio_video_bwe =
1212 configuration.combined_audio_video_bwe;
1213
1214 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001215 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001216
1217 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001218 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001219
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001220 audio_options_.audio_jitter_buffer_min_delay_ms =
1221 configuration.audio_jitter_buffer_min_delay_ms;
1222
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001223 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1224 configuration.audio_jitter_buffer_enable_rtx_handling;
1225
Steve Anton75737c02017-11-06 10:37:17 -08001226 // Whether the certificate generator/certificate is null or not determines
1227 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1228 // the right instructions by clearing the variables if needed.
1229 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001230 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001231 certificate = nullptr;
1232 } else if (certificate) {
1233 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001234 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001235 }
1236
1237 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1238 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001239 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001240 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1241 this, &PeerConnection::OnCertificateReady);
1242
1243 if (options.disable_encryption) {
1244 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1245 }
1246
1247 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001248 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001249 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250
Steve Anton4171afb2017-11-20 10:20:22 -08001251 // Add default audio/video transceivers for Plan B SDP.
1252 if (!IsUnifiedPlan()) {
1253 transceivers_.push_back(
1254 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1255 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1256 transceivers_.push_back(
1257 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1258 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1259 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001260 int delay_ms =
1261 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001262 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1263 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001264
1265 if (dependencies.video_bitrate_allocator_factory) {
1266 video_bitrate_allocator_factory_ =
1267 std::move(dependencies.video_bitrate_allocator_factory);
1268 } else {
1269 video_bitrate_allocator_factory_ =
1270 CreateBuiltinVideoBitrateAllocatorFactory();
1271 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272 return true;
1273}
1274
Steve Anton038834f2017-07-14 15:59:59 -07001275RTCError PeerConnection::ValidateConfiguration(
1276 const RTCConfiguration& config) const {
1277 if (config.ice_regather_interval_range &&
1278 config.continual_gathering_policy == GATHER_ONCE) {
1279 return RTCError(RTCErrorType::INVALID_PARAMETER,
1280 "ice_regather_interval_range specified but continual "
1281 "gathering policy is GATHER_ONCE");
1282 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001283 auto result =
1284 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1285 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001286}
1287
Yves Gerey665174f2018-06-19 15:03:05 +02001288rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001289 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001290 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1291 "Plan SdpSemantics. Please use GetSenders "
1292 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001293 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001294}
1295
Yves Gerey665174f2018-06-19 15:03:05 +02001296rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001297 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001298 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1299 "Plan SdpSemantics. Please use GetReceivers "
1300 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001301 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302}
1303
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001304bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001305 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001306 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1307 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001308 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 if (IsClosed()) {
1310 return false;
1311 }
deadbeefab9b2d12015-10-14 11:33:11 -07001312 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313 return false;
1314 }
deadbeefab9b2d12015-10-14 11:33:11 -07001315
1316 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001317 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1318 observer->SignalAudioTrackAdded.connect(this,
1319 &PeerConnection::OnAudioTrackAdded);
1320 observer->SignalAudioTrackRemoved.connect(
1321 this, &PeerConnection::OnAudioTrackRemoved);
1322 observer->SignalVideoTrackAdded.connect(this,
1323 &PeerConnection::OnVideoTrackAdded);
1324 observer->SignalVideoTrackRemoved.connect(
1325 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001326 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001327
deadbeefab9b2d12015-10-14 11:33:11 -07001328 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001329 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001330 }
1331 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001332 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001333 }
1334
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001335 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001336 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 return true;
1338}
1339
1340void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001341 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001342 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1343 "Plan SdpSemantics. Please use RemoveTrack "
1344 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001345 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001346 if (!IsClosed()) {
1347 for (const auto& track : local_stream->GetAudioTracks()) {
1348 RemoveAudioTrack(track.get(), local_stream);
1349 }
1350 for (const auto& track : local_stream->GetVideoTracks()) {
1351 RemoveVideoTrack(track.get(), local_stream);
1352 }
deadbeefab9b2d12015-10-14 11:33:11 -07001353 }
deadbeefab9b2d12015-10-14 11:33:11 -07001354 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001355 stream_observers_.erase(
1356 std::remove_if(
1357 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001358 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001359 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001360 }),
1361 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001362
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 if (IsClosed()) {
1364 return;
1365 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001366 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367}
1368
Steve Anton2d6c76a2018-01-05 17:10:52 -08001369RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001370 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001371 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001372 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001373 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001374 if (!track) {
1375 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1376 }
1377 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1378 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1379 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1380 "Track has invalid kind: " + track->kind());
1381 }
Steve Antonf9381f02017-12-14 10:23:57 -08001382 if (IsClosed()) {
1383 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1384 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001385 }
Steve Anton4171afb2017-11-20 10:20:22 -08001386 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001387 LOG_AND_RETURN_ERROR(
1388 RTCErrorType::INVALID_PARAMETER,
1389 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001390 }
Steve Antonf9381f02017-12-14 10:23:57 -08001391 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001392 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1393 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001394 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001395 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001396 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001397 }
1398 return sender_or_error;
1399}
deadbeefe1f9d832016-01-14 15:35:42 -08001400
Steve Antonf9381f02017-12-14 10:23:57 -08001401RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1402PeerConnection::AddTrackPlanB(
1403 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001404 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001405 if (stream_ids.size() > 1u) {
1406 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1407 "AddTrack with more than one stream is not "
1408 "supported with Plan B semantics.");
1409 }
1410 std::vector<std::string> adjusted_stream_ids = stream_ids;
1411 if (adjusted_stream_ids.empty()) {
1412 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1413 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001414 cricket::MediaType media_type =
1415 (track->kind() == MediaStreamTrackInterface::kAudioKind
1416 ? cricket::MEDIA_TYPE_AUDIO
1417 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001418 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001419 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001420 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001421 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001422 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001423 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001424 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001425 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001426 if (sender_info) {
1427 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001428 }
Steve Antonf9381f02017-12-14 10:23:57 -08001429 } else {
1430 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001431 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001432 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001433 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001434 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001435 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001436 if (sender_info) {
1437 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001438 }
deadbeefe1f9d832016-01-14 15:35:42 -08001439 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001440 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001441}
deadbeefe1f9d832016-01-14 15:35:42 -08001442
Steve Antonf9381f02017-12-14 10:23:57 -08001443RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1444PeerConnection::AddTrackUnifiedPlan(
1445 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001446 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001447 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1448 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001449 RTC_LOG(LS_INFO) << "Reusing an existing "
1450 << cricket::MediaTypeToString(transceiver->media_type())
1451 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001452 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001453 transceiver->internal()->set_direction(
1454 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001455 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001456 transceiver->internal()->set_direction(
1457 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001458 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001459 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001460 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001461 } else {
1462 cricket::MediaType media_type =
1463 (track->kind() == MediaStreamTrackInterface::kAudioKind
1464 ? cricket::MEDIA_TYPE_AUDIO
1465 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001466 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1467 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001468 std::string sender_id = track->id();
1469 // Avoid creating a sender with an existing ID by generating a random ID.
1470 // This can happen if this is the second time AddTrack has created a sender
1471 // for this track.
1472 if (FindSenderById(sender_id)) {
1473 sender_id = rtc::CreateRandomUuid();
1474 }
Florent Castelli892acf02018-10-01 22:47:20 +02001475 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001476 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1477 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001478 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001479 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001480 }
Steve Antonf9381f02017-12-14 10:23:57 -08001481 return transceiver->sender();
1482}
1483
1484rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1485PeerConnection::FindFirstTransceiverForAddedTrack(
1486 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1487 RTC_DCHECK(track);
1488 for (auto transceiver : transceivers_) {
1489 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001490 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001491 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001492 !transceiver->internal()->has_ever_been_used_to_send() &&
1493 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001494 return transceiver;
1495 }
1496 }
1497 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001498}
1499
1500bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1501 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001502 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001503}
1504
Steve Anton24db5732018-07-23 10:27:33 -07001505RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001506 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001507 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001508 if (!sender) {
1509 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1510 }
deadbeefe1f9d832016-01-14 15:35:42 -08001511 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001512 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1513 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001514 }
Steve Antonf9381f02017-12-14 10:23:57 -08001515 if (IsUnifiedPlan()) {
1516 auto transceiver = FindTransceiverBySender(sender);
1517 if (!transceiver || !sender->track()) {
1518 return RTCError::OK();
1519 }
1520 sender->SetTrack(nullptr);
1521 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001522 transceiver->internal()->set_direction(
1523 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001524 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001525 transceiver->internal()->set_direction(
1526 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001527 }
Steve Anton4171afb2017-11-20 10:20:22 -08001528 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001529 bool removed;
1530 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1531 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1532 } else {
1533 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1534 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1535 }
1536 if (!removed) {
1537 LOG_AND_RETURN_ERROR(
1538 RTCErrorType::INVALID_PARAMETER,
1539 "Couldn't find sender " + sender->id() + " to remove.");
1540 }
Steve Anton4171afb2017-11-20 10:20:22 -08001541 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001542 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001543 return RTCError::OK();
1544}
1545
1546rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1547PeerConnection::FindTransceiverBySender(
1548 rtc::scoped_refptr<RtpSenderInterface> sender) {
1549 for (auto transceiver : transceivers_) {
1550 if (transceiver->sender() == sender) {
1551 return transceiver;
1552 }
1553 }
1554 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001555}
1556
Steve Anton9158ef62017-11-27 13:01:52 -08001557RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1558PeerConnection::AddTransceiver(
1559 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1560 return AddTransceiver(track, RtpTransceiverInit());
1561}
1562
1563RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1564PeerConnection::AddTransceiver(
1565 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1566 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001567 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001568 RTC_CHECK(IsUnifiedPlan())
1569 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001570 if (!track) {
1571 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1572 }
1573 cricket::MediaType media_type;
1574 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1575 media_type = cricket::MEDIA_TYPE_AUDIO;
1576 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1577 media_type = cricket::MEDIA_TYPE_VIDEO;
1578 } else {
1579 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1580 "Track kind is not audio or video");
1581 }
1582 return AddTransceiver(media_type, track, init);
1583}
1584
1585RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1586PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1587 return AddTransceiver(media_type, RtpTransceiverInit());
1588}
1589
1590RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1591PeerConnection::AddTransceiver(cricket::MediaType media_type,
1592 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001593 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001594 RTC_CHECK(IsUnifiedPlan())
1595 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001596 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1597 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1598 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1599 "media type is not audio or video");
1600 }
1601 return AddTransceiver(media_type, nullptr, init);
1602}
1603
1604RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1605PeerConnection::AddTransceiver(
1606 cricket::MediaType media_type,
1607 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001608 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001609 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001610 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1611 media_type == cricket::MEDIA_TYPE_VIDEO));
1612 if (track) {
1613 RTC_DCHECK_EQ(media_type,
1614 (track->kind() == MediaStreamTrackInterface::kAudioKind
1615 ? cricket::MEDIA_TYPE_AUDIO
1616 : cricket::MEDIA_TYPE_VIDEO));
1617 }
1618
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001619 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1620 init.send_encodings.size(), 0, 7, 8);
1621
Amit Hilbuchaa584152019-02-06 17:09:52 -08001622 size_t num_rids = absl::c_count_if(init.send_encodings,
1623 [](const RtpEncodingParameters& encoding) {
1624 return !encoding.rid.empty();
1625 });
1626 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001627 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001628 RTCErrorType::INVALID_PARAMETER,
1629 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001630 }
1631
Amit Hilbuchf4770402019-04-08 14:11:57 -07001632 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1633 [](const RtpEncodingParameters& encoding) {
1634 return !IsLegalRsidName(encoding.rid);
1635 })) {
1636 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1637 "Invalid RID value provided.");
1638 }
1639
Amit Hilbuchaa584152019-02-06 17:09:52 -08001640 if (absl::c_any_of(init.send_encodings,
1641 [](const RtpEncodingParameters& encoding) {
1642 return encoding.ssrc.has_value();
1643 })) {
1644 LOG_AND_RETURN_ERROR(
1645 RTCErrorType::UNSUPPORTED_PARAMETER,
1646 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001647 }
1648
1649 RtpParameters parameters;
1650 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001651
1652 // Encodings are dropped from the tail if too many are provided.
1653 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1654 parameters.encodings.erase(
1655 parameters.encodings.begin() + kMaxSimulcastStreams,
1656 parameters.encodings.end());
1657 }
1658
1659 // Single RID should be removed.
1660 if (parameters.encodings.size() == 1 &&
1661 !parameters.encodings[0].rid.empty()) {
1662 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1663 parameters.encodings[0].rid.clear();
1664 }
1665
1666 // If RIDs were not provided, they are generated for simulcast scenario.
1667 if (parameters.encodings.size() > 1 && num_rids == 0) {
1668 rtc::UniqueStringGenerator rid_generator;
1669 for (RtpEncodingParameters& encoding : parameters.encodings) {
1670 encoding.rid = rid_generator();
1671 }
1672 }
1673
Florent Castelli892acf02018-10-01 22:47:20 +02001674 if (UnimplementedRtpParameterHasValue(parameters)) {
1675 LOG_AND_RETURN_ERROR(
1676 RTCErrorType::UNSUPPORTED_PARAMETER,
1677 "Attempted to set an unimplemented parameter of RtpParameters.");
1678 }
Steve Anton9158ef62017-11-27 13:01:52 -08001679
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001680 auto result = cricket::CheckRtpParametersValues(parameters);
1681 if (!result.ok()) {
1682 LOG_AND_RETURN_ERROR(result.type(), result.message());
1683 }
1684
Steve Anton3d954a62018-04-02 11:27:23 -07001685 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1686 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001687 // Set the sender ID equal to the track ID if the track is specified unless
1688 // that sender ID is already in use.
1689 std::string sender_id =
1690 (track && !FindSenderById(track->id()) ? track->id()
1691 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001692 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001693 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001694 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1695 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1696 transceiver->internal()->set_direction(init.direction);
1697
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001698 if (update_negotiation_needed) {
1699 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001700 }
Steve Antonf9381f02017-12-14 10:23:57 -08001701
1702 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1703}
1704
Steve Anton02ee47c2018-01-10 16:26:06 -08001705rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1706PeerConnection::CreateSender(
1707 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001708 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001709 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001710 const std::vector<std::string>& stream_ids,
1711 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001712 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001713 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001714 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1715 RTC_DCHECK(!track ||
1716 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1717 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1718 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001719 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001720 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001721 } else {
1722 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1723 RTC_DCHECK(!track ||
1724 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1725 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001726 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001727 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001728 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001729 bool set_track_succeeded = sender->SetTrack(track);
1730 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001731 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001732 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001733 return sender;
1734}
1735
1736rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1737PeerConnection::CreateReceiver(cricket::MediaType media_type,
1738 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001739 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1740 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001741 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001742 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001743 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1744 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001745 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001746 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001747 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001748 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001749 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1750 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001751 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001752 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001753 return receiver;
1754}
1755
1756rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1757PeerConnection::CreateAndAddTransceiver(
1758 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1759 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1760 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001761 // Ensure that the new sender does not have an ID that is already in use by
1762 // another sender.
1763 // Allow receiver IDs to conflict since those come from remote SDP (which
1764 // could be invalid, but should not cause a crash).
1765 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001766 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001767 signaling_thread(),
1768 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001769 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001770 transceiver->internal()->SignalNegotiationNeeded.connect(
1771 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001772 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001773}
1774
Steve Anton52d86772018-02-20 15:48:12 -08001775void PeerConnection::OnNegotiationNeeded() {
1776 RTC_DCHECK_RUN_ON(signaling_thread());
1777 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001778 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001779}
1780
deadbeeffac06552015-11-25 11:26:01 -08001781rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001782 const std::string& kind,
1783 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001784 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001785 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1786 "Plan SdpSemantics. Please use AddTransceiver "
1787 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001788 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001789 if (IsClosed()) {
1790 return nullptr;
1791 }
Steve Anton4171afb2017-11-20 10:20:22 -08001792
Seth Hampson5b4f0752018-04-02 16:31:36 -07001793 // Internally we need to have one stream with Plan B semantics, so we
1794 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001795 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001796 if (stream_id.empty()) {
1797 stream_ids.push_back(rtc::CreateRandomUuid());
1798 RTC_LOG(LS_INFO)
1799 << "No stream_id specified for sender. Generated stream ID: "
1800 << stream_ids[0];
1801 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001802 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001803 }
1804
Steve Anton4171afb2017-11-20 10:20:22 -08001805 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001806 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001807 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001808 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001809 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001810 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001811 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001812 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001813 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001814 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001815 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001816 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001817 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001818 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001819 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001820 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001821 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001822 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001823 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001824 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001825 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001826
deadbeefe1f9d832016-01-14 15:35:42 -08001827 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001828}
1829
deadbeef70ab1a12015-09-28 16:53:55 -07001830std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1831 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001832 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001833 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001834 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001835 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001836 }
1837 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001838}
1839
Steve Anton4171afb2017-11-20 10:20:22 -08001840std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1841PeerConnection::GetSendersInternal() const {
1842 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1843 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001844 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001845 auto senders = transceiver->internal()->senders();
1846 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1847 }
1848 return all_senders;
1849}
1850
deadbeef70ab1a12015-09-28 16:53:55 -07001851std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1852PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001853 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001854 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001855 for (const auto& receiver : GetReceiversInternal()) {
1856 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001857 }
1858 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001859}
1860
Steve Anton4171afb2017-11-20 10:20:22 -08001861std::vector<
1862 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1863PeerConnection::GetReceiversInternal() const {
1864 std::vector<
1865 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1866 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001867 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001868 auto receivers = transceiver->internal()->receivers();
1869 all_receivers.insert(all_receivers.end(), receivers.begin(),
1870 receivers.end());
1871 }
1872 return all_receivers;
1873}
1874
Steve Anton9158ef62017-11-27 13:01:52 -08001875std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1876PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001877 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001878 RTC_CHECK(IsUnifiedPlan())
1879 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001880 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001881 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001882 all_transceivers.push_back(transceiver);
1883 }
1884 return all_transceivers;
1885}
1886
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001888 MediaStreamTrackInterface* track,
1889 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001890 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001891 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001892 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001893 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894 return false;
1895 }
1896
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001897 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001898 // The StatsCollector is used to tell if a track is valid because it may
1899 // remember tracks that the PeerConnection previously removed.
1900 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001901 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1902 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001903 return false;
1904 }
Steve Antonad182762018-09-05 20:22:40 +00001905 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1906 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907 return true;
1908}
1909
hbos74e1a4f2016-09-15 23:33:01 -07001910void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001911 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001912 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001913 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001914 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001915 stats_collector_->GetStatsReport(callback);
1916}
1917
Henrik Boström1df1bf82018-03-20 13:24:20 +01001918void PeerConnection::GetStats(
1919 rtc::scoped_refptr<RtpSenderInterface> selector,
1920 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1921 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001922 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001923 RTC_DCHECK(callback);
1924 RTC_DCHECK(stats_collector_);
1925 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1926 if (selector) {
1927 for (const auto& proxy_transceiver : transceivers_) {
1928 for (const auto& proxy_sender :
1929 proxy_transceiver->internal()->senders()) {
1930 if (proxy_sender == selector) {
1931 internal_sender = proxy_sender->internal();
1932 break;
1933 }
1934 }
1935 if (internal_sender)
1936 break;
1937 }
1938 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001939 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001940 // belong to the PeerConnection (in Plan B, senders can be removed from the
1941 // PeerConnection). This means that "all the stats objects representing the
1942 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1943 // produces an empty stats report.
1944 stats_collector_->GetStatsReport(internal_sender, callback);
1945}
1946
1947void PeerConnection::GetStats(
1948 rtc::scoped_refptr<RtpReceiverInterface> selector,
1949 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1950 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001951 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001952 RTC_DCHECK(callback);
1953 RTC_DCHECK(stats_collector_);
1954 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1955 if (selector) {
1956 for (const auto& proxy_transceiver : transceivers_) {
1957 for (const auto& proxy_receiver :
1958 proxy_transceiver->internal()->receivers()) {
1959 if (proxy_receiver == selector) {
1960 internal_receiver = proxy_receiver->internal();
1961 break;
1962 }
1963 }
1964 if (internal_receiver)
1965 break;
1966 }
1967 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001968 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001969 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1970 // the PeerConnection). This means that "all the stats objects representing
1971 // the selector" is an empty set. Invoking GetStatsReport() with a null
1972 // selector produces an empty stats report.
1973 stats_collector_->GetStatsReport(internal_receiver, callback);
1974}
1975
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001977 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978 return signaling_state_;
1979}
1980
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001981PeerConnectionInterface::IceConnectionState
1982PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001983 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 return ice_connection_state_;
1985}
1986
Alex Loiko9289eda2018-11-23 16:18:59 +00001987PeerConnectionInterface::IceConnectionState
1988PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001989 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001990 return standardized_ice_connection_state_;
1991}
1992
Jonas Olsson635474e2018-10-18 15:58:17 +02001993PeerConnectionInterface::PeerConnectionState
1994PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001995 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001996 return connection_state_;
1997}
1998
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001999PeerConnectionInterface::IceGatheringState
2000PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002001 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002 return ice_gathering_state_;
2003}
2004
Yves Gerey665174f2018-06-19 15:03:05 +02002005rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 const std::string& label,
2007 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002008 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002009 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002010
deadbeefab9b2d12015-10-14 11:33:11 -07002011 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002012
kwibergd1fe2812016-04-27 06:47:29 -07002013 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002014 if (config) {
2015 internal_config.reset(new InternalDataChannelInit(*config));
2016 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002017 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002018 InternalCreateDataChannel(label, internal_config.get()));
2019 if (!channel.get()) {
2020 return nullptr;
2021 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002022
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002023 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2024 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002025 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002026 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002027 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002028 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 return DataChannelProxy::Create(signaling_thread(), channel.get());
2030}
2031
Henrik Boström79b69802019-07-18 11:16:56 +02002032void PeerConnection::RestartIce() {
2033 RTC_DCHECK_RUN_ON(signaling_thread());
2034 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2035 current_local_description_.get(), pending_local_description_.get());
2036 UpdateNegotiationNeeded();
2037}
2038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002040 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002041 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002042 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002043
nisse7ce109a2017-01-31 00:57:56 -08002044 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002045 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002046 return;
2047 }
deadbeefab9b2d12015-10-14 11:33:11 -07002048
Steve Anton8d3444d2017-10-20 15:30:51 -07002049 if (IsClosed()) {
2050 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002051 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002052 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002053 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002054 return;
2055 }
2056
Steve Anton25ca0ac2019-06-25 10:40:48 -07002057 // If a session error has occurred the PeerConnection is in a possibly
2058 // inconsistent state so fail right away.
2059 if (session_error() != SessionError::kNone) {
2060 std::string error_message = GetSessionErrorMsg();
2061 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2062 PostCreateSessionDescriptionFailure(
2063 observer,
2064 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2065 return;
2066 }
2067
zhihuang1c378ed2017-08-17 14:10:50 -07002068 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002069 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002070 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002071 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002072 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002073 return;
2074 }
2075
Steve Anton22da89f2018-01-25 13:58:07 -08002076 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2077 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2078 if (IsUnifiedPlan()) {
2079 RTCError error = HandleLegacyOfferOptions(options);
2080 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002081 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002082 return;
2083 }
2084 }
2085
zhihuang1c378ed2017-08-17 14:10:50 -07002086 cricket::MediaSessionOptions session_options;
2087 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002088 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002089}
2090
Steve Anton22da89f2018-01-25 13:58:07 -08002091RTCError PeerConnection::HandleLegacyOfferOptions(
2092 const RTCOfferAnswerOptions& options) {
2093 RTC_DCHECK(IsUnifiedPlan());
2094
2095 if (options.offer_to_receive_audio == 0) {
2096 RemoveRecvDirectionFromReceivingTransceiversOfType(
2097 cricket::MEDIA_TYPE_AUDIO);
2098 } else if (options.offer_to_receive_audio == 1) {
2099 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2100 } else if (options.offer_to_receive_audio > 1) {
2101 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2102 "offer_to_receive_audio > 1 is not supported.");
2103 }
2104
2105 if (options.offer_to_receive_video == 0) {
2106 RemoveRecvDirectionFromReceivingTransceiversOfType(
2107 cricket::MEDIA_TYPE_VIDEO);
2108 } else if (options.offer_to_receive_video == 1) {
2109 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2110 } else if (options.offer_to_receive_video > 1) {
2111 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2112 "offer_to_receive_video > 1 is not supported.");
2113 }
2114
2115 return RTCError::OK();
2116}
2117
2118void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2119 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002120 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002121 RtpTransceiverDirection new_direction =
2122 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2123 if (new_direction != transceiver->direction()) {
2124 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2125 << " transceiver (MID="
2126 << transceiver->mid().value_or("<not set>") << ") from "
2127 << RtpTransceiverDirectionToString(
2128 transceiver->direction())
2129 << " to "
2130 << RtpTransceiverDirectionToString(new_direction)
2131 << " since CreateOffer specified offer_to_receive=0";
2132 transceiver->internal()->set_direction(new_direction);
2133 }
Steve Anton22da89f2018-01-25 13:58:07 -08002134 }
2135}
2136
2137void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2138 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002139 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002140 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002141 RTC_LOG(LS_INFO)
2142 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2143 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002144 RtpTransceiverInit init;
2145 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002146 AddTransceiver(media_type, nullptr, init,
2147 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002148 }
2149}
2150
2151std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2152PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2153 std::vector<
2154 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2155 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002156 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002157 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002158 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2159 receiving_transceivers.push_back(transceiver);
2160 }
2161 }
2162 return receiving_transceivers;
2163}
2164
htaa2a49d92016-03-04 02:51:39 -08002165void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2166 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002167 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002168 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002169 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002170 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002171 return;
2172 }
2173
Steve Anton25ca0ac2019-06-25 10:40:48 -07002174 // If a session error has occurred the PeerConnection is in a possibly
2175 // inconsistent state so fail right away.
2176 if (session_error() != SessionError::kNone) {
2177 std::string error_message = GetSessionErrorMsg();
2178 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2179 PostCreateSessionDescriptionFailure(
2180 observer,
2181 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2182 return;
2183 }
2184
Steve Antondffead82018-02-06 10:31:29 -08002185 if (!(signaling_state_ == kHaveRemoteOffer ||
2186 signaling_state_ == kHaveLocalPrAnswer)) {
2187 std::string error =
2188 "PeerConnection cannot create an answer in a state other than "
2189 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002190 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002191 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002192 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002193 return;
2194 }
2195
Steve Antondffead82018-02-06 10:31:29 -08002196 // The remote description should be set if we're in the right state.
2197 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002198
Steve Anton22da89f2018-01-25 13:58:07 -08002199 if (IsUnifiedPlan()) {
2200 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2201 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2202 "supported with Unified Plan semantics. Use the "
2203 "RtpTransceiver API instead.";
2204 }
2205 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2206 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2207 "supported with Unified Plan semantics. Use the "
2208 "RtpTransceiver API instead.";
2209 }
2210 }
2211
htaa2a49d92016-03-04 02:51:39 -08002212 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002213 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002214
Steve Antond25da372017-11-06 14:50:29 -08002215 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002216}
2217
2218void PeerConnection::SetLocalDescription(
2219 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002220 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002221 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002222 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002223
Steve Anton80dd7b52018-02-16 17:08:42 -08002224 // The SetLocalDescription contract is that we take ownership of the session
2225 // description regardless of the outcome, so wrap it in a unique_ptr right
2226 // away. Ideally, SetLocalDescription's signature will be changed to take the
2227 // description as a unique_ptr argument to formalize this agreement.
2228 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2229
nisse7ce109a2017-01-31 00:57:56 -08002230 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002231 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002232 return;
2233 }
Steve Anton8a006912017-12-04 15:25:56 -08002234
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002236 PostSetSessionDescriptionFailure(
2237 observer,
2238 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 return;
2240 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002241
Steve Anton80dd7b52018-02-16 17:08:42 -08002242 // If a session error has occurred the PeerConnection is in a possibly
2243 // inconsistent state so fail right away.
2244 if (session_error() != SessionError::kNone) {
2245 std::string error_message = GetSessionErrorMsg();
2246 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002247 PostSetSessionDescriptionFailure(
2248 observer,
2249 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002250 return;
2251 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002252
Steve Anton80dd7b52018-02-16 17:08:42 -08002253 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2254 if (!error.ok()) {
2255 std::string error_message = GetSetDescriptionErrorMessage(
2256 cricket::CS_LOCAL, desc->GetType(), error);
2257 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002258 PostSetSessionDescriptionFailure(
2259 observer,
2260 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002261 return;
2262 }
2263
2264 // Grab the description type before moving ownership to ApplyLocalDescription,
2265 // which may destroy it before returning.
2266 const SdpType type = desc->GetType();
2267
2268 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002269 // |desc| may be destroyed at this point.
2270
2271 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002272 // If ApplyLocalDescription fails, the PeerConnection could be in an
2273 // inconsistent state, so act conservatively here and set the session error
2274 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2275 SetSessionError(SessionError::kContent, error.message());
2276 std::string error_message =
2277 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2278 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002279 PostSetSessionDescriptionFailure(
2280 observer,
2281 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002282 return;
2283 }
Steve Anton8a006912017-12-04 15:25:56 -08002284 RTC_DCHECK(local_description());
2285
2286 PostSetSessionDescriptionSuccess(observer);
2287
Steve Antonad182762018-09-05 20:22:40 +00002288 // MaybeStartGathering needs to be called after posting
2289 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2290 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002291 transport_controller_->MaybeStartGathering();
2292
Steve Antona3a92c22017-12-07 10:27:41 -08002293 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002294 // TODO(deadbeef): We already had to hop to the network thread for
2295 // MaybeStartGathering...
2296 network_thread()->Invoke<void>(
2297 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2298 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002299 // Make UMA notes about what was agreed to.
2300 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002301 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002302
2303 if (IsUnifiedPlan()) {
2304 bool was_negotiation_needed = is_negotiation_needed_;
2305 UpdateNegotiationNeeded();
2306 if (signaling_state() == kStable && was_negotiation_needed &&
2307 is_negotiation_needed_) {
2308 Observer()->OnRenegotiationNeeded();
2309 }
2310 }
2311
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002312 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002313}
2314
2315RTCError PeerConnection::ApplyLocalDescription(
2316 std::unique_ptr<SessionDescriptionInterface> desc) {
2317 RTC_DCHECK_RUN_ON(signaling_thread());
2318 RTC_DCHECK(desc);
2319
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002320 // Update stats here so that we have the most recent stats for tracks and
2321 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002322 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002323
Steve Antondcc3c022017-12-22 16:02:54 -08002324 // Take a reference to the old local description since it's used below to
2325 // compare against the new local description. When setting the new local
2326 // description, grab ownership of the replaced session description in case it
2327 // is the same as |old_local_description|, to keep it alive for the duration
2328 // of the method.
2329 const SessionDescriptionInterface* old_local_description =
2330 local_description();
2331 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002332 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002333 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002334 replaced_local_description = pending_local_description_
2335 ? std::move(pending_local_description_)
2336 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002337 current_local_description_ = std::move(desc);
2338 pending_local_description_ = nullptr;
2339 current_remote_description_ = std::move(pending_remote_description_);
2340 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002341 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002342 pending_local_description_ = std::move(desc);
2343 }
2344 // The session description to apply now must be accessed by
2345 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002346 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002347
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002348 // Report statistics about any use of simulcast.
2349 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2350 *local_description()->description());
2351
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002352 if (!is_caller_) {
2353 if (remote_description()) {
2354 // Remote description was applied first, so this PC is the callee.
2355 is_caller_ = false;
2356 } else {
2357 // Local description is applied first, so this PC is the caller.
2358 is_caller_ = true;
2359 }
2360 }
2361
Zhi Huange830e682018-03-30 10:48:35 -07002362 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2363 if (!error.ok()) {
2364 return error;
2365 }
2366
Steve Antondcc3c022017-12-22 16:02:54 -08002367 if (IsUnifiedPlan()) {
2368 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002369 cricket::CS_LOCAL, *local_description(), old_local_description,
2370 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002371 if (!error.ok()) {
2372 return error;
2373 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002374 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2375 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002376 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002377 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2378 // Note that code paths that don't set MID won't be able to use
2379 // information about DTLS transports.
2380 if (transceiver->mid()) {
2381 auto dtls_transport =
2382 LookupDtlsTransportByMidInternal(*transceiver->mid());
2383 transceiver->internal()->sender_internal()->set_transport(
2384 dtls_transport);
2385 transceiver->internal()->receiver_internal()->set_transport(
2386 dtls_transport);
2387 }
2388
Steve Antondcc3c022017-12-22 16:02:54 -08002389 const ContentInfo* content =
2390 FindMediaSectionForTransceiver(transceiver, local_description());
2391 if (!content) {
2392 continue;
2393 }
2394 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002395 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2396 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002397 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002398 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2399 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2400 // "recvonly", process the removal of a remote track for the media
2401 // description, given transceiver, removeList, and muteTracks.
2402 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2403 (transceiver->internal()->fired_direction() &&
2404 RtpTransceiverDirectionHasRecv(
2405 *transceiver->internal()->fired_direction()))) {
2406 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2407 &removed_streams);
2408 }
2409 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2410 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002411 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002412 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002413 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002414 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002415 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002416 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002417 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002418 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002419 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002420 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002421 }
2422 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002423 // Media channels will be created only when offer is set. These may use new
2424 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002425 if (type == SdpType::kOffer) {
2426 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2427 // description is applied. Restore back to old description.
2428 RTCError error = CreateChannels(*local_description()->description());
2429 if (!error.ok()) {
2430 return error;
2431 }
2432 }
Steve Antondcc3c022017-12-22 16:02:54 -08002433 // Remove unused channels if MediaContentDescription is rejected.
2434 RemoveUnusedChannels(local_description()->description());
2435 }
Steve Anton8a006912017-12-04 15:25:56 -08002436
Zhi Huange830e682018-03-30 10:48:35 -07002437 error = UpdateSessionState(type, cricket::CS_LOCAL,
2438 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002439 if (!error.ok()) {
2440 return error;
2441 }
Steve Antondcc3c022017-12-22 16:02:54 -08002442
Steve Anton8a006912017-12-04 15:25:56 -08002443 if (remote_description()) {
2444 // Now that we have a local description, we can push down remote candidates.
2445 UseCandidatesInSessionDescription(remote_description());
2446 }
2447
2448 pending_ice_restarts_.clear();
2449 if (session_error() != SessionError::kNone) {
2450 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2451 }
2452
deadbeefab9b2d12015-10-14 11:33:11 -07002453 // If setting the description decided our SSL role, allocate any necessary
2454 // SCTP sids.
2455 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002456 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002457 AllocateSctpSids(role);
2458 }
2459
Steve Antond3679212018-01-17 17:41:02 -08002460 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002461 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002462 const ContentInfo* content =
2463 FindMediaSectionForTransceiver(transceiver, local_description());
2464 if (!content) {
2465 continue;
2466 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002467 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2468 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002469 // 0 is a special value meaning "this sender has no associated send
2470 // stream". Need to call this so the sender won't attempt to configure
2471 // a no longer existing stream and run into DCHECKs in the lower
2472 // layers.
2473 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002474 } else {
2475 // Get the StreamParams from the channel which could generate SSRCs.
2476 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002477 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002478 streams[0].stream_ids());
2479 transceiver->internal()->sender_internal()->SetSsrc(
2480 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002481 }
2482 }
2483 } else {
2484 // Plan B semantics.
2485
Steve Antondcc3c022017-12-22 16:02:54 -08002486 // Update state and SSRC of local MediaStreams and DataChannels based on the
2487 // local session description.
2488 const cricket::ContentInfo* audio_content =
2489 GetFirstAudioContent(local_description()->description());
2490 if (audio_content) {
2491 if (audio_content->rejected) {
2492 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2493 } else {
2494 const cricket::AudioContentDescription* audio_desc =
2495 audio_content->media_description()->as_audio();
2496 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2497 }
deadbeeffaac4972015-11-12 15:33:07 -08002498 }
deadbeefab9b2d12015-10-14 11:33:11 -07002499
Steve Antondcc3c022017-12-22 16:02:54 -08002500 const cricket::ContentInfo* video_content =
2501 GetFirstVideoContent(local_description()->description());
2502 if (video_content) {
2503 if (video_content->rejected) {
2504 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2505 } else {
2506 const cricket::VideoContentDescription* video_desc =
2507 video_content->media_description()->as_video();
2508 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2509 }
deadbeeffaac4972015-11-12 15:33:07 -08002510 }
deadbeefab9b2d12015-10-14 11:33:11 -07002511 }
2512
2513 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002514 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002515 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002516 const cricket::RtpDataContentDescription* rtp_data_desc =
2517 data_content->media_description()->as_rtp_data();
2518 // rtp_data_desc will be null if this is an SCTP description.
2519 if (rtp_data_desc) {
2520 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002521 }
2522 }
2523
Henrik Boström79b69802019-07-18 11:16:56 +02002524 if (type == SdpType::kAnswer &&
2525 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2526 *current_local_description_)) {
2527 local_ice_credentials_to_replace_->ClearIceCredentials();
2528 }
2529
Steve Anton8a006912017-12-04 15:25:56 -08002530 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531}
2532
Steve Anton06817cd2018-12-18 15:55:30 -08002533// The SDP parser used to populate these values by default for the 'content
2534// name' if an a=mid line was absent.
2535static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2536 switch (media_type) {
2537 case cricket::MEDIA_TYPE_AUDIO:
2538 return cricket::CN_AUDIO;
2539 case cricket::MEDIA_TYPE_VIDEO:
2540 return cricket::CN_VIDEO;
2541 case cricket::MEDIA_TYPE_DATA:
2542 return cricket::CN_DATA;
2543 }
2544 RTC_NOTREACHED();
2545 return "";
2546}
2547
2548void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002549 cricket::SessionDescription* new_remote_description) {
2550 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002551 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002552 const cricket::ContentInfos& local_contents =
2553 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002554 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002555 const cricket::ContentInfos& remote_contents =
2556 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002557 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002558 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2559 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002560 if (!content.name.empty()) {
2561 continue;
2562 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002563 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002564 absl::string_view source_explanation;
2565 if (IsUnifiedPlan()) {
2566 if (i < local_contents.size()) {
2567 new_mid = local_contents[i].name;
2568 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002569 } else if (i < remote_contents.size()) {
2570 new_mid = remote_contents[i].name;
2571 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002572 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002573 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002574 source_explanation = "generated just now";
2575 }
2576 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002577 new_mid = std::string(
2578 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002579 source_explanation = "to match pre-existing behavior";
2580 }
Steve Antond7180cc2019-02-07 10:44:53 -08002581 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002582 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002583 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002584 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2585 << " is missing an a=mid line. Filling in the value '"
2586 << new_mid << "' " << source_explanation << ".";
2587 }
2588}
2589
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002590void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002591 SetSessionDescriptionObserver* observer,
2592 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002593 SetRemoteDescription(
2594 std::unique_ptr<SessionDescriptionInterface>(desc),
2595 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2596 new SetRemoteDescriptionObserverAdapter(this, observer)));
2597}
2598
2599void PeerConnection::SetRemoteDescription(
2600 std::unique_ptr<SessionDescriptionInterface> desc,
2601 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002602 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002603 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002604
nisse7ce109a2017-01-31 00:57:56 -08002605 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002606 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002607 return;
2608 }
Steve Anton8a006912017-12-04 15:25:56 -08002609
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002611 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002612 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613 return;
2614 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002615
Steve Anton80dd7b52018-02-16 17:08:42 -08002616 // If a session error has occurred the PeerConnection is in a possibly
2617 // inconsistent state so fail right away.
2618 if (session_error() != SessionError::kNone) {
2619 std::string error_message = GetSessionErrorMsg();
2620 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2621 observer->OnSetRemoteDescriptionComplete(
2622 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2623 return;
2624 }
Steve Anton71439a62018-02-15 11:53:06 -08002625
Steve Antonba42e992018-04-09 14:10:01 -07002626 if (desc->GetType() == SdpType::kOffer) {
2627 // Report to UMA the format of the received offer.
2628 ReportSdpFormatReceived(*desc);
2629 }
2630
Steve Anton06817cd2018-12-18 15:55:30 -08002631 // Handle remote descriptions missing a=mid lines for interop with legacy end
2632 // points.
2633 FillInMissingRemoteMids(desc->description());
2634
Steve Anton80dd7b52018-02-16 17:08:42 -08002635 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002636 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002637 std::string error_message = GetSetDescriptionErrorMessage(
2638 cricket::CS_REMOTE, desc->GetType(), error);
2639 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002640 observer->OnSetRemoteDescriptionComplete(
2641 RTCError(error.type(), std::move(error_message)));
2642 return;
2643 }
Steve Anton71439a62018-02-15 11:53:06 -08002644
Steve Anton80dd7b52018-02-16 17:08:42 -08002645 // Grab the description type before moving ownership to
2646 // ApplyRemoteDescription, which may destroy it before returning.
2647 const SdpType type = desc->GetType();
2648
2649 error = ApplyRemoteDescription(std::move(desc));
2650 // |desc| may be destroyed at this point.
2651
2652 if (!error.ok()) {
2653 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2654 // inconsistent state, so act conservatively here and set the session error
2655 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2656 SetSessionError(SessionError::kContent, error.message());
2657 std::string error_message =
2658 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2659 RTC_LOG(LS_ERROR) << error_message;
2660 observer->OnSetRemoteDescriptionComplete(
2661 RTCError(error.type(), std::move(error_message)));
2662 return;
2663 }
2664 RTC_DCHECK(remote_description());
2665
2666 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002667 // TODO(deadbeef): We already had to hop to the network thread for
2668 // MaybeStartGathering...
2669 network_thread()->Invoke<void>(
2670 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2671 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002672 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002673 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002674 }
2675
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002676 if (IsUnifiedPlan()) {
2677 bool was_negotiation_needed = is_negotiation_needed_;
2678 UpdateNegotiationNeeded();
2679 if (signaling_state() == kStable && was_negotiation_needed &&
2680 is_negotiation_needed_) {
2681 Observer()->OnRenegotiationNeeded();
2682 }
2683 }
2684
Steve Anton8a006912017-12-04 15:25:56 -08002685 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002686 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002687}
2688
2689RTCError PeerConnection::ApplyRemoteDescription(
2690 std::unique_ptr<SessionDescriptionInterface> desc) {
2691 RTC_DCHECK_RUN_ON(signaling_thread());
2692 RTC_DCHECK(desc);
2693
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 // Update stats here so that we have the most recent stats for tracks and
2695 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002696 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002697
Steve Antondcc3c022017-12-22 16:02:54 -08002698 // Take a reference to the old remote description since it's used below to
2699 // compare against the new remote description. When setting the new remote
2700 // description, grab ownership of the replaced session description in case it
2701 // is the same as |old_remote_description|, to keep it alive for the duration
2702 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002703 const SessionDescriptionInterface* old_remote_description =
2704 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002705 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002706 SdpType type = desc->GetType();
2707 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002708 replaced_remote_description = pending_remote_description_
2709 ? std::move(pending_remote_description_)
2710 : std::move(current_remote_description_);
2711 current_remote_description_ = std::move(desc);
2712 pending_remote_description_ = nullptr;
2713 current_local_description_ = std::move(pending_local_description_);
2714 } else {
2715 replaced_remote_description = std::move(pending_remote_description_);
2716 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717 }
Steve Anton8a006912017-12-04 15:25:56 -08002718 // The session description to apply now must be accessed by
2719 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002720 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002721
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002722 // Report statistics about any use of simulcast.
2723 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2724 *remote_description()->description());
2725
Zhi Huange830e682018-03-30 10:48:35 -07002726 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2727 if (!error.ok()) {
2728 return error;
2729 }
Steve Anton8a006912017-12-04 15:25:56 -08002730 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002731 if (IsUnifiedPlan()) {
2732 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002733 cricket::CS_REMOTE, *remote_description(), local_description(),
2734 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002735 if (!error.ok()) {
2736 return error;
2737 }
Steve Antondcc3c022017-12-22 16:02:54 -08002738 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002739 // Media channels will be created only when offer is set. These may use new
2740 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002741 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002742 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002743 // description is applied. Restore back to old description.
2744 RTCError error = CreateChannels(*remote_description()->description());
2745 if (!error.ok()) {
2746 return error;
2747 }
2748 }
Steve Antondcc3c022017-12-22 16:02:54 -08002749 // Remove unused channels if MediaContentDescription is rejected.
2750 RemoveUnusedChannels(remote_description()->description());
2751 }
Steve Anton8a006912017-12-04 15:25:56 -08002752
Zhi Huange830e682018-03-30 10:48:35 -07002753 // NOTE: Candidates allocation will be initiated only when
2754 // SetLocalDescription is called.
2755 error = UpdateSessionState(type, cricket::CS_REMOTE,
2756 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002757 if (!error.ok()) {
2758 return error;
2759 }
2760
2761 if (local_description() &&
2762 !UseCandidatesInSessionDescription(remote_description())) {
2763 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2764 }
2765
2766 if (old_remote_description) {
2767 for (const cricket::ContentInfo& content :
2768 old_remote_description->description()->contents()) {
2769 // Check if this new SessionDescription contains new ICE ufrag and
2770 // password that indicates the remote peer requests an ICE restart.
2771 // TODO(deadbeef): When we start storing both the current and pending
2772 // remote description, this should reset pending_ice_restarts and compare
2773 // against the current description.
2774 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2775 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002776 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002777 pending_ice_restarts_.insert(content.name);
2778 }
2779 } else {
2780 // We retain all received candidates only if ICE is not restarted.
2781 // When ICE is restarted, all previous candidates belong to an old
2782 // generation and should not be kept.
2783 // TODO(deadbeef): This goes against the W3C spec which says the remote
2784 // description should only contain candidates from the last set remote
2785 // description plus any candidates added since then. We should remove
2786 // this once we're sure it won't break anything.
2787 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2788 old_remote_description, content.name, mutable_remote_description());
2789 }
2790 }
2791 }
2792
2793 if (session_error() != SessionError::kNone) {
2794 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2795 }
2796
2797 // Set the the ICE connection state to connecting since the connection may
2798 // become writable with peer reflexive candidates before any remote candidate
2799 // is signaled.
2800 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2801 // is to have a new signal the indicates a change in checking state from the
2802 // transport and expose a new checking() member from transport that can be
2803 // read to determine the current checking state. The existing SignalConnecting
2804 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002805 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002806 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002807 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2808 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2809 }
2810
deadbeefab9b2d12015-10-14 11:33:11 -07002811 // If setting the description decided our SSL role, allocate any necessary
2812 // SCTP sids.
2813 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002814 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002815 AllocateSctpSids(role);
2816 }
2817
Steve Antondcc3c022017-12-22 16:02:54 -08002818 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002819 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002820 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002821 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002822 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002823 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002824 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002825 const ContentInfo* content =
2826 FindMediaSectionForTransceiver(transceiver, remote_description());
2827 if (!content) {
2828 continue;
2829 }
2830 const MediaContentDescription* media_desc = content->media_description();
2831 RtpTransceiverDirection local_direction =
2832 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002833 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2834 // RTCSessionDescription: Set the associated remote streams given
2835 // transceiver.[[Receiver]], msids, addList, and removeList".
2836 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2837 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2838 std::vector<std::string> stream_ids;
2839 if (!media_desc->streams().empty()) {
2840 // The remote description has signaled the stream IDs.
2841 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002842 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002843 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2844 << " (" << GetStreamIdsString(stream_ids) << ").";
2845 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2846 stream_ids, &added_streams,
2847 &removed_streams);
2848 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2849 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2850 // and transceiver's current direction is neither sendrecv nor recvonly,
2851 // process the addition of a remote track for the media description.
2852 if (!transceiver->fired_direction() ||
2853 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2854 RTC_LOG(LS_INFO)
2855 << "Processing the addition of a remote track for MID="
2856 << content->name << ".";
2857 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002858 }
Steve Antondcc3c022017-12-22 16:02:54 -08002859 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002860 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002861 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2862 // removal of a remote track for the media description, given transceiver,
2863 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002864 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002865 (transceiver->fired_direction() &&
2866 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2867 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2868 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002869 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002870 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002871 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002872 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002873 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002874 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002875 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002876 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002877 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002878 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2879 if (transceiver->mid()) {
2880 auto dtls_transport =
2881 LookupDtlsTransportByMidInternal(*transceiver->mid());
2882 transceiver->internal()->sender_internal()->set_transport(
2883 dtls_transport);
2884 transceiver->internal()->receiver_internal()->set_transport(
2885 dtls_transport);
2886 }
Steve Antondcc3c022017-12-22 16:02:54 -08002887 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002888 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002889 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002890 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002891 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2892 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002893 transceiver->Stop();
2894 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002895 if (!content->rejected &&
2896 RtpTransceiverDirectionHasRecv(local_direction)) {
2897 // Set ssrc to 0 in the case of an unsignalled ssrc.
2898 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002899 if (!media_desc->streams().empty() &&
2900 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002901 ssrc = media_desc->streams()[0].first_ssrc();
2902 }
2903 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002904 }
Steve Antondcc3c022017-12-22 16:02:54 -08002905 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002906 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002907 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002908 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002909 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002910 observer->OnTrack(transceiver);
2911 observer->OnAddTrack(transceiver->receiver(),
2912 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002913 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002914 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002915 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002916 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002917 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002918 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002919 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002920 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002921 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002922 }
Steve Antondcc3c022017-12-22 16:02:54 -08002923 }
2924
Henrik Boströmfdb92012017-11-09 19:55:44 +01002925 const cricket::ContentInfo* audio_content =
2926 GetFirstAudioContent(remote_description()->description());
2927 const cricket::ContentInfo* video_content =
2928 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002929 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002930 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002931 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002932 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002933 const cricket::RtpDataContentDescription* rtp_data_desc =
2934 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002935
2936 // Check if the descriptions include streams, just in case the peer supports
2937 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002938 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002939 (audio_desc && !audio_desc->streams().empty()) ||
2940 (video_desc && !video_desc->streams().empty())) {
2941 remote_peer_supports_msid_ = true;
2942 }
deadbeefab9b2d12015-10-14 11:33:11 -07002943
2944 // We wait to signal new streams until we finish processing the description,
2945 // since only at that point will new streams have all their tracks.
2946 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2947
Steve Antondcc3c022017-12-22 16:02:54 -08002948 if (!IsUnifiedPlan()) {
2949 // TODO(steveanton): When removing RTP senders/receivers in response to a
2950 // rejected media section, there is some cleanup logic that expects the
2951 // voice/ video channel to still be set. But in this method the voice/video
2952 // channel would have been destroyed by the SetRemoteDescription caller
2953 // above so the cleanup that relies on them fails to run. The RemoveSenders
2954 // calls should be moved to right before the DestroyChannel calls to fix
2955 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002956
Steve Antondcc3c022017-12-22 16:02:54 -08002957 // Find all audio rtp streams and create corresponding remote AudioTracks
2958 // and MediaStreams.
2959 if (audio_content) {
2960 if (audio_content->rejected) {
2961 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2962 } else {
2963 bool default_audio_track_needed =
2964 !remote_peer_supports_msid_ &&
2965 RtpTransceiverDirectionHasSend(audio_desc->direction());
2966 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2967 default_audio_track_needed, audio_desc->type(),
2968 new_streams);
2969 }
deadbeeffaac4972015-11-12 15:33:07 -08002970 }
deadbeefab9b2d12015-10-14 11:33:11 -07002971
Steve Antondcc3c022017-12-22 16:02:54 -08002972 // Find all video rtp streams and create corresponding remote VideoTracks
2973 // and MediaStreams.
2974 if (video_content) {
2975 if (video_content->rejected) {
2976 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2977 } else {
2978 bool default_video_track_needed =
2979 !remote_peer_supports_msid_ &&
2980 RtpTransceiverDirectionHasSend(video_desc->direction());
2981 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2982 default_video_track_needed, video_desc->type(),
2983 new_streams);
2984 }
deadbeeffaac4972015-11-12 15:33:07 -08002985 }
deadbeefab9b2d12015-10-14 11:33:11 -07002986
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002987 // If this is an RTP data transport, update the DataChannels with the
2988 // information from the remote peer.
2989 if (rtp_data_desc) {
2990 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002991 }
deadbeefab9b2d12015-10-14 11:33:11 -07002992
Steve Antondcc3c022017-12-22 16:02:54 -08002993 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002994 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002995 for (size_t i = 0; i < new_streams->count(); ++i) {
2996 MediaStreamInterface* new_stream = new_streams->at(i);
2997 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002998 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002999 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3000 }
deadbeefab9b2d12015-10-14 11:33:11 -07003001
Steve Antondcc3c022017-12-22 16:02:54 -08003002 UpdateEndedRemoteMediaStreams();
3003 }
deadbeefab9b2d12015-10-14 11:33:11 -07003004
Henrik Boström79b69802019-07-18 11:16:56 +02003005 if (type == SdpType::kAnswer &&
3006 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3007 *current_local_description_)) {
3008 local_ice_credentials_to_replace_->ClearIceCredentials();
3009 }
3010
Steve Anton8a006912017-12-04 15:25:56 -08003011 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003012}
3013
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003014void PeerConnection::SetAssociatedRemoteStreams(
3015 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3016 const std::vector<std::string>& stream_ids,
3017 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3018 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3019 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3020 for (const std::string& stream_id : stream_ids) {
3021 rtc::scoped_refptr<MediaStreamInterface> stream =
3022 remote_streams_->find(stream_id);
3023 if (!stream) {
3024 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3025 MediaStream::Create(stream_id));
3026 remote_streams_->AddStream(stream);
3027 added_streams->push_back(stream);
3028 }
3029 media_streams.push_back(stream);
3030 }
3031 // Special case: "a=msid" missing, use random stream ID.
3032 if (media_streams.empty() &&
3033 !(remote_description()->description()->msid_signaling() &
3034 cricket::kMsidSignalingMediaSection)) {
3035 if (!missing_msid_default_stream_) {
3036 missing_msid_default_stream_ = MediaStreamProxy::Create(
3037 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3038 added_streams->push_back(missing_msid_default_stream_);
3039 }
3040 media_streams.push_back(missing_msid_default_stream_);
3041 }
3042 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3043 receiver->streams();
3044 // SetStreams() will add/remove the receiver's track to/from the streams. This
3045 // differs from the spec - the spec uses an "addList" and "removeList" to
3046 // update the stream-track relationships in a later step. We do this earlier,
3047 // changing the order of things, but the end-result is the same.
3048 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3049 // instead. https://crbug.com/webrtc/9480
3050 receiver->SetStreams(media_streams);
3051 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3052}
3053
Steve Anton0f5400a2018-07-17 14:25:36 -07003054void PeerConnection::ProcessRemovalOfRemoteTrack(
3055 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3056 transceiver,
3057 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3058 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3059 RTC_DCHECK(transceiver->mid());
3060 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3061 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003062 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003063 transceiver->internal()->receiver_internal()->streams();
3064 // This will remove the remote track from the streams.
3065 transceiver->internal()->receiver_internal()->set_stream_ids({});
3066 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003067 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3068}
3069
3070void PeerConnection::RemoveRemoteStreamsIfEmpty(
3071 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3072 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3073 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3074 // streams, see if the stream was removed by checking if this was the last
3075 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003076 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003077 if (remote_stream->GetAudioTracks().empty() &&
3078 remote_stream->GetVideoTracks().empty()) {
3079 remote_streams_->RemoveStream(remote_stream);
3080 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003081 }
3082 }
3083}
3084
Steve Antondcc3c022017-12-22 16:02:54 -08003085RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3086 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003087 const SessionDescriptionInterface& new_session,
3088 const SessionDescriptionInterface* old_local_description,
3089 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003090 RTC_DCHECK(IsUnifiedPlan());
3091
Steve Anton7464fca2018-01-19 11:10:37 -08003092 const cricket::ContentGroup* bundle_group = nullptr;
3093 if (new_session.GetType() == SdpType::kOffer) {
3094 auto bundle_group_or_error =
3095 GetEarlyBundleGroup(*new_session.description());
3096 if (!bundle_group_or_error.ok()) {
3097 return bundle_group_or_error.MoveError();
3098 }
3099 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003100 }
Steve Antondcc3c022017-12-22 16:02:54 -08003101
Steve Antondcc3c022017-12-22 16:02:54 -08003102 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003103 for (size_t i = 0; i < new_contents.size(); ++i) {
3104 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003105 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003106 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003107 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3108 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003109 const cricket::ContentInfo* old_local_content = nullptr;
3110 if (old_local_description &&
3111 i < old_local_description->description()->contents().size()) {
3112 old_local_content =
3113 &old_local_description->description()->contents()[i];
3114 }
3115 const cricket::ContentInfo* old_remote_content = nullptr;
3116 if (old_remote_description &&
3117 i < old_remote_description->description()->contents().size()) {
3118 old_remote_content =
3119 &old_remote_description->description()->contents()[i];
3120 }
Steve Antondcc3c022017-12-22 16:02:54 -08003121 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003122 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3123 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003124 if (!transceiver_or_error.ok()) {
3125 return transceiver_or_error.MoveError();
3126 }
3127 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003128 RTCError error =
3129 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3130 if (!error.ok()) {
3131 return error;
3132 }
3133 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003134 if (GetDataMid() && new_content.name != *GetDataMid()) {
3135 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003136 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3137 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003138 continue;
3139 }
3140 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3141 if (!error.ok()) {
3142 return error;
3143 }
Steve Antondcc3c022017-12-22 16:02:54 -08003144 } else {
3145 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3146 "Unknown section type.");
3147 }
3148 }
3149
3150 return RTCError::OK();
3151}
3152
3153RTCError PeerConnection::UpdateTransceiverChannel(
3154 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3155 transceiver,
3156 const cricket::ContentInfo& content,
3157 const cricket::ContentGroup* bundle_group) {
3158 RTC_DCHECK(IsUnifiedPlan());
3159 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003160 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003161 if (content.rejected) {
3162 if (channel) {
3163 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003164 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003165 }
3166 } else {
3167 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003168 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003169 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003170 } else {
Steve Anton69470252018-02-09 11:43:08 -08003171 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003172 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003173 }
3174 if (!channel) {
3175 LOG_AND_RETURN_ERROR(
3176 RTCErrorType::INTERNAL_ERROR,
3177 "Failed to create channel for mid=" + content.name);
3178 }
3179 transceiver->internal()->SetChannel(channel);
3180 }
3181 }
3182 return RTCError::OK();
3183}
3184
Steve Antonfa2260d2017-12-28 16:38:23 -08003185RTCError PeerConnection::UpdateDataChannel(
3186 cricket::ContentSource source,
3187 const cricket::ContentInfo& content,
3188 const cricket::ContentGroup* bundle_group) {
3189 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003190 // If data channels are disabled, ignore this media section. CreateAnswer
3191 // will take care of rejecting it.
3192 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003193 }
3194 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003195 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003196 DestroyDataChannel();
3197 } else {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003198 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
3199 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003200 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003201 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3202 "Failed to create data channel.");
3203 }
3204 }
3205 if (source == cricket::CS_REMOTE) {
3206 const MediaContentDescription* data_desc = content.media_description();
3207 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3208 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3209 }
3210 }
3211 }
3212 return RTCError::OK();
3213}
3214
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003215// This method will extract any send encodings that were sent by the remote
3216// connection. This is currently only relevant for Simulcast scenario (where
3217// the number of layers may be communicated by the server).
3218static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3219 const MediaContentDescription& desc) {
3220 if (!desc.HasSimulcast()) {
3221 return {};
3222 }
3223 std::vector<RtpEncodingParameters> result;
3224 const SimulcastDescription& simulcast = desc.simulcast_description();
3225
3226 // This is a remote description, the parameters we are after should appear
3227 // as receive streams.
3228 for (const auto& alternatives : simulcast.receive_layers()) {
3229 RTC_DCHECK(!alternatives.empty());
3230 // There is currently no way to specify or choose from alternatives.
3231 // We will always use the first alternative, which is the most preferred.
3232 const SimulcastLayer& layer = alternatives[0];
3233 RtpEncodingParameters parameters;
3234 parameters.rid = layer.rid;
3235 parameters.active = !layer.is_paused;
3236 result.push_back(parameters);
3237 }
3238
3239 return result;
3240}
3241
3242static RTCError UpdateSimulcastLayerStatusInSender(
3243 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003244 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003245 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003246 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003247 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003248
3249 // The simulcast envelope cannot be changed, only the status of the streams.
3250 // So we will iterate over the send encodings rather than the layers.
3251 for (RtpEncodingParameters& encoding : parameters.encodings) {
3252 auto iter = std::find_if(layers.begin(), layers.end(),
3253 [&encoding](const SimulcastLayer& layer) {
3254 return layer.rid == encoding.rid;
3255 });
3256 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003257 if (iter == layers.end()) {
3258 disabled_layers.push_back(encoding.rid);
3259 continue;
3260 }
3261
3262 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003263 }
3264
Amit Hilbuch619b2942019-02-26 15:55:19 -08003265 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003266 if (result.ok()) {
3267 result = sender->DisableEncodingLayers(disabled_layers);
3268 }
3269
3270 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003271}
3272
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003273static bool SimulcastIsRejected(
3274 const ContentInfo* local_content,
3275 const MediaContentDescription& answer_media_desc) {
3276 bool simulcast_offered = local_content &&
3277 local_content->media_description() &&
3278 local_content->media_description()->HasSimulcast();
3279 bool simulcast_answered = answer_media_desc.HasSimulcast();
3280 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3281 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3282 return simulcast_offered && (!simulcast_answered || !rids_supported);
3283}
3284
Amit Hilbuch2297d332019-02-19 12:49:22 -08003285static RTCError DisableSimulcastInSender(
3286 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003287 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003288 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003289 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003290 return RTCError::OK();
3291 }
3292
Amit Hilbuch2297d332019-02-19 12:49:22 -08003293 std::vector<std::string> disabled_layers;
3294 std::transform(
3295 parameters.encodings.begin() + 1, parameters.encodings.end(),
3296 std::back_inserter(disabled_layers),
3297 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3298 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003299}
3300
Steve Antondcc3c022017-12-22 16:02:54 -08003301RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3302PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003303 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003304 size_t mline_index,
3305 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003306 const ContentInfo* old_local_content,
3307 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003308 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003309 // If this is an offer then the m= section might be recycled. If the m=
3310 // section is being recycled (defined as: rejected in the current local or
3311 // remote description and not rejected in new description), dissociate the
3312 // currently associated RtpTransceiver by setting its mid property to null,
3313 // and discard the mapping between the transceiver and its m= section index.
3314 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3315 old_remote_content)) {
3316 // We want to dissociate the transceiver that has the rejected mid.
3317 const std::string& old_mid =
3318 (old_local_content && old_local_content->rejected)
3319 ? old_local_content->name
3320 : old_remote_content->name;
3321 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003322 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003323 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3324 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003325 old_transceiver->internal()->set_mid(absl::nullopt);
3326 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003327 }
3328 }
3329 const MediaContentDescription* media_desc = content.media_description();
3330 auto transceiver = GetAssociatedTransceiver(content.name);
3331 if (source == cricket::CS_LOCAL) {
3332 // Find the RtpTransceiver that corresponds to this m= section, using the
3333 // mapping between transceivers and m= section indices established when
3334 // creating the offer.
3335 if (!transceiver) {
3336 transceiver = GetTransceiverByMLineIndex(mline_index);
3337 }
3338 if (!transceiver) {
3339 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3340 "Unknown transceiver");
3341 }
3342 } else {
3343 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3344 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3345 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003346 // When simulcast is requested, a transceiver cannot be associated because
3347 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003348 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003349 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3350 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003351 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3352 }
3353 // If no RtpTransceiver was found in the previous step, create one with a
3354 // recvonly direction.
3355 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003356 RTC_LOG(LS_INFO) << "Adding "
3357 << cricket::MediaTypeToString(media_desc->type())
3358 << " transceiver for MID=" << content.name
3359 << " at i=" << mline_index
3360 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003361 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003362 std::vector<RtpEncodingParameters> send_encodings =
3363 GetSendEncodingsFromRemoteDescription(*media_desc);
3364 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3365 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003366 std::string receiver_id;
3367 if (!media_desc->streams().empty()) {
3368 receiver_id = media_desc->streams()[0].id;
3369 } else {
3370 receiver_id = rtc::CreateRandomUuid();
3371 }
3372 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003373 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003374 transceiver->internal()->set_direction(
3375 RtpTransceiverDirection::kRecvOnly);
3376 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003377
3378 // Check if the offer indicated simulcast but the answer rejected it.
3379 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003380 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003381 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003382 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003383 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003384 if (!error.ok()) {
3385 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3386 return std::move(error);
3387 }
3388 }
Steve Antondcc3c022017-12-22 16:02:54 -08003389 }
3390 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003391 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003392 LOG_AND_RETURN_ERROR(
3393 RTCErrorType::INVALID_PARAMETER,
3394 "Transceiver type does not match media description type.");
3395 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003396 if (media_desc->HasSimulcast()) {
3397 std::vector<SimulcastLayer> layers =
3398 source == cricket::CS_LOCAL
3399 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3400 : media_desc->simulcast_description()
3401 .receive_layers()
3402 .GetAllLayers();
3403 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003404 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003405 if (!error.ok()) {
3406 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3407 return std::move(error);
3408 }
3409 }
Steve Antondcc3c022017-12-22 16:02:54 -08003410 // Associate the found or created RtpTransceiver with the m= section by
3411 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3412 // section, and establish a mapping between the transceiver and the index of
3413 // the m= section.
3414 transceiver->internal()->set_mid(content.name);
3415 transceiver->internal()->set_mline_index(mline_index);
3416 return std::move(transceiver);
3417}
3418
3419rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3420PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3421 RTC_DCHECK(IsUnifiedPlan());
3422 for (auto transceiver : transceivers_) {
3423 if (transceiver->mid() == mid) {
3424 return transceiver;
3425 }
3426 }
3427 return nullptr;
3428}
3429
3430rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3431PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3432 RTC_DCHECK(IsUnifiedPlan());
3433 for (auto transceiver : transceivers_) {
3434 if (transceiver->internal()->mline_index() == mline_index) {
3435 return transceiver;
3436 }
3437 }
3438 return nullptr;
3439}
3440
3441rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3442PeerConnection::FindAvailableTransceiverToReceive(
3443 cricket::MediaType media_type) const {
3444 RTC_DCHECK(IsUnifiedPlan());
3445 // From JSEP section 5.10 (Applying a Remote Description):
3446 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3447 // the same type that were added to the PeerConnection by addTrack and are not
3448 // associated with any m= section and are not stopped, find the first such
3449 // RtpTransceiver.
3450 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003451 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003452 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3453 !transceiver->stopped()) {
3454 return transceiver;
3455 }
3456 }
3457 return nullptr;
3458}
3459
Steve Antoned10bd92017-12-05 10:52:59 -08003460const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3461 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3462 transceiver,
3463 const SessionDescriptionInterface* sdesc) const {
3464 RTC_DCHECK(transceiver);
3465 RTC_DCHECK(sdesc);
3466 if (IsUnifiedPlan()) {
3467 if (!transceiver->internal()->mid()) {
3468 // This transceiver is not associated with a media section yet.
3469 return nullptr;
3470 }
3471 return sdesc->description()->GetContentByName(
3472 *transceiver->internal()->mid());
3473 } else {
3474 // Plan B only allows at most one audio and one video section, so use the
3475 // first media section of that type.
3476 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003477 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003478 }
3479}
3480
deadbeef46c73892016-11-16 19:42:04 -08003481PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003482 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003483 return configuration_;
3484}
3485
deadbeef293e9262017-01-11 12:28:30 -08003486bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3487 RTCError* error) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003488 RTCError result = SetConfiguration(configuration);
3489 bool success = result.ok();
3490 if (error) {
3491 *error = std::move(result);
3492 }
3493 return success;
3494}
3495
3496RTCError PeerConnection::SetConfiguration(
3497 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003498 RTC_DCHECK_RUN_ON(signaling_thread());
3499 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003500 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003501 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003502 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3503 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003504 }
3505
Qingsi Wanga2d60672018-04-11 16:57:45 -07003506 // According to JSEP, after setLocalDescription, changing the candidate pool
3507 // size is not allowed, and changing the set of ICE servers will not result
3508 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003509 if (local_description() && configuration.ice_candidate_pool_size !=
3510 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003511 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3512 "Can't change candidate pool size after calling "
3513 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003514 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003515
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003516 if (local_description() &&
3517 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3519 "Can't change media_transport after calling "
3520 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003521 }
3522
3523 if (remote_description() &&
3524 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003525 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3526 "Can't change media_transport after calling "
3527 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003528 }
3529
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003530 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003531 configuration.use_media_transport_for_data_channels !=
3532 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003533 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3534 "Can't change media_transport_for_data_channels "
3535 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003536 }
3537
3538 if (remote_description() &&
3539 configuration.use_media_transport_for_data_channels !=
3540 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003541 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3542 "Can't change media_transport_for_data_channels "
3543 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003544 }
3545
3546 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003547 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003548 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3549 "Can't change crypto_options after calling "
3550 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003551 }
3552
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003553 if (local_description() && configuration.use_datagram_transport !=
3554 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003555 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3556 "Can't change use_datagram_transport "
3557 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003558 }
3559
3560 if (remote_description() && configuration.use_datagram_transport !=
3561 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003562 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3563 "Can't change use_datagram_transport "
3564 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003565 }
3566
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003567 if (local_description() &&
3568 configuration.use_datagram_transport_for_data_channels !=
3569 configuration_.use_datagram_transport_for_data_channels) {
3570 LOG_AND_RETURN_ERROR(
3571 RTCErrorType::INVALID_MODIFICATION,
3572 "Can't change use_datagram_transport_for_data_channels "
3573 "after calling SetLocalDescription.");
3574 }
3575
3576 if (remote_description() &&
3577 configuration.use_datagram_transport_for_data_channels !=
3578 configuration_.use_datagram_transport_for_data_channels) {
3579 LOG_AND_RETURN_ERROR(
3580 RTCErrorType::INVALID_MODIFICATION,
3581 "Can't change use_datagram_transport_for_data_channels "
3582 "after calling SetRemoteDescription.");
3583 }
3584
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003585 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003586 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003587 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003588 *configuration.use_datagram_transport) ||
3589 (configuration.use_datagram_transport_for_data_channels &&
3590 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003591 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3592 << "Media transport requires MaxBundle policy.";
3593 }
3594
deadbeef293e9262017-01-11 12:28:30 -08003595 // The simplest (and most future-compatible) way to tell if the config was
3596 // modified in an invalid way is to copy each property we do support
3597 // modifying, then use operator==. There are far more properties we don't
3598 // support modifying than those we do, and more could be added.
3599 RTCConfiguration modified_config = configuration_;
3600 modified_config.servers = configuration.servers;
3601 modified_config.type = configuration.type;
3602 modified_config.ice_candidate_pool_size =
3603 configuration.ice_candidate_pool_size;
3604 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003605 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3606 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003607 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003608 modified_config.ice_check_interval_strong_connectivity =
3609 configuration.ice_check_interval_strong_connectivity;
3610 modified_config.ice_check_interval_weak_connectivity =
3611 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003612 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3613 modified_config.ice_unwritable_min_checks =
3614 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003615 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003616 modified_config.stun_candidate_keepalive_interval =
3617 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003618 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003619 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003620 modified_config.active_reset_srtp_params =
3621 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003622 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003623 modified_config.use_media_transport_for_data_channels =
3624 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003625 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003626 modified_config.use_datagram_transport_for_data_channels =
3627 configuration.use_datagram_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003628 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003629 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3630 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003631 }
3632
Steve Anton038834f2017-07-14 15:59:59 -07003633 // Validate the modified configuration.
3634 RTCError validate_error = ValidateConfiguration(modified_config);
3635 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003636 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003637 }
3638
deadbeef293e9262017-01-11 12:28:30 -08003639 // Note that this isn't possible through chromium, since it's an unsigned
3640 // short in WebIDL.
3641 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003642 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003643 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003644 }
3645
3646 // Parse ICE servers before hopping to network thread.
3647 cricket::ServerAddresses stun_servers;
3648 std::vector<cricket::RelayServerConfig> turn_servers;
3649 RTCErrorType parse_error =
3650 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3651 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003652 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003653 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003654 // Note if STUN or TURN servers were supplied.
3655 if (!stun_servers.empty()) {
3656 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3657 }
3658 if (!turn_servers.empty()) {
3659 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3660 }
deadbeef293e9262017-01-11 12:28:30 -08003661
3662 // In theory this shouldn't fail.
3663 if (!network_thread()->Invoke<bool>(
3664 RTC_FROM_HERE,
3665 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3666 stun_servers, turn_servers, modified_config.type,
3667 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003668 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003669 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003670 modified_config.stun_candidate_keepalive_interval,
3671 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003672 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3673 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003674 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003675
deadbeefd1a38b52016-12-10 13:15:33 -08003676 // As described in JSEP, calling setConfiguration with new ICE servers or
3677 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3678 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003679 if (modified_config.servers != configuration_.servers ||
3680 modified_config.type != configuration_.type ||
3681 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003682 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003683 }
skvladd1f5fda2017-02-03 16:54:05 -08003684
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003685 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003686
3687 use_datagram_transport_ = datagram_transport_config_.enabled &&
3688 modified_config.use_datagram_transport.value_or(
3689 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003690 use_datagram_transport_for_data_channels_ =
3691 datagram_transport_data_channel_config_.enabled &&
3692 modified_config.use_datagram_transport_for_data_channels.value_or(
3693 datagram_transport_data_channel_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003694 transport_controller_->SetMediaTransportSettings(
3695 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003696 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003697 use_datagram_transport_, use_datagram_transport_for_data_channels_);
skvladd1f5fda2017-02-03 16:54:05 -08003698
Zhi Huangb57e1692018-06-12 11:41:11 -07003699 if (configuration_.active_reset_srtp_params !=
3700 modified_config.active_reset_srtp_params) {
3701 transport_controller_->SetActiveResetSrtpParams(
3702 modified_config.active_reset_srtp_params);
3703 }
3704
deadbeef293e9262017-01-11 12:28:30 -08003705 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003706 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003707 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003708}
3709
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003710bool PeerConnection::AddIceCandidate(
3711 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003712 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003713 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003714 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003715 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003716 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003717 return false;
3718 }
Steve Antond25da372017-11-06 14:50:29 -08003719
3720 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003721 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003722 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003723 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003724 return false;
3725 }
3726
3727 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003728 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003729 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003730 return false;
3731 }
3732
3733 bool valid = false;
3734 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3735 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003736 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003737 return false;
3738 }
3739
3740 // Add this candidate to the remote session description.
3741 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003742 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003743 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003744 return false;
3745 }
3746
3747 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003748 bool result = UseCandidate(ice_candidate);
3749 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003750 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003751 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3752 } else {
3753 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3754 }
3755 return result;
Steve Antond25da372017-11-06 14:50:29 -08003756 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003757 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003758 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003759 return true;
3760 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003761}
3762
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003763bool PeerConnection::RemoveIceCandidates(
3764 const std::vector<cricket::Candidate>& candidates) {
3765 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003766 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003767 if (IsClosed()) {
3768 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3769 return false;
3770 }
3771
Steve Antond25da372017-11-06 14:50:29 -08003772 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003773 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3774 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003775 return false;
3776 }
3777
3778 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003779 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003780 return false;
3781 }
3782
3783 size_t number_removed =
3784 mutable_remote_description()->RemoveCandidates(candidates);
3785 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003786 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003787 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003788 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003789 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003790 }
3791
3792 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003793 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3794 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003795 RTC_LOG(LS_ERROR)
3796 << "RemoveIceCandidates: Error when removing remote candidates: "
3797 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003798 }
3799 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003800}
3801
Niels Möller0c4f7be2018-05-07 14:01:37 +02003802RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003803 if (!worker_thread()->IsCurrent()) {
3804 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003805 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003806 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003807 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003808
Niels Möller0c4f7be2018-05-07 14:01:37 +02003809 const bool has_min = bitrate.min_bitrate_bps.has_value();
3810 const bool has_start = bitrate.start_bitrate_bps.has_value();
3811 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003812 if (has_min && *bitrate.min_bitrate_bps < 0) {
3813 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3814 "min_bitrate_bps <= 0");
3815 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003816 if (has_start) {
3817 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003818 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003819 "start_bitrate_bps < min_bitrate_bps");
3820 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003821 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3822 "curent_bitrate_bps < 0");
3823 }
3824 }
3825 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003826 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003827 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003828 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003829 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3830 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3831 "max_bitrate_bps < min_bitrate_bps");
3832 } else if (*bitrate.max_bitrate_bps < 0) {
3833 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3834 "max_bitrate_bps < 0");
3835 }
3836 }
3837
zstein4b979802017-06-02 14:37:37 -07003838 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003839 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003840
3841 return RTCError::OK();
3842}
3843
henrika5f6bf242017-11-01 11:06:56 +01003844void PeerConnection::SetAudioPlayout(bool playout) {
3845 if (!worker_thread()->IsCurrent()) {
3846 worker_thread()->Invoke<void>(
3847 RTC_FROM_HERE,
3848 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3849 return;
3850 }
3851 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003852 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003853 audio_state->SetPlayout(playout);
3854}
3855
3856void PeerConnection::SetAudioRecording(bool recording) {
3857 if (!worker_thread()->IsCurrent()) {
3858 worker_thread()->Invoke<void>(
3859 RTC_FROM_HERE,
3860 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3861 return;
3862 }
3863 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003864 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003865 audio_state->SetRecording(recording);
3866}
3867
Steve Anton8c0f7a72017-10-03 10:03:10 -07003868std::unique_ptr<rtc::SSLCertificate>
3869PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003870 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3871 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003872 return nullptr;
3873 }
Steve Antonf25303e2018-10-16 15:23:31 -07003874 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003875}
3876
Zhi Huang70b820f2018-01-27 14:16:15 -08003877std::unique_ptr<rtc::SSLCertChain>
3878PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003879 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003880 auto audio_transceiver = GetFirstAudioTransceiver();
3881 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003882 return nullptr;
3883 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003884 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003885 audio_transceiver->internal()->channel()->transport_name());
3886}
3887
3888rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3889PeerConnection::GetFirstAudioTransceiver() const {
3890 for (auto transceiver : transceivers_) {
3891 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3892 return transceiver;
3893 }
3894 }
3895 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003896}
3897
Bjorn Tereliusde939432017-11-20 17:38:14 +01003898bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3899 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003900 // TODO(eladalon): In C++14, this can be done with a lambda.
3901 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003902 bool operator()() {
3903 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3904 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003905 PeerConnection* const pc;
3906 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003907 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003908 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003909 return worker_thread()->Invoke<bool>(
3910 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003911}
3912
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003913bool PeerConnection::StartRtcEventLog(
3914 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003915 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3916 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3917 output_period_ms = 5000;
3918 }
3919 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003920}
3921
ivoc14d5dbe2016-07-04 07:06:55 -07003922void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003923 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003924 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3925}
3926
Harald Alvestrandad88c882018-11-28 16:47:46 +01003927rtc::scoped_refptr<DtlsTransportInterface>
3928PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003929 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003930 return transport_controller_->LookupDtlsTransportByMid(mid);
3931}
3932
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003933rtc::scoped_refptr<DtlsTransport>
3934PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003935 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003936 return transport_controller_->LookupDtlsTransportByMid(mid);
3937}
3938
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003939rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3940 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003941 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003942 return sctp_transport_;
3943}
3944
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003945const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003946 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003947 return pending_local_description_ ? pending_local_description_.get()
3948 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003949}
3950
3951const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003952 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003953 return pending_remote_description_ ? pending_remote_description_.get()
3954 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003955}
3956
deadbeeffe4a8a42016-12-20 17:56:17 -08003957const SessionDescriptionInterface* PeerConnection::current_local_description()
3958 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003959 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003960 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003961}
3962
3963const SessionDescriptionInterface* PeerConnection::current_remote_description()
3964 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003965 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003966 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003967}
3968
3969const SessionDescriptionInterface* PeerConnection::pending_local_description()
3970 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003971 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003972 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003973}
3974
3975const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3976 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003977 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003978 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003979}
3980
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003981void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003982 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003983 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003984 // Update stats here so that we have the most recent stats for tracks and
3985 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003986 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003987
Steve Anton75737c02017-11-06 10:37:17 -08003988 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003989 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003990
Mirko Bonadei739baf02019-01-27 17:29:42 +01003991 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003992 transceiver->Stop();
3993 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003994
3995 // Ensure that all asynchronous stats requests are completed before destroying
3996 // the transport controller below.
3997 if (stats_collector_) {
3998 stats_collector_->WaitForPendingRequest();
3999 }
4000
4001 // Don't destroy BaseChannels until after stats has been cleaned up so that
4002 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004003 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004004
Qingsi Wang93a84392018-01-30 17:13:09 -08004005 // The event log is used in the transport controller, which must be outlived
4006 // by the former. CreateOffer by the peer connection is implemented
4007 // asynchronously and if the peer connection is closed without resetting the
4008 // WebRTC session description factory, the session description factory would
4009 // call the transport controller.
4010 webrtc_session_desc_factory_.reset();
4011 transport_controller_.reset();
4012
deadbeef42a42632017-03-10 15:18:00 -08004013 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004014 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4015 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004016
Steve Anton978b8762017-09-29 12:15:02 -07004017 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004018 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004019 call_.reset();
4020 // The event log must outlive call (and any other object that uses it).
4021 event_log_.reset();
4022 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004023 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004024 // The .h file says that observer can be discarded after close() returns.
4025 // Make sure this is true.
4026 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004027}
4028
Steve Antonad182762018-09-05 20:22:40 +00004029void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004030 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004031 switch (msg->message_id) {
4032 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4033 SetSessionDescriptionMsg* param =
4034 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4035 param->observer->OnSuccess();
4036 delete param;
4037 break;
4038 }
4039 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4040 SetSessionDescriptionMsg* param =
4041 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4042 param->observer->OnFailure(std::move(param->error));
4043 delete param;
4044 break;
4045 }
4046 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4047 CreateSessionDescriptionMsg* param =
4048 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4049 param->observer->OnFailure(std::move(param->error));
4050 delete param;
4051 break;
4052 }
4053 case MSG_GETSTATS: {
4054 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4055 StatsReports reports;
4056 stats_->GetStats(param->track, &reports);
4057 param->observer->OnComplete(reports);
4058 delete param;
4059 break;
4060 }
4061 case MSG_FREE_DATACHANNELS: {
4062 sctp_data_channels_to_free_.clear();
4063 break;
4064 }
4065 case MSG_REPORT_USAGE_PATTERN: {
4066 ReportUsagePattern();
4067 break;
4068 }
4069 default:
4070 RTC_NOTREACHED() << "Not implemented";
4071 break;
4072 }
4073}
4074
Steve Antonafb0bb72018-02-20 11:35:37 -08004075cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4076 RTC_DCHECK(!IsUnifiedPlan());
4077 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4078 GetAudioTransceiver()->internal()->channel());
4079 if (voice_channel) {
4080 return voice_channel->media_channel();
4081 } else {
4082 return nullptr;
4083 }
4084}
4085
4086cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4087 RTC_DCHECK(!IsUnifiedPlan());
4088 auto* video_channel = static_cast<cricket::VideoChannel*>(
4089 GetVideoTransceiver()->internal()->channel());
4090 if (video_channel) {
4091 return video_channel->media_channel();
4092 } else {
4093 return nullptr;
4094 }
4095}
4096
Steve Anton4171afb2017-11-20 10:20:22 -08004097void PeerConnection::CreateAudioReceiver(
4098 MediaStreamInterface* stream,
4099 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004100 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4101 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004102 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4103 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004104 auto* audio_receiver = new AudioRtpReceiver(
4105 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004106 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004107 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4108 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4109 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004110 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004111 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004112 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004113}
4114
Steve Anton4171afb2017-11-20 10:20:22 -08004115void PeerConnection::CreateVideoReceiver(
4116 MediaStreamInterface* stream,
4117 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004118 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4119 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004120 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4121 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004122 auto* video_receiver = new VideoRtpReceiver(
4123 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004124 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004125 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4126 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4127 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004128 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004129 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004130 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004131}
4132
deadbeef70ab1a12015-09-28 16:53:55 -07004133// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4134// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004135rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004136 const RtpSenderInfo& remote_sender_info) {
4137 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4138 if (!receiver) {
4139 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4140 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004141 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004142 }
Steve Anton4171afb2017-11-20 10:20:22 -08004143 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4144 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4145 } else {
4146 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4147 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004148 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004149}
4150
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004151void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4152 MediaStreamInterface* stream) {
4153 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004154 RTC_DCHECK(track);
4155 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004156 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004157 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004158 // We already have a sender for this track, so just change the stream_id
4159 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004160 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004161 return;
4162 }
4163
4164 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004165 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004166 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004167 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004168 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004169 // If the sender has already been configured in SDP, we call SetSsrc,
4170 // which will connect the sender to the underlying transport. This can
4171 // occur if a local session description that contains the ID of the sender
4172 // is set before AddStream is called. It can also occur if the local
4173 // session description is not changed and RemoveStream is called, and
4174 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004175 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004176 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004177 if (sender_info) {
4178 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004179 }
4180}
4181
4182// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4183// indefinitely, when we have unified plan SDP.
4184void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4185 MediaStreamInterface* stream) {
4186 RTC_DCHECK(!IsClosed());
4187 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004188 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004189 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4190 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004191 return;
4192 }
Steve Anton4171afb2017-11-20 10:20:22 -08004193 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004194}
4195
4196void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4197 MediaStreamInterface* stream) {
4198 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004199 RTC_DCHECK(track);
4200 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004201 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004202 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004203 // We already have a sender for this track, so just change the stream_id
4204 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004205 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004206 return;
4207 }
4208
4209 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004210 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004211 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004212 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004213 GetVideoTransceiver()->internal()->AddSender(new_sender);
4214 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004215 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004216 if (sender_info) {
4217 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004218 }
4219}
4220
4221void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4222 MediaStreamInterface* stream) {
4223 RTC_DCHECK(!IsClosed());
4224 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004225 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004226 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4227 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004228 return;
4229 }
Steve Anton4171afb2017-11-20 10:20:22 -08004230 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004231}
4232
Steve Antonba818672017-11-06 10:21:57 -08004233void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004234 if (ice_connection_state_ == new_state) {
4235 return;
4236 }
4237
deadbeefcbecd352015-09-23 11:50:27 -07004238 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004239 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004240 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004241 return;
4242 }
Steve Antonba818672017-11-06 10:21:57 -08004243
Mirko Bonadei675513b2017-11-09 11:09:25 +01004244 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4245 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004246 RTC_DCHECK(ice_connection_state_ !=
4247 PeerConnectionInterface::kIceConnectionClosed);
4248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004249 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004250 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004251}
4252
Alex Loiko9289eda2018-11-23 16:18:59 +00004253void PeerConnection::SetStandardizedIceConnectionState(
4254 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004255 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004256 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004257 }
4258
4259 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004260 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004261 }
4262
4263 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4264 << standardized_ice_connection_state_ << " => " << new_state;
4265
Alex Loiko9289eda2018-11-23 16:18:59 +00004266 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004267 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004268}
4269
Jonas Olsson635474e2018-10-18 15:58:17 +02004270void PeerConnection::SetConnectionState(
4271 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004272 if (connection_state_ == new_state)
4273 return;
4274 if (IsClosed())
4275 return;
4276 connection_state_ = new_state;
4277 Observer()->OnConnectionChange(new_state);
4278}
4279
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004280void PeerConnection::OnIceGatheringChange(
4281 PeerConnectionInterface::IceGatheringState new_state) {
4282 if (IsClosed()) {
4283 return;
4284 }
4285 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004286 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004287}
4288
jbauch81bf7b02017-03-25 08:31:12 -07004289void PeerConnection::OnIceCandidate(
4290 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004291 if (IsClosed()) {
4292 return;
4293 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004294 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004295 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004296}
4297
Eldar Relloda13ea22019-06-01 12:23:43 +03004298void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4299 const std::string& url,
4300 int error_code,
4301 const std::string& error_text) {
4302 if (IsClosed()) {
4303 return;
4304 }
4305 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4306}
4307
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004308void PeerConnection::OnIceCandidatesRemoved(
4309 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004310 if (IsClosed()) {
4311 return;
4312 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004313 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004314}
4315
Alex Drake00c7ecf2019-08-06 10:54:47 -07004316void PeerConnection::OnSelectedCandidatePairChanged(
4317 const cricket::CandidatePairChangeEvent& event) {
4318 if (IsClosed()) {
4319 return;
4320 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004321
Alex Drake00c7ecf2019-08-06 10:54:47 -07004322 Observer()->OnIceSelectedCandidatePairChanged(event);
4323}
4324
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004325void PeerConnection::ChangeSignalingState(
4326 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004327 if (signaling_state_ == signaling_state) {
4328 return;
4329 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004330 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4331 << GetSignalingStateString(signaling_state_)
4332 << " New state: "
4333 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004334 signaling_state_ = signaling_state;
4335 if (signaling_state == kClosed) {
4336 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004337 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004338 standardized_ice_connection_state_ =
4339 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004340 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4341 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004342 if (ice_gathering_state_ != kIceGatheringComplete) {
4343 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004344 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004345 }
4346 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004347 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004348}
4349
deadbeefeb459812015-12-15 19:24:43 -08004350void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4351 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004352 if (IsClosed()) {
4353 return;
4354 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004355 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004356 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004357}
4358
deadbeefeb459812015-12-15 19:24:43 -08004359void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4360 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004361 if (IsClosed()) {
4362 return;
4363 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004364 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004365 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004366}
4367
4368void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4369 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004370 if (IsClosed()) {
4371 return;
4372 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004373 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004374 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004375}
4376
4377void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4378 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004379 if (IsClosed()) {
4380 return;
4381 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004382 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004383 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004384}
4385
Henrik Boström31638672017-11-23 17:48:32 +01004386void PeerConnection::PostSetSessionDescriptionSuccess(
4387 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004388 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4389 signaling_thread()->Post(RTC_FROM_HERE, this,
4390 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004391}
4392
deadbeefab9b2d12015-10-14 11:33:11 -07004393void PeerConnection::PostSetSessionDescriptionFailure(
4394 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004395 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004396 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004397 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4398 msg->error = std::move(error);
4399 signaling_thread()->Post(RTC_FROM_HERE, this,
4400 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004401}
4402
4403void PeerConnection::PostCreateSessionDescriptionFailure(
4404 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004405 RTCError error) {
4406 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004407 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4408 msg->error = std::move(error);
4409 signaling_thread()->Post(RTC_FROM_HERE, this,
4410 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004411}
4412
zhihuang1c378ed2017-08-17 14:10:50 -07004413void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004414 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004415 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004416 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004417
Steve Antondcc3c022017-12-22 16:02:54 -08004418 if (IsUnifiedPlan()) {
4419 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4420 } else {
4421 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4422 }
4423
Steve Antonfa2260d2017-12-28 16:38:23 -08004424 // Intentionally unset the data channel type for RTP data channel with the
4425 // second condition. Otherwise the RTP data channels would be successfully
4426 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4427 // when building with chromium. We want to leave RTP data channels broken, so
4428 // people won't try to use them.
4429 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4430 session_options->data_channel_type = data_channel_type();
4431 }
4432
Steve Antondcc3c022017-12-22 16:02:54 -08004433 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004434 bool ice_restart = offer_answer_options.ice_restart ||
4435 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004436 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004437 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004438 options.transport_options.enable_ice_renomination =
4439 configuration_.enable_ice_renomination;
4440 }
4441
4442 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004443 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004444 session_options->pooled_ice_credentials =
4445 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4446 RTC_FROM_HERE,
4447 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4448 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004449 session_options->offer_extmap_allow_mixed =
4450 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004451
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004452 if (configuration_.use_media_transport ||
4453 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004454 session_options->media_transport_settings =
4455 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4456 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004457
4458 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004459 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004460 for (auto& options : session_options->media_description_options) {
4461 options.transport_options.opaque_parameters =
4462 transport_controller_->GetTransportParameters(options.mid);
4463 }
4464 }
4465
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004466 // Allow fallback for using obsolete SCTP syntax.
4467 // Note that the default in |session_options| is true, while
4468 // the default in |options| is false.
4469 session_options->use_obsolete_sctp_sdp =
4470 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004471}
4472
4473void PeerConnection::GetOptionsForPlanBOffer(
4474 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4475 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004476 // Figure out transceiver directional preferences.
4477 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4478 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4479
4480 // By default, generate sendrecv/recvonly m= sections.
4481 bool recv_audio = true;
4482 bool recv_video = true;
4483
4484 // By default, only offer a new m= section if we have media to send with it.
4485 bool offer_new_audio_description = send_audio;
4486 bool offer_new_video_description = send_video;
4487 bool offer_new_data_description = HasDataChannels();
4488
4489 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004490 if (offer_answer_options.offer_to_receive_audio !=
4491 RTCOfferAnswerOptions::kUndefined) {
4492 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004493 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004494 offer_new_audio_description ||
4495 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004496 }
Steve Antondcc3c022017-12-22 16:02:54 -08004497 if (offer_answer_options.offer_to_receive_video !=
4498 RTCOfferAnswerOptions::kUndefined) {
4499 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004500 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004501 offer_new_video_description ||
4502 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004503 }
4504
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004505 absl::optional<size_t> audio_index;
4506 absl::optional<size_t> video_index;
4507 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004508 // If a current description exists, generate m= sections in the same order,
4509 // using the first audio/video/data section that appears and rejecting
4510 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004511 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004512 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004513 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004514 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4515 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4516 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004517 }
4518
zhihuang1c378ed2017-08-17 14:10:50 -07004519 // Add audio/video/data m= sections to the end if needed.
4520 if (!audio_index && offer_new_audio_description) {
4521 session_options->media_description_options.push_back(
4522 cricket::MediaDescriptionOptions(
4523 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004524 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4525 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004526 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004527 }
zhihuang1c378ed2017-08-17 14:10:50 -07004528 if (!video_index && offer_new_video_description) {
4529 session_options->media_description_options.push_back(
4530 cricket::MediaDescriptionOptions(
4531 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004532 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4533 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004534 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004535 }
zhihuang1c378ed2017-08-17 14:10:50 -07004536 if (!data_index && offer_new_data_description) {
4537 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004538 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004539 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004540 }
4541
4542 cricket::MediaDescriptionOptions* audio_media_description_options =
4543 !audio_index ? nullptr
4544 : &session_options->media_description_options[*audio_index];
4545 cricket::MediaDescriptionOptions* video_media_description_options =
4546 !video_index ? nullptr
4547 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004548
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004549 AddPlanBRtpSenderOptions(GetSendersInternal(),
4550 audio_media_description_options,
4551 video_media_description_options,
4552 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004553}
4554
Steve Antondcc3c022017-12-22 16:02:54 -08004555static cricket::MediaDescriptionOptions
4556GetMediaDescriptionOptionsForTransceiver(
4557 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4558 transceiver,
4559 const std::string& mid) {
4560 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004561 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004562 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004563 media_description_options.codec_preferences =
4564 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004565 // This behavior is specified in JSEP. The gist is that:
4566 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4567 // sendrecv.
4568 // 2. If the MSID is included, then it must be included in any subsequent
4569 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004570 if (transceiver->stopped() ||
4571 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4572 !transceiver->internal()->has_ever_been_used_to_send())) {
4573 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004574 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004575
4576 cricket::SenderOptions sender_options;
4577 sender_options.track_id = transceiver->sender()->id();
4578 sender_options.stream_ids = transceiver->sender()->stream_ids();
4579
4580 // The following sets up RIDs and Simulcast.
4581 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004582 RtpParameters send_parameters =
4583 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004584 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4585 send_parameters.encodings.end(),
4586 [](const RtpEncodingParameters& encoding) {
4587 return !encoding.rid.empty();
4588 });
4589
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004590 std::vector<RidDescription> send_rids;
4591 SimulcastLayerList send_layers;
4592 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4593 if (encoding.rid.empty()) {
4594 continue;
4595 }
4596 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4597 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4598 }
4599
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004600 if (has_rids) {
4601 sender_options.rids = send_rids;
4602 }
4603
4604 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004605 // When RIDs are configured, we must set num_sim_layers to 0 to.
4606 // Otherwise, num_sim_layers must be 1 because either there is no
4607 // simulcast, or simulcast is acheived by munging the SDP.
4608 sender_options.num_sim_layers = has_rids ? 0 : 1;
4609 media_description_options.sender_options.push_back(sender_options);
4610
Steve Antondcc3c022017-12-22 16:02:54 -08004611 return media_description_options;
4612}
4613
Steve Anton5c72e712018-12-10 14:25:30 -08004614// Returns the ContentInfo at mline index |i|, or null if none exists.
4615static const ContentInfo* GetContentByIndex(
4616 const SessionDescriptionInterface* sdesc,
4617 size_t i) {
4618 if (!sdesc) {
4619 return nullptr;
4620 }
4621 const ContentInfos& contents = sdesc->description()->contents();
4622 return (i < contents.size() ? &contents[i] : nullptr);
4623}
4624
Steve Antondcc3c022017-12-22 16:02:54 -08004625void PeerConnection::GetOptionsForUnifiedPlanOffer(
4626 const RTCOfferAnswerOptions& offer_answer_options,
4627 cricket::MediaSessionOptions* session_options) {
4628 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4629 // Offers) and 5.2.2 (Subsequent Offers).
4630 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004631 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004632 const ContentInfos& local_contents =
4633 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004634 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004635 const ContentInfos& remote_contents =
4636 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004637 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004638 // The mline indices that can be recycled. New transceivers should reuse these
4639 // slots first.
4640 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004641 // First, go through each media section that exists in either the local or
4642 // remote description and generate a media section in this offer for the
4643 // associated transceiver. If a media section can be recycled, generate a
4644 // default, rejected media section here that can be later overwritten.
4645 for (size_t i = 0;
4646 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4647 // Either |local_content| or |remote_content| is non-null.
4648 const ContentInfo* local_content =
4649 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004650 const ContentInfo* current_local_content =
4651 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004652 const ContentInfo* remote_content =
4653 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004654 const ContentInfo* current_remote_content =
4655 GetContentByIndex(current_remote_description(), i);
4656 bool had_been_rejected =
4657 (current_local_content && current_local_content->rejected) ||
4658 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004659 const std::string& mid =
4660 (local_content ? local_content->name : remote_content->name);
4661 cricket::MediaType media_type =
4662 (local_content ? local_content->media_description()->type()
4663 : remote_content->media_description()->type());
4664 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4665 media_type == cricket::MEDIA_TYPE_VIDEO) {
4666 auto transceiver = GetAssociatedTransceiver(mid);
4667 RTC_CHECK(transceiver);
4668 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004669 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004670 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004671 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004672 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4673 RtpTransceiverDirection::kInactive,
4674 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004675 recycleable_mline_indices.push(i);
4676 } else {
4677 session_options->media_description_options.push_back(
4678 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4679 // CreateOffer shouldn't really cause any state changes in
4680 // PeerConnection, but we need a way to match new transceivers to new
4681 // media sections in SetLocalDescription and JSEP specifies this is done
4682 // by recording the index of the media section generated for the
4683 // transceiver in the offer.
4684 transceiver->internal()->set_mline_index(i);
4685 }
4686 } else {
4687 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004688 RTC_CHECK(GetDataMid());
4689 if (had_been_rejected || mid != *GetDataMid()) {
4690 session_options->media_description_options.push_back(
4691 GetMediaDescriptionOptionsForRejectedData(mid));
4692 } else {
4693 session_options->media_description_options.push_back(
4694 GetMediaDescriptionOptionsForActiveData(mid));
4695 }
Steve Antondcc3c022017-12-22 16:02:54 -08004696 }
4697 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004698
Steve Antondcc3c022017-12-22 16:02:54 -08004699 // Next, look for transceivers that are newly added (that is, are not stopped
4700 // and not associated). Reuse media sections marked as recyclable first,
4701 // otherwise append to the end of the offer. New media sections should be
4702 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004703 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004704 if (transceiver->mid() || transceiver->stopped()) {
4705 continue;
4706 }
4707 size_t mline_index;
4708 if (!recycleable_mline_indices.empty()) {
4709 mline_index = recycleable_mline_indices.front();
4710 recycleable_mline_indices.pop();
4711 session_options->media_description_options[mline_index] =
4712 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004713 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004714 } else {
4715 mline_index = session_options->media_description_options.size();
4716 session_options->media_description_options.push_back(
4717 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004718 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004719 }
4720 // See comment above for why CreateOffer changes the transceiver's state.
4721 transceiver->internal()->set_mline_index(mline_index);
4722 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004723 // Lastly, add a m-section if we have local data channels and an m section
4724 // does not already exist.
4725 if (!GetDataMid() && HasDataChannels()) {
4726 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004727 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004728 }
Steve Antondcc3c022017-12-22 16:02:54 -08004729}
4730
4731void PeerConnection::GetOptionsForAnswer(
4732 const RTCOfferAnswerOptions& offer_answer_options,
4733 cricket::MediaSessionOptions* session_options) {
4734 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4735
4736 if (IsUnifiedPlan()) {
4737 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4738 } else {
4739 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4740 }
4741
Steve Antonfa2260d2017-12-28 16:38:23 -08004742 // Intentionally unset the data channel type for RTP data channel. Otherwise
4743 // the RTP data channels would be successfully negotiated by default and the
4744 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4745 // We want to leave RTP data channels broken, so people won't try to use them.
4746 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4747 session_options->data_channel_type = data_channel_type();
4748 }
4749
Steve Antondcc3c022017-12-22 16:02:54 -08004750 // Apply ICE renomination flag.
4751 for (auto& options : session_options->media_description_options) {
4752 options.transport_options.enable_ice_renomination =
4753 configuration_.enable_ice_renomination;
4754 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004755
4756 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004757 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004758 session_options->pooled_ice_credentials =
4759 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4760 RTC_FROM_HERE,
4761 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4762 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004763
4764 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004765 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004766 for (auto& options : session_options->media_description_options) {
4767 options.transport_options.opaque_parameters =
4768 transport_controller_->GetTransportParameters(options.mid);
4769 }
4770 }
deadbeefab9b2d12015-10-14 11:33:11 -07004771}
4772
Steve Antondcc3c022017-12-22 16:02:54 -08004773void PeerConnection::GetOptionsForPlanBAnswer(
4774 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004775 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004776 // Figure out transceiver directional preferences.
4777 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4778 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4779
4780 // By default, generate sendrecv/recvonly m= sections. The direction is also
4781 // restricted by the direction in the offer.
4782 bool recv_audio = true;
4783 bool recv_video = true;
4784
4785 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004786 if (offer_answer_options.offer_to_receive_audio !=
4787 RTCOfferAnswerOptions::kUndefined) {
4788 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004789 }
Steve Antondcc3c022017-12-22 16:02:54 -08004790 if (offer_answer_options.offer_to_receive_video !=
4791 RTCOfferAnswerOptions::kUndefined) {
4792 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004793 }
4794
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004795 absl::optional<size_t> audio_index;
4796 absl::optional<size_t> video_index;
4797 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004798
4799 // Generate m= sections that match those in the offer.
4800 // Note that mediasession.cc will handle intersection our preferred
4801 // direction with the offered direction.
4802 GenerateMediaDescriptionOptions(
4803 remote_description(),
4804 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4805 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4806 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004807
4808 cricket::MediaDescriptionOptions* audio_media_description_options =
4809 !audio_index ? nullptr
4810 : &session_options->media_description_options[*audio_index];
4811 cricket::MediaDescriptionOptions* video_media_description_options =
4812 !video_index ? nullptr
4813 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004814
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004815 AddPlanBRtpSenderOptions(GetSendersInternal(),
4816 audio_media_description_options,
4817 video_media_description_options,
4818 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004819}
zhihuangaf388472016-11-02 16:49:48 -07004820
Steve Antondcc3c022017-12-22 16:02:54 -08004821void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4822 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4823 cricket::MediaSessionOptions* session_options) {
4824 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4825 // Answers) and 5.3.2 (Subsequent Answers).
4826 RTC_DCHECK(remote_description());
4827 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4828 for (const ContentInfo& content :
4829 remote_description()->description()->contents()) {
4830 cricket::MediaType media_type = content.media_description()->type();
4831 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4832 media_type == cricket::MEDIA_TYPE_VIDEO) {
4833 auto transceiver = GetAssociatedTransceiver(content.name);
4834 RTC_CHECK(transceiver);
4835 session_options->media_description_options.push_back(
4836 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4837 } else {
4838 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004839 // Reject all data sections if data channels are disabled.
4840 // Reject a data section if it has already been rejected.
4841 // Reject all data sections except for the first one.
4842 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4843 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004844 session_options->media_description_options.push_back(
4845 GetMediaDescriptionOptionsForRejectedData(content.name));
4846 } else {
4847 session_options->media_description_options.push_back(
4848 GetMediaDescriptionOptionsForActiveData(content.name));
4849 }
Steve Antondcc3c022017-12-22 16:02:54 -08004850 }
4851 }
htaa2a49d92016-03-04 02:51:39 -08004852}
4853
zhihuang1c378ed2017-08-17 14:10:50 -07004854void PeerConnection::GenerateMediaDescriptionOptions(
4855 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004856 RtpTransceiverDirection audio_direction,
4857 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004858 absl::optional<size_t>* audio_index,
4859 absl::optional<size_t>* video_index,
4860 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004861 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004862 for (const cricket::ContentInfo& content :
4863 session_desc->description()->contents()) {
4864 if (IsAudioContent(&content)) {
4865 // If we already have an audio m= section, reject this extra one.
4866 if (*audio_index) {
4867 session_options->media_description_options.push_back(
4868 cricket::MediaDescriptionOptions(
4869 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004870 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004871 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004872 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004873 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004874 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4875 content.name, audio_direction,
4876 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004877 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004878 }
4879 } else if (IsVideoContent(&content)) {
4880 // If we already have an video m= section, reject this extra one.
4881 if (*video_index) {
4882 session_options->media_description_options.push_back(
4883 cricket::MediaDescriptionOptions(
4884 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004885 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004886 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004887 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004888 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004889 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4890 content.name, video_direction,
4891 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004892 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004893 }
4894 } else {
4895 RTC_DCHECK(IsDataContent(&content));
4896 // If we already have an data m= section, reject this extra one.
4897 if (*data_index) {
4898 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004899 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004900 } else {
4901 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004902 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004903 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004904 }
4905 }
htaa2a49d92016-03-04 02:51:39 -08004906 }
deadbeefab9b2d12015-10-14 11:33:11 -07004907}
4908
Steve Antonfa2260d2017-12-28 16:38:23 -08004909cricket::MediaDescriptionOptions
4910PeerConnection::GetMediaDescriptionOptionsForActiveData(
4911 const std::string& mid) const {
4912 // Direction for data sections is meaningless, but legacy endpoints might
4913 // expect sendrecv.
4914 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4915 RtpTransceiverDirection::kSendRecv,
4916 /*stopped=*/false);
4917 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4918 return options;
4919}
4920
4921cricket::MediaDescriptionOptions
4922PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4923 const std::string& mid) const {
4924 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4925 RtpTransceiverDirection::kInactive,
4926 /*stopped=*/true);
4927 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4928 return options;
4929}
4930
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004931absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004932 switch (data_channel_type_) {
4933 case cricket::DCT_RTP:
4934 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004935 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004936 }
4937 return rtp_data_channel_->content_name();
4938 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004939 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004940 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
4941 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
4942 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004943 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004944 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004945 }
4946}
4947
Steve Anton4171afb2017-11-20 10:20:22 -08004948void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4949 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4950 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004951 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004952}
4953
Steve Anton4171afb2017-11-20 10:20:22 -08004954void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004955 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004956 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004957 cricket::MediaType media_type,
4958 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004959 RTC_DCHECK(!IsUnifiedPlan());
4960
Steve Anton4171afb2017-11-20 10:20:22 -08004961 std::vector<RtpSenderInfo>* current_senders =
4962 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004963
Steve Anton4171afb2017-11-20 10:20:22 -08004964 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004965 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004966 for (auto sender_it = current_senders->begin();
4967 sender_it != current_senders->end();
4968 /* incremented manually */) {
4969 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004970 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004971 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004972 std::string params_stream_id;
4973 if (params) {
4974 params_stream_id =
4975 (!params->first_stream_id().empty() ? params->first_stream_id()
4976 : kDefaultStreamId);
4977 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004978 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004979 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004980 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004981 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004982 sender_exists) {
4983 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004984 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004985 OnRemoteSenderRemoved(info, media_type);
4986 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004987 }
4988 }
4989
Steve Anton4171afb2017-11-20 10:20:22 -08004990 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004991 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004992 if (!params.has_ssrcs()) {
4993 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4994 // sender, this means it is coming from a Unified Plan endpoint,so we just
4995 // create a default.
4996 default_sender_needed = true;
4997 break;
4998 }
4999
Seth Hampson845e8782018-03-02 11:34:10 -08005000 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005001 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005002 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5003 // not supported in Plan B, we just take the first here and create the
5004 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005005 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005006 (!params.first_stream_id().empty() ? params.first_stream_id()
5007 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005008 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005009 uint32_t ssrc = params.first_ssrc();
5010
5011 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005012 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005013 if (!stream) {
5014 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005015 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005016 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005017 remote_streams_->AddStream(stream);
5018 new_streams->AddStream(stream);
5019 }
5020
Steve Anton4171afb2017-11-20 10:20:22 -08005021 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005022 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005023 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005024 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005025 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005026 }
5027 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005028
Steve Anton4171afb2017-11-20 10:20:22 -08005029 // Add default sender if necessary.
5030 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005031 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005032 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005033 if (!default_stream) {
5034 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005035 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005036 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005037 remote_streams_->AddStream(default_stream);
5038 new_streams->AddStream(default_stream);
5039 }
Steve Anton4171afb2017-11-20 10:20:22 -08005040 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5041 ? kDefaultAudioSenderId
5042 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005043 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005044 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005045 if (!default_sender_info) {
5046 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005047 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005048 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005049 }
5050 }
deadbeefab9b2d12015-10-14 11:33:11 -07005051}
5052
Steve Anton4171afb2017-11-20 10:20:22 -08005053void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5054 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005055 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5056 << " receiver for track_id=" << sender_info.sender_id
5057 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005058
Steve Anton3d954a62018-04-02 11:27:23 -07005059 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005060 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005061 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005062 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005063 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005064 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005065 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005066 }
5067}
5068
Steve Anton4171afb2017-11-20 10:20:22 -08005069void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5070 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005071 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5072 << " receiver for track_id=" << sender_info.sender_id
5073 << " and stream_id=" << sender_info.stream_id;
5074
Seth Hampson845e8782018-03-02 11:34:10 -08005075 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005076
Henrik Boström933d8b02017-10-10 10:05:16 -07005077 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005078 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005079 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5080 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005081 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005082 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005083 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005084 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005085 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005086 }
5087 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005088 // Stopping or destroying a VideoRtpReceiver will end the
5089 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005090 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005091 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005092 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005093 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005094 // There's no guarantee the track is still available, e.g. the track may
5095 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005096 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005097 }
5098 } else {
nisseede5da42017-01-12 05:15:36 -08005099 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005100 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005101 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005102 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005103 }
deadbeefab9b2d12015-10-14 11:33:11 -07005104}
5105
5106void PeerConnection::UpdateEndedRemoteMediaStreams() {
5107 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5108 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5109 MediaStreamInterface* stream = remote_streams_->at(i);
5110 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5111 streams_to_remove.push_back(stream);
5112 }
5113 }
5114
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005115 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005116 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005117 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005118 }
5119}
5120
Steve Anton4171afb2017-11-20 10:20:22 -08005121void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005122 const std::vector<cricket::StreamParams>& streams,
5123 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005124 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005125
Seth Hampson845e8782018-03-02 11:34:10 -08005126 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005127 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005128 for (auto sender_it = current_senders->begin();
5129 sender_it != current_senders->end();
5130 /* incremented manually */) {
5131 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005132 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005133 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5134 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005135 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005136 OnLocalSenderRemoved(info, media_type);
5137 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005138 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005139 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005140 }
5141 }
5142
Steve Anton4171afb2017-11-20 10:20:22 -08005143 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005144 for (const cricket::StreamParams& params : streams) {
5145 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005146 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005147 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005148 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005149 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005150 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005151 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005152 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005153 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005154 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005155 }
5156 }
5157}
5158
Steve Anton4171afb2017-11-20 10:20:22 -08005159void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5160 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005161 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005162 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005163 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005164 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5165 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005166 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005167 return;
5168 }
5169
deadbeeffac06552015-11-25 11:26:01 -08005170 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005171 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005172 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005173 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005174 }
deadbeeffac06552015-11-25 11:26:01 -08005175
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005176 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005177 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005178}
5179
Steve Anton4171afb2017-11-20 10:20:22 -08005180void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5181 cricket::MediaType media_type) {
5182 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005183 if (!sender) {
5184 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005185 // SessionDescriptions has been renegotiated.
5186 return;
5187 }
deadbeeffac06552015-11-25 11:26:01 -08005188
5189 // A sender has been removed from the SessionDescription but it's still
5190 // associated with the PeerConnection. This only occurs if the SDP doesn't
5191 // match with the calls to CreateSender, AddStream and RemoveStream.
5192 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005193 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005194 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005195 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005196 }
deadbeeffac06552015-11-25 11:26:01 -08005197
Steve Anton4171afb2017-11-20 10:20:22 -08005198 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005199}
5200
5201void PeerConnection::UpdateLocalRtpDataChannels(
5202 const cricket::StreamParamsVec& streams) {
5203 std::vector<std::string> existing_channels;
5204
5205 // Find new and active data channels.
5206 for (const cricket::StreamParams& params : streams) {
5207 // |it->sync_label| is actually the data channel label. The reason is that
5208 // we use the same naming of data channels as we do for
5209 // MediaStreams and Tracks.
5210 // For MediaStreams, the sync_label is the MediaStream label and the
5211 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005212 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005213 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005214 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005215 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005216 continue;
5217 }
5218 // Set the SSRC the data channel should use for sending.
5219 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5220 existing_channels.push_back(data_channel_it->first);
5221 }
5222
5223 UpdateClosingRtpDataChannels(existing_channels, true);
5224}
5225
5226void PeerConnection::UpdateRemoteRtpDataChannels(
5227 const cricket::StreamParamsVec& streams) {
5228 std::vector<std::string> existing_channels;
5229
5230 // Find new and active data channels.
5231 for (const cricket::StreamParams& params : streams) {
5232 // The data channel label is either the mslabel or the SSRC if the mslabel
5233 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005234 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005235 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005236 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005237 auto data_channel_it = rtp_data_channels_.find(label);
5238 if (data_channel_it == rtp_data_channels_.end()) {
5239 // This is a new data channel.
5240 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5241 } else {
5242 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5243 }
5244 existing_channels.push_back(label);
5245 }
5246
5247 UpdateClosingRtpDataChannels(existing_channels, false);
5248}
5249
5250void PeerConnection::UpdateClosingRtpDataChannels(
5251 const std::vector<std::string>& active_channels,
5252 bool is_local_update) {
5253 auto it = rtp_data_channels_.begin();
5254 while (it != rtp_data_channels_.end()) {
5255 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005256 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005257 ++it;
5258 continue;
5259 }
5260
5261 if (is_local_update) {
5262 data_channel->SetSendSsrc(0);
5263 } else {
5264 data_channel->RemotePeerRequestClose();
5265 }
5266
5267 if (data_channel->state() == DataChannel::kClosed) {
5268 rtp_data_channels_.erase(it);
5269 it = rtp_data_channels_.begin();
5270 } else {
5271 ++it;
5272 }
5273 }
5274}
5275
5276void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5277 uint32_t remote_ssrc) {
5278 rtc::scoped_refptr<DataChannel> channel(
5279 InternalCreateDataChannel(label, nullptr));
5280 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005281 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005282 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005283 return;
5284 }
5285 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005286 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5287 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005288 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005289}
5290
5291rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5292 const std::string& label,
5293 const InternalDataChannelInit* config) {
5294 if (IsClosed()) {
5295 return nullptr;
5296 }
Steve Anton75737c02017-11-06 10:37:17 -08005297 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005298 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005299 << "InternalCreateDataChannel: Data is not supported in this call.";
5300 return nullptr;
5301 }
5302 InternalDataChannelInit new_config =
5303 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005304 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005305 if (new_config.id < 0) {
5306 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005307 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005308 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005309 RTC_LOG(LS_ERROR)
5310 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005311 return nullptr;
5312 }
5313 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005314 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005315 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005316 return nullptr;
5317 }
5318 }
5319
Steve Anton75737c02017-11-06 10:37:17 -08005320 rtc::scoped_refptr<DataChannel> channel(
5321 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005322 if (!channel) {
5323 sid_allocator_.ReleaseSid(new_config.id);
5324 return nullptr;
5325 }
5326
5327 if (channel->data_channel_type() == cricket::DCT_RTP) {
5328 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005329 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5330 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005331 return nullptr;
5332 }
5333 rtp_data_channels_[channel->label()] = channel;
5334 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005335 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005336 sctp_data_channels_.push_back(channel);
5337 channel->SignalClosed.connect(this,
5338 &PeerConnection::OnSctpDataChannelClosed);
5339 }
5340
Steve Anton2d8609c2018-01-23 16:38:46 -08005341 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005342 return channel;
5343}
5344
5345bool PeerConnection::HasDataChannels() const {
5346 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5347}
5348
5349void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005350 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005351 for (const auto& channel : sctp_data_channels_) {
5352 if (channel->id() < 0) {
5353 int sid;
5354 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005355 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5356 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005357 continue;
5358 }
5359 channel->SetSctpSid(sid);
5360 }
5361 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005362 // Since closing modifies the list of channels, we have to do the actual
5363 // closing outside the loop.
5364 for (const auto& channel : channels_to_close) {
5365 channel->CloseAbruptly();
5366 }
deadbeefab9b2d12015-10-14 11:33:11 -07005367}
5368
5369void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005370 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005371 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5372 ++it) {
5373 if (it->get() == channel) {
5374 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005375 // After the closing procedure is done, it's safe to use this ID for
5376 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005377 sid_allocator_.ReleaseSid(channel->id());
5378 }
deadbeefbd292462015-12-14 18:15:29 -08005379 // Since this method is triggered by a signal from the DataChannel,
5380 // we can't free it directly here; we need to free it asynchronously.
5381 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005382 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005383 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5384 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005385 return;
5386 }
5387 }
5388}
5389
deadbeefab9b2d12015-10-14 11:33:11 -07005390void PeerConnection::OnDataChannelDestroyed() {
5391 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5392 // DataChannel may callback to us and try to modify the list.
5393 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5394 temp_rtp_dcs.swap(rtp_data_channels_);
5395 for (const auto& kv : temp_rtp_dcs) {
5396 kv.second->OnTransportChannelDestroyed();
5397 }
5398
5399 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5400 temp_sctp_dcs.swap(sctp_data_channels_);
5401 for (const auto& channel : temp_sctp_dcs) {
5402 channel->OnTransportChannelDestroyed();
5403 }
5404}
5405
5406void PeerConnection::OnDataChannelOpenMessage(
5407 const std::string& label,
5408 const InternalDataChannelInit& config) {
5409 rtc::scoped_refptr<DataChannel> channel(
5410 InternalCreateDataChannel(label, &config));
5411 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005412 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005413 return;
5414 }
5415
deadbeefa601f5c2016-06-06 14:27:39 -07005416 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5417 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005418 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005419 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005420}
5421
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005422bool PeerConnection::HandleOpenMessage_s(
5423 const cricket::ReceiveDataParams& params,
5424 const rtc::CopyOnWriteBuffer& buffer) {
5425 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5426 // Received OPEN message; parse and signal that a new data channel should
5427 // be created.
5428 std::string label;
5429 InternalDataChannelInit config;
5430 config.id = params.ssrc;
5431 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5432 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5433 << params.ssrc;
5434 return true;
5435 }
5436 config.open_handshake_role = InternalDataChannelInit::kAcker;
5437 OnDataChannelOpenMessage(label, config);
5438 return true;
5439 }
5440 return false;
5441}
5442
Steve Anton4171afb2017-11-20 10:20:22 -08005443rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5444PeerConnection::GetAudioTransceiver() const {
5445 // This method only works with Plan B SDP, where there is a single
5446 // audio/video transceiver.
5447 RTC_DCHECK(!IsUnifiedPlan());
5448 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005449 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005450 return transceiver;
5451 }
5452 }
5453 RTC_NOTREACHED();
5454 return nullptr;
5455}
5456
5457rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5458PeerConnection::GetVideoTransceiver() const {
5459 // This method only works with Plan B SDP, where there is a single
5460 // audio/video transceiver.
5461 RTC_DCHECK(!IsUnifiedPlan());
5462 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005463 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005464 return transceiver;
5465 }
5466 }
5467 RTC_NOTREACHED();
5468 return nullptr;
5469}
5470
5471// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5472// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005473bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005474 switch (type) {
5475 case cricket::MEDIA_TYPE_AUDIO:
5476 return !GetAudioTransceiver()->internal()->senders().empty();
5477 case cricket::MEDIA_TYPE_VIDEO:
5478 return !GetVideoTransceiver()->internal()->senders().empty();
5479 case cricket::MEDIA_TYPE_DATA:
5480 return false;
5481 }
5482 RTC_NOTREACHED();
5483 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005484}
5485
Steve Anton4171afb2017-11-20 10:20:22 -08005486rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5487PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005488 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005489 for (auto sender : transceiver->internal()->senders()) {
5490 if (sender->track() == track) {
5491 return sender;
5492 }
5493 }
5494 }
5495 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005496}
5497
Steve Anton4171afb2017-11-20 10:20:22 -08005498rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5499PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005500 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005501 for (auto sender : transceiver->internal()->senders()) {
5502 if (sender->id() == sender_id) {
5503 return sender;
5504 }
5505 }
5506 }
5507 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005508}
5509
Steve Anton4171afb2017-11-20 10:20:22 -08005510rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5511PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005512 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005513 for (auto receiver : transceiver->internal()->receivers()) {
5514 if (receiver->id() == receiver_id) {
5515 return receiver;
5516 }
5517 }
5518 }
5519 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005520}
5521
Steve Anton4171afb2017-11-20 10:20:22 -08005522std::vector<PeerConnection::RtpSenderInfo>*
5523PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5524 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5525 media_type == cricket::MEDIA_TYPE_VIDEO);
5526 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5527 ? &remote_audio_sender_infos_
5528 : &remote_video_sender_infos_;
5529}
5530
5531std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005532 cricket::MediaType media_type) {
5533 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5534 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005535 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5536 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005537}
5538
Steve Anton4171afb2017-11-20 10:20:22 -08005539const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5540 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005541 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005542 const std::string sender_id) const {
5543 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005544 if (sender_info.stream_id == stream_id &&
5545 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005546 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005547 }
5548 }
5549 return nullptr;
5550}
5551
5552DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5553 for (const auto& channel : sctp_data_channels_) {
5554 if (channel->id() == sid) {
5555 return channel;
5556 }
5557 }
5558 return nullptr;
5559}
5560
Karl Wibergfb3be392019-03-22 14:13:22 +01005561PeerConnection::InitializePortAllocatorResult
5562PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005563 const cricket::ServerAddresses& stun_servers,
5564 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005565 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005566 RTC_DCHECK_RUN_ON(network_thread());
5567
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005568 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005569 // To handle both internal and externally created port allocator, we will
5570 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005571 int port_allocator_flags = port_allocator_->flags();
5572 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5573 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5574 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005575 // If the disable-IPv6 flag was specified, we'll not override it
5576 // by experiment.
5577 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005578 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005579 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5580 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005581 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005582 }
5583
zhihuangb09b3f92017-03-07 14:40:51 -08005584 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005585 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005586 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005587 }
5588
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005589 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005590 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005591 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005592 }
5593
honghaiz60347052016-05-31 18:29:12 -07005594 if (configuration.candidate_network_policy ==
5595 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005596 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005597 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005598 }
5599
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005600 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005601 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005602 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5603 }
5604
Karl Wibergfb3be392019-03-22 14:13:22 +01005605 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005606 // No step delay is used while allocating ports.
5607 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005608 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005609 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005610 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005611
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005612 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005613 for (auto& turn_server : turn_servers_copy) {
5614 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005615 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005616 // Call this last since it may create pooled allocator sessions using the
5617 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005618 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005619 stun_servers, std::move(turn_servers_copy),
5620 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5621 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005622 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005623
5624 InitializePortAllocatorResult res;
5625 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5626 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005627}
5628
deadbeef91dd5672016-05-18 16:55:30 -07005629bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005630 const cricket::ServerAddresses& stun_servers,
5631 const std::vector<cricket::RelayServerConfig>& turn_servers,
5632 IceTransportsType type,
5633 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005634 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005635 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005636 absl::optional<int> stun_candidate_keepalive_interval,
5637 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005638 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005639 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005640 // According to JSEP, after setLocalDescription, changing the candidate pool
5641 // size is not allowed, and changing the set of ICE servers will not result
5642 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005643 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005644 port_allocator_->FreezeCandidatePool();
5645 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005646 // Add the custom tls turn servers if they exist.
5647 auto turn_servers_copy = turn_servers;
5648 for (auto& turn_server : turn_servers_copy) {
5649 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5650 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005651 // Call this last since it may create pooled allocator sessions using the
5652 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005653 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005654 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5655 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005656}
5657
Steve Antonba818672017-11-06 10:21:57 -08005658cricket::ChannelManager* PeerConnection::channel_manager() const {
5659 return factory_->channel_manager();
5660}
5661
Elad Alon99c3fe52017-10-13 16:29:40 +02005662bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005663 std::unique_ptr<RtcEventLogOutput> output,
5664 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005665 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005666 if (!event_log_) {
5667 return false;
5668 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005669 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005670}
5671
5672void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005673 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005674 if (event_log_) {
5675 event_log_->StopLogging();
5676 }
ivoc14d5dbe2016-07-04 07:06:55 -07005677}
nisseeaabdf62017-05-05 02:23:02 -07005678
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005679cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005680 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005681 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005682 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005683 if (channel && channel->content_name() == content_name) {
5684 return channel;
5685 }
Steve Anton75737c02017-11-06 10:37:17 -08005686 }
5687 if (rtp_data_channel() &&
5688 rtp_data_channel()->content_name() == content_name) {
5689 return rtp_data_channel();
5690 }
5691 return nullptr;
5692}
5693
5694bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005695 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005696 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005697 RTC_LOG(LS_INFO)
5698 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005699 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005700 return false;
5701 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005702 if (!sctp_transport_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005703 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005704 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005705 return false;
5706 }
5707
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005708 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005709 if (sctp_mid_ && sctp_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005710 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5711 } else if (is_caller_) {
5712 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5713 }
Zhi Huange830e682018-03-30 10:48:35 -07005714 if (dtls_role) {
5715 *role = *dtls_role;
5716 return true;
5717 }
5718 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005719}
5720
5721bool PeerConnection::GetSslRole(const std::string& content_name,
5722 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005723 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005724 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005725 RTC_LOG(LS_INFO)
5726 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005727 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005728 return false;
5729 }
5730
Zhi Huange830e682018-03-30 10:48:35 -07005731 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5732 if (dtls_role) {
5733 *role = *dtls_role;
5734 return true;
5735 }
5736 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005737}
5738
Steve Antonf8470812017-12-04 10:46:21 -08005739void PeerConnection::SetSessionError(SessionError error,
5740 const std::string& error_desc) {
5741 RTC_DCHECK_RUN_ON(signaling_thread());
5742 if (error != session_error_) {
5743 session_error_ = error;
5744 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005745 }
5746}
5747
Zhi Huange830e682018-03-30 10:48:35 -07005748RTCError PeerConnection::UpdateSessionState(
5749 SdpType type,
5750 cricket::ContentSource source,
5751 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005752 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005753
5754 // If there's already a pending error then no state transition should happen.
5755 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005756 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005757
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005758 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005759 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005760 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005761 }
5762
5763 // Update the signaling state according to the specified state machine (see
5764 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005765 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005766 ChangeSignalingState(source == cricket::CS_LOCAL
5767 ? PeerConnectionInterface::kHaveLocalOffer
5768 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005769 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005770 ChangeSignalingState(source == cricket::CS_LOCAL
5771 ? PeerConnectionInterface::kHaveLocalPrAnswer
5772 : PeerConnectionInterface::kHaveRemotePrAnswer);
5773 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005774 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005775 ChangeSignalingState(PeerConnectionInterface::kStable);
5776 }
5777
5778 // Update internal objects according to the session description's media
5779 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005780 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005781 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005782 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005783 }
5784
Steve Anton8a006912017-12-04 15:25:56 -08005785 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005786}
5787
Steve Anton8a006912017-12-04 15:25:56 -08005788RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005789 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005790 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005791 const SessionDescriptionInterface* sdesc =
5792 (source == cricket::CS_LOCAL ? local_description()
5793 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005794 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005795
5796 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005797 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005798 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005799 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005800 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005801 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005802 continue;
5803 }
5804 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005805 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005806 if (!content_desc) {
5807 continue;
5808 }
5809 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005810 bool success = (source == cricket::CS_LOCAL)
5811 ? channel->SetLocalContent(content_desc, type, &error)
5812 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005813 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005814 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005815 }
5816 }
5817
5818 // If using the RtpDataChannel, push down the new SDP section for it too.
5819 if (rtp_data_channel_) {
5820 const ContentInfo* data_content =
5821 cricket::GetFirstDataContent(sdesc->description());
5822 if (data_content && !data_content->rejected) {
5823 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005824 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005825 if (data_desc) {
5826 std::string error;
5827 bool success =
5828 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005829 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005830 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005831 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005832 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005833 }
Steve Anton75737c02017-11-06 10:37:17 -08005834 }
5835 }
5836 }
Steve Antoned10bd92017-12-05 10:52:59 -08005837
Steve Anton75737c02017-11-06 10:37:17 -08005838 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5839 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005840 if (sctp_transport_ && local_description() && remote_description()) {
5841 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5842 local_description()->description());
5843 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5844 remote_description()->description());
5845 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005846 int max_message_size;
5847 // A remote max message size of zero means "any size supported".
5848 // We configure the connection with our own max message size.
5849 if (remote_sctp_description->max_message_size() == 0) {
5850 max_message_size = local_sctp_description->max_message_size();
5851 } else {
5852 max_message_size =
5853 std::min(local_sctp_description->max_message_size(),
5854 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005855 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005856 sctp_transport_->Start(local_sctp_description->port(),
5857 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005858 }
Steve Anton75737c02017-11-06 10:37:17 -08005859 }
Steve Antoned10bd92017-12-05 10:52:59 -08005860
Steve Anton8a006912017-12-04 15:25:56 -08005861 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005862}
5863
Steve Anton8a006912017-12-04 15:25:56 -08005864RTCError PeerConnection::PushdownTransportDescription(
5865 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005866 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005867 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005868
Zhi Huange830e682018-03-30 10:48:35 -07005869 if (source == cricket::CS_LOCAL) {
5870 const SessionDescriptionInterface* sdesc = local_description();
5871 RTC_DCHECK(sdesc);
5872 return transport_controller_->SetLocalDescription(type,
5873 sdesc->description());
5874 } else {
5875 const SessionDescriptionInterface* sdesc = remote_description();
5876 RTC_DCHECK(sdesc);
5877 return transport_controller_->SetRemoteDescription(type,
5878 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005879 }
Steve Anton75737c02017-11-06 10:37:17 -08005880}
5881
5882bool PeerConnection::GetTransportDescription(
5883 const SessionDescription* description,
5884 const std::string& content_name,
5885 cricket::TransportDescription* tdesc) {
5886 if (!description || !tdesc) {
5887 return false;
5888 }
5889 const TransportInfo* transport_info =
5890 description->GetTransportInfoByName(content_name);
5891 if (!transport_info) {
5892 return false;
5893 }
5894 *tdesc = transport_info->description;
5895 return true;
5896}
5897
Steve Anton75737c02017-11-06 10:37:17 -08005898cricket::IceConfig PeerConnection::ParseIceConfig(
5899 const PeerConnectionInterface::RTCConfiguration& config) const {
5900 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005901 switch (config.continual_gathering_policy) {
5902 case PeerConnectionInterface::GATHER_ONCE:
5903 gathering_policy = cricket::GATHER_ONCE;
5904 break;
5905 case PeerConnectionInterface::GATHER_CONTINUALLY:
5906 gathering_policy = cricket::GATHER_CONTINUALLY;
5907 break;
5908 default:
5909 RTC_NOTREACHED();
5910 gathering_policy = cricket::GATHER_ONCE;
5911 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005912
Steve Anton75737c02017-11-06 10:37:17 -08005913 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005914 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5915 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005916 ice_config.prioritize_most_likely_candidate_pairs =
5917 config.prioritize_most_likely_ice_candidate_pairs;
5918 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005919 RTCConfigurationToIceConfigOptionalInt(
5920 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005921 ice_config.continual_gathering_policy = gathering_policy;
5922 ice_config.presume_writable_when_fully_relayed =
5923 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005924 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5925 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005926 ice_config.ice_check_interval_strong_connectivity =
5927 config.ice_check_interval_strong_connectivity;
5928 ice_config.ice_check_interval_weak_connectivity =
5929 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005930 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005931 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5932 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005933 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005934 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005935 ice_config.regather_all_networks_interval_range =
5936 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005937 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005938 return ice_config;
5939}
5940
Steve Anton75737c02017-11-06 10:37:17 -08005941bool PeerConnection::SendData(const cricket::SendDataParams& params,
5942 const rtc::CopyOnWriteBuffer& payload,
5943 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005944 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005945 if (data_channel_transport_ && data_channel_transport_negotiated_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005946 SendDataParams send_params;
5947 send_params.type = ToWebrtcDataMessageType(params.type);
5948 send_params.ordered = params.ordered;
5949 if (params.max_rtx_count >= 0) {
5950 send_params.max_rtx_count = params.max_rtx_count;
5951 } else if (params.max_rtx_ms >= 0) {
5952 send_params.max_rtx_ms = params.max_rtx_ms;
5953 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005954 return data_channel_transport_->SendData(params.sid, send_params, payload)
5955 .ok();
5956 } else if (sctp_transport_ && sctp_negotiated_) {
5957 return network_thread()->Invoke<bool>(
5958 RTC_FROM_HERE, Bind(&cricket::SctpTransportInternal::SendData,
5959 cricket_sctp_transport(), params, payload, result));
5960 } else if (rtp_data_channel_) {
5961 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005962 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005963 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
5964 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005965}
5966
5967bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005968 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005969 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005970 // Don't log an error here, because DataChannels are expected to call
5971 // ConnectDataChannel in this state. It's the only way to initially tell
5972 // whether or not the underlying transport is ready.
5973 return false;
5974 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005975 if (data_channel_transport_) {
5976 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
5977 &DataChannel::OnChannelReady);
5978 SignalDataChannelTransportReceivedData_s.connect(
5979 webrtc_data_channel, &DataChannel::OnDataReceived);
5980 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005981 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005982 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005983 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005984 }
5985 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005986 rtp_data_channel_->SignalReadyToSendData.connect(
5987 webrtc_data_channel, &DataChannel::OnChannelReady);
5988 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5989 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005990 }
5991 if (sctp_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005992 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5993 &DataChannel::OnChannelReady);
5994 SignalSctpDataReceived.connect(webrtc_data_channel,
5995 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005996 SignalSctpClosingProcedureStartedRemotely.connect(
5997 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5998 SignalSctpClosingProcedureComplete.connect(
5999 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08006000 }
6001 return true;
6002}
6003
6004void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006005 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006006 if (!rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006007 RTC_LOG(LS_ERROR)
6008 << "DisconnectDataChannel called when rtp_data_channel_ and "
6009 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006010 return;
6011 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006012 if (data_channel_transport_) {
6013 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6014 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6015 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6016 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6017 }
6018 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006019 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6020 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006021 }
6022 if (sctp_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006023 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
6024 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006025 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
6026 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006027 }
6028}
6029
6030void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006031 if (data_channel_transport_) {
6032 data_channel_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006033 }
Steve Anton75737c02017-11-06 10:37:17 -08006034 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006035 RTC_LOG(LS_ERROR)
6036 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006037 return;
6038 }
6039 network_thread()->Invoke<void>(
6040 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006041 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006042}
6043
6044void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006045 if (data_channel_transport_) {
6046 data_channel_transport_->CloseChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006047 }
Steve Anton75737c02017-11-06 10:37:17 -08006048 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006049 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006050 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006051 return;
6052 }
6053 network_thread()->Invoke<void>(
6054 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006055 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006056}
6057
6058bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006059 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006060 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006061 (data_channel_transport_ && data_channel_transport_ready_to_send_ &&
6062 data_channel_transport_negotiated_) ||
6063 (sctp_ready_to_send_data_ && sctp_negotiated_);
Steve Anton75737c02017-11-06 10:37:17 -08006064}
6065
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006066void PeerConnection::OnDataReceived(int channel_id,
6067 DataMessageType type,
6068 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006069 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006070 cricket::ReceiveDataParams params;
6071 params.sid = channel_id;
6072 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006073 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006074 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6075 RTC_DCHECK_RUN_ON(signaling_thread());
6076 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006077 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006078 }
6079 });
6080}
6081
6082void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006083 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006084 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006085 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6086 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006087 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006088 });
6089}
6090
6091void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006092 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006093 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006094 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6095 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006096 SignalDataChannelTransportChannelClosed_s(channel_id);
6097 });
6098}
6099
6100void PeerConnection::OnReadyToSend() {
6101 RTC_DCHECK_RUN_ON(network_thread());
6102 data_channel_transport_invoker_->AsyncInvoke<void>(
6103 RTC_FROM_HERE, signaling_thread(), [this] {
6104 RTC_DCHECK_RUN_ON(signaling_thread());
6105 data_channel_transport_ready_to_send_ = true;
6106 if (data_channel_transport_negotiated_) {
6107 SignalDataChannelTransportWritable_s(
6108 data_channel_transport_ready_to_send_);
6109 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006110 });
6111}
6112
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006113absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006114 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006115 if (sctp_mid_ && transport_controller_) {
6116 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6117 if (dtls_transport) {
6118 return dtls_transport->transport_name();
6119 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006120 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006121 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006122 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006123}
6124
Qingsi Wang72a43a12018-02-20 16:03:18 -08006125cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6126 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006127 network_thread()->Invoke<void>(
6128 RTC_FROM_HERE,
6129 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6130 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006131 return candidate_states_list;
6132}
6133
Steve Anton5dfde182018-02-06 10:34:40 -08006134std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6135 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006136 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006137 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006138 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006139 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006140 if (channel) {
6141 transport_names_by_mid[channel->content_name()] =
6142 channel->transport_name();
6143 }
Steve Anton75737c02017-11-06 10:37:17 -08006144 }
Steve Anton5dfde182018-02-06 10:34:40 -08006145 if (rtp_data_channel_) {
6146 transport_names_by_mid[rtp_data_channel_->content_name()] =
6147 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006148 }
6149 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006150 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006151 RTC_DCHECK(transport_name);
6152 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006153 }
Steve Anton5dfde182018-02-06 10:34:40 -08006154 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006155}
6156
Steve Anton5dfde182018-02-06 10:34:40 -08006157std::map<std::string, cricket::TransportStats>
6158PeerConnection::GetTransportStatsByNames(
6159 const std::set<std::string>& transport_names) {
6160 if (!network_thread()->IsCurrent()) {
6161 return network_thread()
6162 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6163 RTC_FROM_HERE,
6164 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006165 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006166 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006167 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6168 for (const std::string& transport_name : transport_names) {
6169 cricket::TransportStats transport_stats;
6170 bool success =
6171 transport_controller_->GetStats(transport_name, &transport_stats);
6172 if (success) {
6173 transport_stats_by_name[transport_name] = std::move(transport_stats);
6174 } else {
6175 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6176 << transport_name;
6177 }
6178 }
6179 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006180}
6181
6182bool PeerConnection::GetLocalCertificate(
6183 const std::string& transport_name,
6184 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006185 if (!certificate) {
6186 return false;
6187 }
6188 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6189 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006190}
6191
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006192std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006193 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006194 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006195}
6196
6197cricket::DataChannelType PeerConnection::data_channel_type() const {
6198 return data_channel_type_;
6199}
6200
6201bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006202 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006203 return pending_ice_restarts_.find(content_name) !=
6204 pending_ice_restarts_.end();
6205}
6206
Steve Anton75737c02017-11-06 10:37:17 -08006207bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6208 return transport_controller_->NeedsIceRestart(content_name);
6209}
6210
6211void PeerConnection::OnCertificateReady(
6212 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6213 transport_controller_->SetLocalCertificate(certificate);
6214}
6215
6216void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006217 SetSessionError(SessionError::kTransport,
6218 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006219}
6220
Alex Loiko9289eda2018-11-23 16:18:59 +00006221void PeerConnection::OnTransportControllerConnectionState(
6222 cricket::IceConnectionState state) {
6223 switch (state) {
6224 case cricket::kIceConnectionConnecting:
6225 // If the current state is Connected or Completed, then there were
6226 // writable channels but now there are not, so the next state must
6227 // be Disconnected.
6228 // kIceConnectionConnecting is currently used as the default,
6229 // un-connected state by the TransportController, so its only use is
6230 // detecting disconnections.
6231 if (ice_connection_state_ ==
6232 PeerConnectionInterface::kIceConnectionConnected ||
6233 ice_connection_state_ ==
6234 PeerConnectionInterface::kIceConnectionCompleted) {
6235 SetIceConnectionState(
6236 PeerConnectionInterface::kIceConnectionDisconnected);
6237 }
6238 break;
6239 case cricket::kIceConnectionFailed:
6240 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6241 break;
6242 case cricket::kIceConnectionConnected:
6243 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6244 "all transports are writable.";
6245 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6246 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6247 break;
6248 case cricket::kIceConnectionCompleted:
6249 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6250 "all transports are complete.";
6251 if (ice_connection_state_ !=
6252 PeerConnectionInterface::kIceConnectionConnected) {
6253 // If jumping directly from "checking" to "connected",
6254 // signal "connected" first.
6255 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6256 }
6257 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6258 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6259 ReportTransportStats();
6260 break;
6261 default:
6262 RTC_NOTREACHED();
6263 }
6264}
6265
Steve Anton75737c02017-11-06 10:37:17 -08006266void PeerConnection::OnTransportControllerCandidatesGathered(
6267 const std::string& transport_name,
6268 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006269 int sdp_mline_index;
6270 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006271 RTC_LOG(LS_ERROR)
6272 << "OnTransportControllerCandidatesGathered: content name "
6273 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006274 return;
6275 }
6276
6277 for (cricket::Candidates::const_iterator citer = candidates.begin();
6278 citer != candidates.end(); ++citer) {
6279 // Use transport_name as the candidate media id.
6280 std::unique_ptr<JsepIceCandidate> candidate(
6281 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6282 if (local_description()) {
6283 mutable_local_description()->AddCandidate(candidate.get());
6284 }
6285 OnIceCandidate(std::move(candidate));
6286 }
6287}
6288
Eldar Relloda13ea22019-06-01 12:23:43 +03006289void PeerConnection::OnTransportControllerCandidateError(
6290 const cricket::IceCandidateErrorEvent& event) {
6291 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6292 event.error_text);
6293}
6294
Steve Anton75737c02017-11-06 10:37:17 -08006295void PeerConnection::OnTransportControllerCandidatesRemoved(
6296 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006297 // Sanity check.
6298 for (const cricket::Candidate& candidate : candidates) {
6299 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006300 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006301 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006302 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006303 return;
6304 }
6305 }
6306
6307 if (local_description()) {
6308 mutable_local_description()->RemoveCandidates(candidates);
6309 }
6310 OnIceCandidatesRemoved(candidates);
6311}
6312
Alex Drake00c7ecf2019-08-06 10:54:47 -07006313void PeerConnection::OnTransportControllerCandidateChanged(
6314 const cricket::CandidatePairChangeEvent& event) {
6315 OnSelectedCandidatePairChanged(event);
6316}
6317
Steve Anton75737c02017-11-06 10:37:17 -08006318void PeerConnection::OnTransportControllerDtlsHandshakeError(
6319 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006320 RTC_HISTOGRAM_ENUMERATION(
6321 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6322 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006323}
6324
Steve Antoned10bd92017-12-05 10:52:59 -08006325void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006326 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006327 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006328 if (channel && !channel->enabled()) {
6329 channel->Enable(true);
6330 }
Steve Anton75737c02017-11-06 10:37:17 -08006331 }
6332
Steve Anton4171afb2017-11-20 10:20:22 -08006333 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006334 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006335 }
Steve Anton75737c02017-11-06 10:37:17 -08006336}
6337
6338// Returns the media index for a local ice candidate given the content name.
6339bool PeerConnection::GetLocalCandidateMediaIndex(
6340 const std::string& content_name,
6341 int* sdp_mline_index) {
6342 if (!local_description() || !sdp_mline_index) {
6343 return false;
6344 }
6345
6346 bool content_found = false;
6347 const ContentInfos& contents = local_description()->description()->contents();
6348 for (size_t index = 0; index < contents.size(); ++index) {
6349 if (contents[index].name == content_name) {
6350 *sdp_mline_index = static_cast<int>(index);
6351 content_found = true;
6352 break;
6353 }
6354 }
6355 return content_found;
6356}
6357
6358bool PeerConnection::UseCandidatesInSessionDescription(
6359 const SessionDescriptionInterface* remote_desc) {
6360 if (!remote_desc) {
6361 return true;
6362 }
6363 bool ret = true;
6364
6365 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6366 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6367 for (size_t n = 0; n < candidates->count(); ++n) {
6368 const IceCandidateInterface* candidate = candidates->at(n);
6369 bool valid = false;
6370 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6371 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006372 RTC_LOG(LS_INFO)
6373 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006374 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006375 }
6376 continue;
6377 }
6378 ret = UseCandidate(candidate);
6379 if (!ret) {
6380 break;
6381 }
6382 }
6383 }
6384 return ret;
6385}
6386
6387bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006388 RTCErrorOr<const cricket::ContentInfo*> result =
6389 FindContentInfo(remote_description(), candidate);
6390 if (!result.ok()) {
6391 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6392 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006393 return false;
6394 }
Steve Anton75737c02017-11-06 10:37:17 -08006395 std::vector<cricket::Candidate> candidates;
6396 candidates.push_back(candidate->candidate());
6397 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006398 RTCError error = transport_controller_->AddRemoteCandidates(
6399 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006400 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006401 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006402 // Candidates successfully submitted for checking.
6403 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6404 ice_connection_state_ ==
6405 PeerConnectionInterface::kIceConnectionDisconnected) {
6406 // If state is New, then the session has just gotten its first remote ICE
6407 // candidates, so go to Checking.
6408 // If state is Disconnected, the session is re-using old candidates or
6409 // receiving additional ones, so go to Checking.
6410 // If state is Connected, stay Connected.
6411 // TODO(bemasc): If state is Connected, and the new candidates are for a
6412 // newly added transport, then the state actually _should_ move to
6413 // checking. Add a way to distinguish that case.
6414 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6415 }
6416 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006417 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006418 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006419 }
6420 return true;
6421}
6422
Guido Urdaneta41633172019-05-23 20:12:29 +02006423RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6424 const SessionDescriptionInterface* description,
6425 const IceCandidateInterface* candidate) {
6426 if (candidate->sdp_mline_index() >= 0) {
6427 size_t mediacontent_index =
6428 static_cast<size_t>(candidate->sdp_mline_index());
6429 size_t content_size = description->description()->contents().size();
6430 if (mediacontent_index < content_size) {
6431 return &description->description()->contents()[mediacontent_index];
6432 } else {
6433 return RTCError(RTCErrorType::INVALID_RANGE,
6434 "Media line index (" +
6435 rtc::ToString(candidate->sdp_mline_index()) +
6436 ") out of range (number of mlines: " +
6437 rtc::ToString(content_size) + ").");
6438 }
6439 } else if (!candidate->sdp_mid().empty()) {
6440 auto& contents = description->description()->contents();
6441 auto it = absl::c_find_if(
6442 contents, [candidate](const cricket::ContentInfo& content_info) {
6443 return content_info.mid() == candidate->sdp_mid();
6444 });
6445 if (it == contents.end()) {
6446 return RTCError(
6447 RTCErrorType::INVALID_PARAMETER,
6448 "Mid " + candidate->sdp_mid() +
6449 " specified but no media section with that mid found.");
6450 } else {
6451 return &*it;
6452 }
6453 }
6454
6455 return RTCError(RTCErrorType::INVALID_PARAMETER,
6456 "Neither sdp_mline_index nor sdp_mid specified.");
6457}
6458
Steve Anton75737c02017-11-06 10:37:17 -08006459void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006460 // Destroy video channel first since it may have a pointer to the
6461 // voice channel.
6462 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006463 if (!video_info || video_info->rejected) {
6464 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006465 }
6466
Steve Anton6fec8802017-12-04 10:37:29 -08006467 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6468 if (!audio_info || audio_info->rejected) {
6469 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006470 }
6471
6472 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6473 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006474 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006475 }
6476}
6477
Steve Antondcc3c022017-12-22 16:02:54 -08006478RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6479 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006480 const cricket::ContentGroup* bundle_group = nullptr;
6481 if (configuration_.bundle_policy ==
6482 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006483 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006484 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006485 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6486 "max-bundle configured but session description "
6487 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006488 }
6489 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006490 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006491}
6492
6493RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006494 // Creating the media channels. Transports should already have been created
6495 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006496 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006497 if (voice && !voice->rejected &&
6498 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006499 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006500 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006501 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6502 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006503 }
6504 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6505 }
6506
Steve Antondcc3c022017-12-22 16:02:54 -08006507 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006508 if (video && !video->rejected &&
6509 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006510 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006511 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006512 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6513 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006514 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006515 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006516 }
6517
Steve Antondcc3c022017-12-22 16:02:54 -08006518 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006519 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006520 !rtp_data_channel_ && !sctp_transport_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006521 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006522 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6523 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006524 }
6525 }
6526
Steve Anton8a006912017-12-04 15:25:56 -08006527 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006528}
6529
Steve Anton4171afb2017-11-20 10:20:22 -08006530// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006531cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006532 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006533 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006534 MediaTransportConfig media_transport_config =
6535 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006536
Steve Anton75737c02017-11-06 10:37:17 -08006537 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006538 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006539 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6540 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006541 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006542 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006543 }
Steve Anton75737c02017-11-06 10:37:17 -08006544 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6545 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006546 voice_channel->SignalSentPacket.connect(this,
6547 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006548 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006549
Steve Antoneda6ccd2017-12-04 10:21:55 -08006550 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006551}
6552
Steve Anton4171afb2017-11-20 10:20:22 -08006553// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006554cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006555 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006556 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006557 MediaTransportConfig media_transport_config =
6558 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006559
Steve Anton75737c02017-11-06 10:37:17 -08006560 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006561 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006562 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6563 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006564 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006565 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006566 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006567 }
Steve Anton75737c02017-11-06 10:37:17 -08006568 video_channel->SignalDtlsSrtpSetupFailure.connect(
6569 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006570 video_channel->SignalSentPacket.connect(this,
6571 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006572 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006573
Steve Antoneda6ccd2017-12-04 10:21:55 -08006574 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006575}
6576
Zhi Huange830e682018-03-30 10:48:35 -07006577bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006578 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006579 case cricket::DCT_SCTP:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006580 // Only using SCTP transport. No more setup required. Since SCTP is
6581 // the only option, it doesn't need to wait for negotiation.
6582 sctp_negotiated_ = true;
6583 if (!CreateSctpDataChannel(mid)) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006584 return false;
6585 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006586 break;
6587 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
6588 // Setup a data channel transport with SCTP as a fallback. Which one is
6589 // used will be determined later in negotiation.
6590 if (!CreateSctpDataChannel(mid)) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006591 return false;
6592 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006593 if (!SetupDataChannelTransport(mid)) {
6594 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006595 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006596 break;
6597 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6598 case cricket::DCT_MEDIA_TRANSPORT:
6599 // Using data channel transport without a fallback. It is the only
6600 // option. Data channel transport doesn't need to be negotiated.
6601 data_channel_transport_negotiated_ = true;
6602 if (!SetupDataChannelTransport(mid)) {
6603 return false;
6604 }
6605 break;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006606 case cricket::DCT_RTP:
6607 default:
6608 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6609 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6610 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006611 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006612 if (!rtp_data_channel_) {
6613 return false;
6614 }
6615 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6616 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6617 rtp_data_channel_->SignalSentPacket.connect(
6618 this, &PeerConnection::OnSentPacket_w);
6619 rtp_data_channel_->SetRtpTransport(rtp_transport);
6620 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006621 }
6622
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006623 // All non-RTP data channels must initialize |sctp_data_channels_|.
6624 for (const auto& channel : sctp_data_channels_) {
6625 channel->OnTransportChannelCreated();
6626 }
6627 return true;
6628}
6629
6630bool PeerConnection::CreateSctpDataChannel(const std::string& mid) {
6631 if (!sctp_factory_) {
6632 RTC_LOG(LS_ERROR)
6633 << "Trying to create SCTP transport, but didn't compile with "
6634 "SCTP support (HAVE_SCTP)";
6635 return false;
6636 }
6637 if (!network_thread()->Invoke<bool>(
6638 RTC_FROM_HERE,
6639 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6640 return false;
6641 }
6642 return true;
6643}
6644
6645bool PeerConnection::SetupDataChannelTransport(const std::string& mid) {
6646 if (!network_thread()->Invoke<bool>(
6647 RTC_FROM_HERE,
6648 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this, mid))) {
6649 return false;
6650 }
Steve Anton75737c02017-11-06 10:37:17 -08006651 return true;
6652}
6653
6654Call::Stats PeerConnection::GetCallStats() {
6655 if (!worker_thread()->IsCurrent()) {
6656 return worker_thread()->Invoke<Call::Stats>(
6657 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6658 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006659 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006660 if (call_) {
6661 return call_->GetStats();
6662 } else {
6663 return Call::Stats();
6664 }
6665}
6666
Zhi Huange830e682018-03-30 10:48:35 -07006667bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006668 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006669 RTC_DCHECK(sctp_factory_);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006670 RTC_LOG(LS_INFO) << "Creating SCTP transport for mid=" << mid;
6671
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006672 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6673 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006674 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006675 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006676 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006677 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6678 sctp_factory_->CreateSctpTransport(dtls_transport);
6679 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006680 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006681 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006682 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006683 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006684 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006685 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6686 // another thread. Would be nice if there was a helper class similar to
6687 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6688 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006689 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006690 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006691 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006692 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006693 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006694 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6695 std::move(cricket_sctp_transport));
6696 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006697 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006698}
6699
6700void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006701 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006702 RTC_LOG(LS_INFO) << "Destroying SCTP transport for mid=" << *sctp_mid_;
6703
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006704 sctp_transport_->Clear();
6705 sctp_transport_ = nullptr;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006706 // |sctp_mid_| may still be active through a data channel transport. If not,
6707 // unset it.
6708 if (!data_channel_transport_) {
6709 sctp_mid_.reset();
6710 }
Steve Anton75737c02017-11-06 10:37:17 -08006711 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006712}
6713
6714void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006715 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006716 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6717 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006718 // Note: Cannot use rtc::Bind here because it will grab a reference to
6719 // PeerConnection and potentially cause PeerConnection to live longer than
6720 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6721 // be destroyed before PeerConnection is destroyed, and at that point all
6722 // pending tasks will be cleared.
6723 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6724 OnSctpTransportReadyToSendData_s(true);
6725 });
6726}
6727
6728void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006729 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006730 sctp_ready_to_send_data_ = ready;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006731 if (sctp_negotiated_) {
6732 SignalSctpReadyToSendData(ready);
6733 }
Steve Anton75737c02017-11-06 10:37:17 -08006734}
6735
6736void PeerConnection::OnSctpTransportDataReceived_n(
6737 const cricket::ReceiveDataParams& params,
6738 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006739 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006740 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6741 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006742 // Note: Cannot use rtc::Bind here because it will grab a reference to
6743 // PeerConnection and potentially cause PeerConnection to live longer than
6744 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6745 // be destroyed before PeerConnection is destroyed, and at that point all
6746 // pending tasks will be cleared.
6747 sctp_invoker_->AsyncInvoke<void>(
6748 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6749 OnSctpTransportDataReceived_s(params, payload);
6750 });
6751}
6752
6753void PeerConnection::OnSctpTransportDataReceived_s(
6754 const cricket::ReceiveDataParams& params,
6755 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006756 RTC_DCHECK_RUN_ON(signaling_thread());
6757 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006758 SignalSctpDataReceived(params, payload);
6759 }
6760}
6761
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006762void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006763 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006764 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6765 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006766 sctp_invoker_->AsyncInvoke<void>(
6767 RTC_FROM_HERE, signaling_thread(),
6768 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006769 &SignalSctpClosingProcedureStartedRemotely, sid));
6770}
6771
6772void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006773 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006774 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP ||
6775 data_channel_type_ == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006776 sctp_invoker_->AsyncInvoke<void>(
6777 RTC_FROM_HERE, signaling_thread(),
6778 rtc::Bind(&sigslot::signal1<int>::operator(),
6779 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006780}
6781
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006782bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
6783 data_channel_transport_ = transport_controller_->GetDataChannelTransport(mid);
6784 if (!data_channel_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006785 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006786 << "Data channel transport is not available for data channels, mid="
6787 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006788 return false;
6789 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006790 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006791
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006792 data_channel_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6793 data_channel_transport_->SetDataSink(this);
6794 sctp_mid_ = mid;
6795 // TODO(mellem): Handling data channel state through media transport is
6796 // deprecated. Delete these lines when downstream implementations call
6797 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006798 transport_controller_->SignalMediaTransportStateChanged.connect(
6799 this, &PeerConnection::OnMediaTransportStateChanged_n);
6800 // Check the initial state right away, in case transport is already writable.
6801 OnMediaTransportStateChanged_n();
6802 return true;
6803}
6804
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006805void PeerConnection::TeardownDataChannelTransport_n() {
6806 if (!data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006807 return;
6808 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006809 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6810 << *sctp_mid_;
6811
6812 // TODO(mellem): Delete this line when downstream implementations call
6813 // DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006814 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006815 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6816 // it.
6817 if (!sctp_transport_) {
6818 sctp_mid_.reset();
6819 }
6820 data_channel_transport_->SetDataSink(nullptr);
6821 data_channel_transport_invoker_ = nullptr;
6822 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006823}
6824
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006825// TODO(mellem): Handling of data channel state through the media transport
6826// callback is deprecated. This function should be deleted once downstream
6827// implementations call DataChannelSink::OnStateChanged().
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006828void PeerConnection::OnMediaTransportStateChanged_n() {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006829 if (!sctp_mid_ || transport_controller_->GetMediaTransportState(*sctp_mid_) !=
6830 MediaTransportState::kWritable) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006831 return;
6832 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006833 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006834 RTC_FROM_HERE, signaling_thread(), [this] {
6835 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006836 data_channel_transport_ready_to_send_ = true;
6837 if (data_channel_transport_negotiated_) {
6838 SignalDataChannelTransportWritable_s(
6839 data_channel_transport_ready_to_send_);
6840 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006841 });
6842}
6843
Steve Anton75737c02017-11-06 10:37:17 -08006844// Returns false if bundle is enabled and rtcp_mux is disabled.
6845bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6846 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6847 if (!bundle_enabled)
6848 return true;
6849
6850 const cricket::ContentGroup* bundle_group =
6851 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6852 RTC_DCHECK(bundle_group != NULL);
6853
6854 const cricket::ContentInfos& contents = desc->contents();
6855 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6856 citer != contents.end(); ++citer) {
6857 const cricket::ContentInfo* content = (&*citer);
6858 RTC_DCHECK(content != NULL);
6859 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006860 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006861 if (!HasRtcpMuxEnabled(content))
6862 return false;
6863 }
6864 }
6865 // RTCP-MUX is enabled in all the contents.
6866 return true;
6867}
6868
6869bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006870 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006871}
6872
Steve Anton06817cd2018-12-18 15:55:30 -08006873static RTCError ValidateMids(const cricket::SessionDescription& description) {
6874 std::set<std::string> mids;
6875 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006876 if (content.name.empty()) {
6877 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6878 "A media section is missing a MID attribute.");
6879 }
Steve Anton06817cd2018-12-18 15:55:30 -08006880 if (!mids.insert(content.name).second) {
6881 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6882 "Duplicate a=mid value '" + content.name + "'.");
6883 }
6884 }
6885 return RTCError::OK();
6886}
6887
Steve Anton8a006912017-12-04 15:25:56 -08006888RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006889 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006890 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006891 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006892 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006893 }
6894
6895 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006896 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006897 }
6898
Steve Anton3828c062017-12-06 10:34:51 -08006899 SdpType type = sdesc->GetType();
6900 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6901 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006902 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006903 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006904 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006905 }
6906
Steve Anton06817cd2018-12-18 15:55:30 -08006907 RTCError error = ValidateMids(*sdesc->description());
6908 if (!error.ok()) {
6909 return error;
6910 }
6911
Steve Anton75737c02017-11-06 10:37:17 -08006912 // Verify crypto settings.
6913 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006914 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6915 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006916 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006917 if (!crypto_error.ok()) {
6918 return crypto_error;
6919 }
Steve Anton75737c02017-11-06 10:37:17 -08006920 }
6921
6922 // Verify ice-ufrag and ice-pwd.
6923 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006924 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6925 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006926 }
6927
6928 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006929 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6930 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006931 }
6932
6933 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6934 // m-lines that do not rtcp-mux enabled.
6935
6936 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006937 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006938 // With an answer we want to compare the new answer session description with
6939 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006940 const cricket::SessionDescription* offer_desc =
6941 (source == cricket::CS_LOCAL) ? remote_description()->description()
6942 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006943 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6944 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6945 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006946 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6947 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006948 }
6949 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006950 // The re-offers should respect the order of m= sections in current
6951 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006952 // With a re-offer, either the current local or current remote descriptions
6953 // could be the most up to date, so we would like to check against both of
6954 // them if they exist. It could be the case that one of them has a 0 port
6955 // for a media section, but the other does not. This is important to check
6956 // against in the case that we are recycling an m= section.
6957 const cricket::SessionDescription* current_desc = nullptr;
6958 const cricket::SessionDescription* secondary_current_desc = nullptr;
6959 if (local_description()) {
6960 current_desc = local_description()->description();
6961 if (remote_description()) {
6962 secondary_current_desc = remote_description()->description();
6963 }
6964 } else if (remote_description()) {
6965 current_desc = remote_description()->description();
6966 }
Steve Anton75737c02017-11-06 10:37:17 -08006967 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006968 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6969 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006970 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6971 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006972 }
6973 }
6974
Steve Antonba42e992018-04-09 14:10:01 -07006975 if (IsUnifiedPlan()) {
6976 // Ensure that each audio and video media section has at most one
6977 // "StreamParams". This will return an error if receiving a session
6978 // description from a "Plan B" endpoint which adds multiple tracks of the
6979 // same type. With Unified Plan, there can only be at most one track per
6980 // media section.
6981 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006982 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006983 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6984 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6985 desc.streams().size() > 1u) {
6986 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6987 "Media section has more than one track specified "
6988 "with a=ssrc lines which is not supported with "
6989 "Unified Plan.");
6990 }
6991 }
6992 }
6993
Steve Anton8a006912017-12-04 15:25:56 -08006994 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006995}
6996
Steve Anton3828c062017-12-06 10:34:51 -08006997bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006998 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006999 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007000 return (state == PeerConnectionInterface::kStable) ||
7001 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08007002 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007003 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007004 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7005 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7006 }
7007}
7008
Steve Anton3828c062017-12-06 10:34:51 -08007009bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007010 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007011 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007012 return (state == PeerConnectionInterface::kStable) ||
7013 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08007014 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007015 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007016 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7017 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7018 }
7019}
7020
Steve Antonf8470812017-12-04 10:46:21 -08007021const char* PeerConnection::SessionErrorToString(SessionError error) const {
7022 switch (error) {
7023 case SessionError::kNone:
7024 return "ERROR_NONE";
7025 case SessionError::kContent:
7026 return "ERROR_CONTENT";
7027 case SessionError::kTransport:
7028 return "ERROR_TRANSPORT";
7029 }
7030 RTC_NOTREACHED();
7031 return "";
7032}
7033
Steve Anton75737c02017-11-06 10:37:17 -08007034std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02007035 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08007036 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7037 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02007038 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08007039}
7040
Steve Anton8e20f172018-03-06 10:55:04 -08007041void PeerConnection::ReportSdpFormatReceived(
7042 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08007043 int num_audio_mlines = 0;
7044 int num_video_mlines = 0;
7045 int num_audio_tracks = 0;
7046 int num_video_tracks = 0;
7047 for (const ContentInfo& content : remote_offer.description()->contents()) {
7048 cricket::MediaType media_type = content.media_description()->type();
7049 int num_tracks = std::max(
7050 1, static_cast<int>(content.media_description()->streams().size()));
7051 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7052 num_audio_mlines += 1;
7053 num_audio_tracks += num_tracks;
7054 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7055 num_video_mlines += 1;
7056 num_video_tracks += num_tracks;
7057 }
7058 }
7059 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7060 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7061 format = kSdpFormatReceivedComplexUnifiedPlan;
7062 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7063 format = kSdpFormatReceivedComplexPlanB;
7064 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7065 format = kSdpFormatReceivedSimple;
7066 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007067 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7068 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007069}
7070
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007071void PeerConnection::ReportIceCandidateCollected(
7072 const cricket::Candidate& candidate) {
7073 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7074 if (candidate.address().IsPrivateIP()) {
7075 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7076 }
7077 if (candidate.address().IsUnresolvedIP()) {
7078 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7079 }
7080 if (candidate.address().family() == AF_INET6) {
7081 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7082 }
7083}
7084
7085void PeerConnection::ReportRemoteIceCandidateAdded(
7086 const cricket::Candidate& candidate) {
7087 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7088 if (candidate.address().IsPrivateIP()) {
7089 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7090 }
7091 if (candidate.address().IsUnresolvedIP()) {
7092 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7093 }
7094 if (candidate.address().family() == AF_INET6) {
7095 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7096 }
7097}
7098
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007099void PeerConnection::NoteUsageEvent(UsageEvent event) {
7100 RTC_DCHECK_RUN_ON(signaling_thread());
7101 usage_event_accumulator_ |= static_cast<int>(event);
7102}
7103
7104void PeerConnection::ReportUsagePattern() const {
7105 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007106 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7107 usage_event_accumulator_,
7108 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007109 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007110 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007111 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7112 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007113 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007114 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7115 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7116 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7117 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007118 // If called after close(), we can't report, because observer may have
7119 // been deallocated, and therefore pointer is null. Write to log instead.
7120 if (observer_) {
7121 Observer()->OnInterestingUsage(usage_event_accumulator_);
7122 } else {
7123 RTC_LOG(LS_INFO) << "Interesting usage signature "
7124 << usage_event_accumulator_
7125 << " observed after observer shutdown";
7126 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007127 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007128}
7129
Steve Anton0ffaaa22018-02-23 10:31:30 -08007130void PeerConnection::ReportNegotiatedSdpSemantics(
7131 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007132 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007133 switch (answer.description()->msid_signaling()) {
7134 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007135 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007136 break;
7137 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007138 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007139 break;
7140 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007141 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007142 break;
7143 case cricket::kMsidSignalingMediaSection |
7144 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007145 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007146 break;
7147 default:
7148 RTC_NOTREACHED();
7149 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007150 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7151 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007152}
7153
Steve Anton75737c02017-11-06 10:37:17 -08007154// We need to check the local/remote description for the Transport instead of
7155// the session, because a new Transport added during renegotiation may have
7156// them unset while the session has them set from the previous negotiation.
7157// Not doing so may trigger the auto generation of transport description and
7158// mess up DTLS identity information, ICE credential, etc.
7159bool PeerConnection::ReadyToUseRemoteCandidate(
7160 const IceCandidateInterface* candidate,
7161 const SessionDescriptionInterface* remote_desc,
7162 bool* valid) {
7163 *valid = true;
7164
7165 const SessionDescriptionInterface* current_remote_desc =
7166 remote_desc ? remote_desc : remote_description();
7167
7168 if (!current_remote_desc) {
7169 return false;
7170 }
7171
Guido Urdaneta41633172019-05-23 20:12:29 +02007172 RTCErrorOr<const cricket::ContentInfo*> result =
7173 FindContentInfo(current_remote_desc, candidate);
7174 if (!result.ok()) {
7175 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7176 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007177
7178 *valid = false;
7179 return false;
7180 }
7181
Guido Urdaneta41633172019-05-23 20:12:29 +02007182 std::string transport_name = GetTransportName(result.value()->name);
7183 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007184}
7185
7186bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007187 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007188 (dtls_enabled_ ||
7189 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007190}
7191
7192void PeerConnection::OnTransportControllerGatheringState(
7193 cricket::IceGatheringState state) {
7194 RTC_DCHECK(signaling_thread()->IsCurrent());
7195 if (state == cricket::kIceGatheringGathering) {
7196 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7197 } else if (state == cricket::kIceGatheringComplete) {
7198 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7199 }
7200}
7201
7202void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007203 std::map<std::string, std::set<cricket::MediaType>>
7204 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007205 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007206 if (transceiver->internal()->channel()) {
7207 const std::string& transport_name =
7208 transceiver->internal()->channel()->transport_name();
7209 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007210 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007211 }
Steve Anton75737c02017-11-06 10:37:17 -08007212 }
7213 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007214 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7215 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007216 }
Zhi Huange830e682018-03-30 10:48:35 -07007217
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007218 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007219 if (transport_name) {
7220 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007221 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007222 }
Zhi Huange830e682018-03-30 10:48:35 -07007223
Steve Antonc7b964c2018-02-01 14:39:45 -08007224 for (const auto& entry : media_types_by_transport_name) {
7225 const std::string& transport_name = entry.first;
7226 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007227 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007228 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007229 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007230 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007231 }
7232 }
7233}
7234// Walk through the ConnectionInfos to gather best connection usage
7235// for IPv4 and IPv6.
7236void PeerConnection::ReportBestConnectionState(
7237 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007238 for (const cricket::TransportChannelStats& channel_stats :
7239 stats.channel_stats) {
7240 for (const cricket::ConnectionInfo& connection_info :
7241 channel_stats.connection_infos) {
7242 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007243 continue;
7244 }
7245
Steve Antonc7b964c2018-02-01 14:39:45 -08007246 const cricket::Candidate& local = connection_info.local_candidate;
7247 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007248
7249 // Increment the counter for IceCandidatePairType.
7250 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7251 (local.type() == RELAY_PORT_TYPE &&
7252 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007253 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7254 GetIceCandidatePairCounter(local, remote),
7255 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007256 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007257 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7258 GetIceCandidatePairCounter(local, remote),
7259 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007260 } else {
7261 RTC_CHECK(0);
7262 }
Steve Anton75737c02017-11-06 10:37:17 -08007263
7264 // Increment the counter for IP type.
7265 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007266 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7267 kBestConnections_IPv4,
7268 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007269 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007270 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7271 kBestConnections_IPv6,
7272 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007273 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007274 RTC_CHECK(!local.address().hostname().empty() &&
7275 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007276 }
7277
7278 return;
7279 }
7280 }
7281}
7282
7283void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007284 const cricket::TransportStats& stats,
7285 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007286 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7287 return;
7288 }
7289
7290 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7291 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7292 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7293 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7294 return;
7295 }
7296
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007297 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7298 for (cricket::MediaType media_type : media_types) {
7299 switch (media_type) {
7300 case cricket::MEDIA_TYPE_AUDIO:
7301 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7302 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7303 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7304 break;
7305 case cricket::MEDIA_TYPE_VIDEO:
7306 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7307 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7308 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7309 break;
7310 case cricket::MEDIA_TYPE_DATA:
7311 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7312 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7313 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7314 break;
7315 default:
7316 RTC_NOTREACHED();
7317 continue;
7318 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007319 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007320 }
7321
7322 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7323 for (cricket::MediaType media_type : media_types) {
7324 switch (media_type) {
7325 case cricket::MEDIA_TYPE_AUDIO:
7326 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7327 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7328 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7329 break;
7330 case cricket::MEDIA_TYPE_VIDEO:
7331 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7332 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7333 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7334 break;
7335 case cricket::MEDIA_TYPE_DATA:
7336 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7337 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7338 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7339 break;
7340 default:
7341 RTC_NOTREACHED();
7342 continue;
7343 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007344 }
Steve Anton75737c02017-11-06 10:37:17 -08007345 }
7346}
7347
7348void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007349 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007350 RTC_DCHECK(call_);
7351 call_->OnSentPacket(sent_packet);
7352}
7353
7354const std::string PeerConnection::GetTransportName(
7355 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007356 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007357 if (channel) {
7358 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007359 }
Steve Anton6fec8802017-12-04 10:37:29 -08007360 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007361 RTC_DCHECK(sctp_mid_);
7362 if (content_name == *sctp_mid_) {
7363 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007364 }
7365 }
7366 // Return an empty string if failed to retrieve the transport name.
7367 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007368}
7369
Steve Anton6fec8802017-12-04 10:37:29 -08007370void PeerConnection::DestroyTransceiverChannel(
7371 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7372 transceiver) {
7373 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007374
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007375 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007376 if (channel) {
7377 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007378 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007379 }
7380}
7381
7382void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007383 if (rtp_data_channel_) {
7384 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007385 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007386 rtp_data_channel_ = nullptr;
7387 }
7388
7389 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7390 // grab a reference to this PeerConnection. If this is called from the
7391 // PeerConnection destructor, the RefCountedObject vtable will have already
7392 // been destroyed (since it is a subclass of PeerConnection) and using
7393 // rtc::Bind will cause "Pure virtual function called" error to appear.
7394
7395 if (sctp_transport_) {
7396 OnDataChannelDestroyed();
7397 network_thread()->Invoke<void>(RTC_FROM_HERE,
7398 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007399 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007400 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007401
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007402 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007403 OnDataChannelDestroyed();
7404 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7405 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007406 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007407 });
7408 }
Steve Anton6fec8802017-12-04 10:37:29 -08007409}
7410
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007411void PeerConnection::DestroyChannelInterface(
7412 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007413 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007414 switch (channel->media_type()) {
7415 case cricket::MEDIA_TYPE_AUDIO:
7416 channel_manager()->DestroyVoiceChannel(
7417 static_cast<cricket::VoiceChannel*>(channel));
7418 break;
7419 case cricket::MEDIA_TYPE_VIDEO:
7420 channel_manager()->DestroyVideoChannel(
7421 static_cast<cricket::VideoChannel*>(channel));
7422 break;
7423 case cricket::MEDIA_TYPE_DATA:
7424 channel_manager()->DestroyRtpDataChannel(
7425 static_cast<cricket::RtpDataChannel*>(channel));
7426 break;
7427 default:
7428 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7429 break;
7430 }
Zhi Huange830e682018-03-30 10:48:35 -07007431}
Steve Anton6fec8802017-12-04 10:37:29 -08007432
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007433bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007434 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007435 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007436 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007437 MediaTransportInterface* media_transport,
7438 DataChannelTransportInterface* data_channel_transport,
7439 JsepTransportController::NegotiationState negotiation_state) {
Karl Wibergac025892019-03-26 13:08:37 +01007440 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007441 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007442 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007443 auto base_channel = GetChannel(mid);
7444 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007445 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007446 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007447 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007448 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007449 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007450
Karl Wiberg5966c502019-02-21 23:55:09 +01007451 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007452 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007453 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007454
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007455 if (mid == sctp_mid_) {
7456 switch (negotiation_state) {
7457 case JsepTransportController::NegotiationState::kFinal:
7458 if (data_channel_transport) {
7459 if (sctp_transport_) {
7460 DestroySctpTransport_n();
7461 }
7462 } else {
7463 TeardownDataChannelTransport_n();
7464 }
7465 // We also need to mark the remaining transport as ready-to-send.
7466 RTC_FALLTHROUGH();
7467 case JsepTransportController::NegotiationState::kProvisional: {
7468 rtc::AsyncInvoker* invoker = data_channel_transport_invoker_
7469 ? data_channel_transport_invoker_.get()
7470 : sctp_invoker_.get();
7471 if (!invoker) {
7472 break; // Have neither SCTP nor DataChannelTransport, nothing to do.
7473 }
7474 invoker->AsyncInvoke<void>(
7475 RTC_FROM_HERE, signaling_thread(), [this, data_channel_transport] {
7476 RTC_DCHECK_RUN_ON(signaling_thread());
7477 if (data_channel_transport) {
7478 data_channel_transport_negotiated_ = true;
7479 if (data_channel_transport_ready_to_send_) {
7480 SignalDataChannelTransportWritable_s(
7481 data_channel_transport_ready_to_send_);
7482 }
7483 } else {
7484 sctp_negotiated_ = true;
7485 if (sctp_ready_to_send_data_) {
7486 SignalSctpReadyToSendData(sctp_ready_to_send_data_);
7487 }
7488 }
7489 });
7490 } break;
7491 case JsepTransportController::NegotiationState::kInitial:
7492 // Negotiation isn't finished. Nothing to do here.
7493 break;
7494 }
7495 }
7496
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007497 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007498}
7499
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007500void PeerConnection::OnSetStreams() {
7501 RTC_DCHECK_RUN_ON(signaling_thread());
7502 if (IsUnifiedPlan())
7503 UpdateNegotiationNeeded();
7504}
7505
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007506PeerConnectionObserver* PeerConnection::Observer() const {
7507 // In earlier production code, the pointer was not cleared on close,
7508 // which might have led to undefined behavior if the observer was not
7509 // deallocated, or strange crashes if it was.
7510 // We use CHECK in order to catch such behavior if it exists.
7511 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7512 RTC_CHECK(observer_);
7513 return observer_;
7514}
7515
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007516CryptoOptions PeerConnection::GetCryptoOptions() {
7517 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7518 // after it has been removed.
7519 return configuration_.crypto_options.has_value()
7520 ? *configuration_.crypto_options
7521 : factory_->options().crypto_options;
7522}
7523
Harald Alvestrand89061872018-01-02 14:08:34 +01007524void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007525 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007526 if (stats_collector_) {
7527 stats_collector_->ClearCachedStatsReport();
7528 }
7529}
7530
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007531void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007532 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7533 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007534}
7535
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007536void PeerConnection::UpdateNegotiationNeeded() {
7537 RTC_DCHECK_RUN_ON(signaling_thread());
7538 if (!IsUnifiedPlan()) {
7539 Observer()->OnRenegotiationNeeded();
7540 return;
7541 }
7542
7543 // If connection's [[IsClosed]] slot is true, abort these steps.
7544 if (IsClosed())
7545 return;
7546
7547 // If connection's signaling state is not "stable", abort these steps.
7548 if (signaling_state() != kStable)
7549 return;
7550
7551 // NOTE
7552 // The negotiation-needed flag will be updated once the state transitions to
7553 // "stable", as part of the steps for setting an RTCSessionDescription.
7554
7555 // If the result of checking if negotiation is needed is false, clear the
7556 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7557 // to false, and abort these steps.
7558 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7559 if (!is_negotiation_needed) {
7560 is_negotiation_needed_ = false;
7561 return;
7562 }
7563
7564 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7565 // steps.
7566 if (is_negotiation_needed_)
7567 return;
7568
7569 // Set connection's [[NegotiationNeeded]] slot to true.
7570 is_negotiation_needed_ = true;
7571
7572 // Queue a task that runs the following steps:
7573 // If connection's [[IsClosed]] slot is true, abort these steps.
7574 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7575 // Fire an event named negotiationneeded at connection.
7576 Observer()->OnRenegotiationNeeded();
7577}
7578
7579bool PeerConnection::CheckIfNegotiationIsNeeded() {
7580 RTC_DCHECK_RUN_ON(signaling_thread());
7581 // 1. If any implementation-specific negotiation is required, as described at
7582 // the start of this section, return true.
7583
Henrik Boström79b69802019-07-18 11:16:56 +02007584 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7585 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7586 return true;
7587 }
7588
7589 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007590 const SessionDescriptionInterface* description = current_local_description();
7591 if (!description)
7592 return true;
7593
Henrik Boström79b69802019-07-18 11:16:56 +02007594 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007595 // description has been negotiated yet for data, return true.
7596 if (!sctp_data_channels_.empty()) {
7597 if (!cricket::GetFirstDataContent(description->description()->contents()))
7598 return true;
7599 }
7600
Henrik Boström79b69802019-07-18 11:16:56 +02007601 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007602 // following checks:
7603 for (const auto& transceiver : transceivers_) {
7604 const ContentInfo* current_local_msection =
7605 FindTransceiverMSection(transceiver.get(), description);
7606
7607 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7608 transceiver.get(), current_remote_description());
7609
Henrik Boström79b69802019-07-18 11:16:56 +02007610 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007611 // but the associated m= section is not yet rejected in
7612 // connection.[[CurrentLocalDescription]] or
7613 // connection.[[CurrentRemoteDescription]], return true.
7614 if (transceiver->stopped()) {
7615 if (current_local_msection && !current_local_msection->rejected &&
7616 ((current_remote_msection && !current_remote_msection->rejected) ||
7617 !current_remote_msection)) {
7618 return true;
7619 }
7620 continue;
7621 }
7622
Henrik Boström79b69802019-07-18 11:16:56 +02007623 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007624 // section in description, return true.
7625 if (!current_local_msection)
7626 return true;
7627
7628 const MediaContentDescription* current_local_media_description =
7629 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007630 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007631 // in description then perform the following checks:
7632
Henrik Boström79b69802019-07-18 11:16:56 +02007633 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007634 // associated m= section in description either doesn't contain a single
7635 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7636 // m= section, or the MSID values themselves, differ from what is in
7637 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7638 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7639 if (current_local_media_description->streams().size() == 0)
7640 return true;
7641
7642 std::vector<std::string> msection_msids;
7643 for (const auto& stream : current_local_media_description->streams()) {
7644 for (const std::string& msid : stream.stream_ids())
7645 msection_msids.push_back(msid);
7646 }
7647
7648 std::vector<std::string> transceiver_msids =
7649 transceiver->sender()->stream_ids();
7650 if (msection_msids.size() != transceiver_msids.size())
7651 return true;
7652
7653 absl::c_sort(transceiver_msids);
7654 absl::c_sort(msection_msids);
7655 if (transceiver_msids != msection_msids)
7656 return true;
7657 }
7658
Henrik Boström79b69802019-07-18 11:16:56 +02007659 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007660 // associated m= section in neither connection.[[CurrentLocalDescription]]
7661 // nor connection.[[CurrentRemoteDescription]] matches
7662 // transceiver.[[Direction]], return true.
7663 if (description->GetType() == SdpType::kOffer) {
7664 if (!current_remote_description())
7665 return true;
7666
7667 if (!current_remote_msection)
7668 return true;
7669
7670 RtpTransceiverDirection current_local_direction =
7671 current_local_media_description->direction();
7672 RtpTransceiverDirection current_remote_direction =
7673 current_remote_msection->media_description()->direction();
7674 if (transceiver->direction() != current_local_direction &&
7675 transceiver->direction() !=
7676 RtpTransceiverDirectionReversed(current_remote_direction)) {
7677 return true;
7678 }
7679 }
7680
Henrik Boström79b69802019-07-18 11:16:56 +02007681 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007682 // associated m= section in the description does not match
7683 // transceiver.[[Direction]] intersected with the offered direction (as
7684 // described in [JSEP] (section 5.3.1.)), return true.
7685 if (description->GetType() == SdpType::kAnswer) {
7686 if (!remote_description())
7687 return true;
7688
7689 const ContentInfo* offered_remote_msection =
7690 FindTransceiverMSection(transceiver.get(), remote_description());
7691
7692 RtpTransceiverDirection offered_direction =
7693 offered_remote_msection
7694 ? offered_remote_msection->media_description()->direction()
7695 : RtpTransceiverDirection::kInactive;
7696
7697 if (current_local_media_description->direction() !=
7698 (RtpTransceiverDirectionIntersection(
7699 transceiver->direction(),
7700 RtpTransceiverDirectionReversed(offered_direction)))) {
7701 return true;
7702 }
7703 }
7704 }
7705
7706 // If all the preceding checks were performed and true was not returned,
7707 // nothing remains to be negotiated; return false.
7708 return false;
7709}
7710
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007711} // namespace webrtc