blob: cc334b1c0eca7d4b626f9a14f51beef71787fd69 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070062#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080073using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080074using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080075using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080078using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070079using cricket::RELAY_PORT_TYPE;
80using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080081
Steve Antonba818672017-11-06 10:21:57 -080082namespace webrtc {
83
Steve Anton75737c02017-11-06 10:37:17 -080084// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080088const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080096const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
Steve Anton75737c02017-11-06 10:37:17 -0800108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700110// Field trials.
111// Controls datagram transport support.
112const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
113
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800114// UMA metric names.
115const char kSimulcastVersionApplyLocalDescription[] =
116 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
117const char kSimulcastVersionApplyRemoteDescription[] =
118 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
119const char kSimulcastNumberOfEncodings[] =
120 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
121const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
122
Seth Hampson845e8782018-03-02 11:34:10 -0800123static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800124static const char kDefaultAudioSenderId[] = "defaulta0";
125static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700126
zhihuang8f65cdf2016-05-06 18:40:30 -0700127// The length of RTCP CNAMEs.
128static const int kRtcpCnameLength = 16;
129
Steve Antonad182762018-09-05 20:22:40 +0000130enum {
131 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
132 MSG_SET_SESSIONDESCRIPTION_FAILED,
133 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
134 MSG_GETSTATS,
135 MSG_FREE_DATACHANNELS,
136 MSG_REPORT_USAGE_PATTERN,
137};
138
Harald Alvestrand19793842018-06-25 12:03:50 +0200139static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
140
Steve Antonad182762018-09-05 20:22:40 +0000141struct SetSessionDescriptionMsg : public rtc::MessageData {
142 explicit SetSessionDescriptionMsg(
143 webrtc::SetSessionDescriptionObserver* observer)
144 : observer(observer) {}
145
146 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
147 RTCError error;
148};
149
150struct CreateSessionDescriptionMsg : public rtc::MessageData {
151 explicit CreateSessionDescriptionMsg(
152 webrtc::CreateSessionDescriptionObserver* observer)
153 : observer(observer) {}
154
155 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
156 RTCError error;
157};
158
159struct GetStatsMsg : public rtc::MessageData {
160 GetStatsMsg(webrtc::StatsObserver* observer,
161 webrtc::MediaStreamTrackInterface* track)
162 : observer(observer), track(track) {}
163 rtc::scoped_refptr<webrtc::StatsObserver> observer;
164 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
165};
166
deadbeefab9b2d12015-10-14 11:33:11 -0700167// Check if we can send |new_stream| on a PeerConnection.
168bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
169 webrtc::MediaStreamInterface* new_stream) {
170 if (!new_stream || !current_streams) {
171 return false;
172 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700173 if (current_streams->find(new_stream->id()) != nullptr) {
174 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100175 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700176 return false;
177 }
178 return true;
179}
180
deadbeef5e97fb52015-10-15 12:49:08 -0700181// If the direction is "recvonly" or "inactive", treat the description
182// as containing no streams.
183// See: https://code.google.com/p/webrtc/issues/detail?id=5054
184std::vector<cricket::StreamParams> GetActiveStreams(
185 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800186 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700187 ? desc->streams()
188 : std::vector<cricket::StreamParams>();
189}
190
deadbeefab9b2d12015-10-14 11:33:11 -0700191bool IsValidOfferToReceiveMedia(int value) {
192 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
193 return (value >= Options::kUndefined) &&
194 (value <= Options::kMaxOfferToReceiveMedia);
195}
196
zhihuang1c378ed2017-08-17 14:10:50 -0700197// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800198void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700199 const std::vector<rtc::scoped_refptr<
200 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700201 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200202 cricket::MediaDescriptionOptions* video_media_description_options,
203 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700204 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
206 if (audio_media_description_options) {
207 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700208 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700209 }
210 } else {
211 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
212 if (video_media_description_options) {
213 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800214 sender->id(), sender->internal()->stream_ids(), {},
215 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700216 }
217 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700218 }
zhihuang1c378ed2017-08-17 14:10:50 -0700219}
olka3c747662017-08-17 06:50:32 -0700220
zhihuang1c378ed2017-08-17 14:10:50 -0700221// Add options to |session_options| from |rtp_data_channels|.
222void AddRtpDataChannelOptions(
223 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
224 rtp_data_channels,
225 cricket::MediaDescriptionOptions* data_media_description_options) {
226 if (!data_media_description_options) {
227 return;
228 }
deadbeefab9b2d12015-10-14 11:33:11 -0700229 // Check for data channels.
230 for (const auto& kv : rtp_data_channels) {
231 const DataChannel* channel = kv.second;
232 if (channel->state() == DataChannel::kConnecting ||
233 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700234 // Legacy RTP data channels are signaled with the track/stream ID set to
235 // the data channel's label.
236 data_media_description_options->AddRtpDataChannel(channel->label(),
237 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700238 }
239 }
240}
241
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700242uint32_t ConvertIceTransportTypeToCandidateFilter(
243 PeerConnectionInterface::IceTransportsType type) {
244 switch (type) {
245 case PeerConnectionInterface::kNone:
246 return cricket::CF_NONE;
247 case PeerConnectionInterface::kRelay:
248 return cricket::CF_RELAY;
249 case PeerConnectionInterface::kNoHost:
250 return (cricket::CF_ALL & ~cricket::CF_HOST);
251 case PeerConnectionInterface::kAll:
252 return cricket::CF_ALL;
253 default:
nissec80e7412017-01-11 05:56:46 -0800254 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700255 }
256 return cricket::CF_NONE;
257}
258
Steve Antonba818672017-11-06 10:21:57 -0800259std::string GetSignalingStateString(
260 PeerConnectionInterface::SignalingState state) {
261 switch (state) {
262 case PeerConnectionInterface::kStable:
263 return "kStable";
264 case PeerConnectionInterface::kHaveLocalOffer:
265 return "kHaveLocalOffer";
266 case PeerConnectionInterface::kHaveLocalPrAnswer:
267 return "kHavePrAnswer";
268 case PeerConnectionInterface::kHaveRemoteOffer:
269 return "kHaveRemoteOffer";
270 case PeerConnectionInterface::kHaveRemotePrAnswer:
271 return "kHaveRemotePrAnswer";
272 case PeerConnectionInterface::kClosed:
273 return "kClosed";
274 }
275 RTC_NOTREACHED();
276 return "";
277}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700278
Steve Anton75737c02017-11-06 10:37:17 -0800279IceCandidatePairType GetIceCandidatePairCounter(
280 const cricket::Candidate& local,
281 const cricket::Candidate& remote) {
282 const auto& l = local.type();
283 const auto& r = remote.type();
284 const auto& host = LOCAL_PORT_TYPE;
285 const auto& srflx = STUN_PORT_TYPE;
286 const auto& relay = RELAY_PORT_TYPE;
287 const auto& prflx = PRFLX_PORT_TYPE;
288 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800289 bool local_hostname =
290 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
291 bool remote_hostname = !remote.address().hostname().empty() &&
292 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800293 bool local_private = IPIsPrivate(local.address().ipaddr());
294 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800295 if (local_hostname) {
296 if (remote_hostname) {
297 return kIceCandidatePairHostNameHostName;
298 } else if (remote_private) {
299 return kIceCandidatePairHostNameHostPrivate;
300 } else {
301 return kIceCandidatePairHostNameHostPublic;
302 }
303 } else if (local_private) {
304 if (remote_hostname) {
305 return kIceCandidatePairHostPrivateHostName;
306 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800307 return kIceCandidatePairHostPrivateHostPrivate;
308 } else {
309 return kIceCandidatePairHostPrivateHostPublic;
310 }
311 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800312 if (remote_hostname) {
313 return kIceCandidatePairHostPublicHostName;
314 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800315 return kIceCandidatePairHostPublicHostPrivate;
316 } else {
317 return kIceCandidatePairHostPublicHostPublic;
318 }
319 }
320 }
321 if (l == host && r == srflx)
322 return kIceCandidatePairHostSrflx;
323 if (l == host && r == relay)
324 return kIceCandidatePairHostRelay;
325 if (l == host && r == prflx)
326 return kIceCandidatePairHostPrflx;
327 if (l == srflx && r == host)
328 return kIceCandidatePairSrflxHost;
329 if (l == srflx && r == srflx)
330 return kIceCandidatePairSrflxSrflx;
331 if (l == srflx && r == relay)
332 return kIceCandidatePairSrflxRelay;
333 if (l == srflx && r == prflx)
334 return kIceCandidatePairSrflxPrflx;
335 if (l == relay && r == host)
336 return kIceCandidatePairRelayHost;
337 if (l == relay && r == srflx)
338 return kIceCandidatePairRelaySrflx;
339 if (l == relay && r == relay)
340 return kIceCandidatePairRelayRelay;
341 if (l == relay && r == prflx)
342 return kIceCandidatePairRelayPrflx;
343 if (l == prflx && r == host)
344 return kIceCandidatePairPrflxHost;
345 if (l == prflx && r == srflx)
346 return kIceCandidatePairPrflxSrflx;
347 if (l == prflx && r == relay)
348 return kIceCandidatePairPrflxRelay;
349 return kIceCandidatePairMax;
350}
351
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800352// Logic to decide if an m= section can be recycled. This means that the new
353// m= section is not rejected, but the old local or remote m= section is
354// rejected. |old_content_one| and |old_content_two| refer to the m= section
355// of the old remote and old local descriptions in no particular order.
356// We need to check both the old local and remote because either
357// could be the most current from the latest negotation.
358bool IsMediaSectionBeingRecycled(SdpType type,
359 const ContentInfo& content,
360 const ContentInfo* old_content_one,
361 const ContentInfo* old_content_two) {
362 return type == SdpType::kOffer && !content.rejected &&
363 ((old_content_one && old_content_one->rejected) ||
364 (old_content_two && old_content_two->rejected));
365}
366
Steve Anton75737c02017-11-06 10:37:17 -0800367// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368// |current_desc|. The number of m= sections in |new_desc| should be no
369// less than |current_desc|. In the case of checking an answer's
370// |new_desc|, the |current_desc| is the last offer that was set as the
371// local or remote. In the case of checking an offer's |new_desc| we
372// check against the local and remote descriptions stored from the last
373// negotiation, because either of these could be the most up to date for
374// possible rejected m sections. These are the |current_desc| and
375// |secondary_current_desc|.
376bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
377 const SessionDescription* secondary_current_desc,
378 const SessionDescription& new_desc,
379 const SdpType type) {
380 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800381 return false;
382 }
383
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800384 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
385 const cricket::ContentInfo* secondary_content_info = nullptr;
386 if (secondary_current_desc &&
387 i < secondary_current_desc->contents().size()) {
388 secondary_content_info = &secondary_current_desc->contents()[i];
389 }
390 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
391 &current_desc.contents()[i],
392 secondary_content_info)) {
393 // For new offer descriptions, if the media section can be recycled, it's
394 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800395 continue;
396 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800397 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800398 return false;
399 }
400 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401 new_desc.contents()[i].media_description();
402 const MediaContentDescription* current_desc_mdesc =
403 current_desc.contents()[i].media_description();
404 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800405 return false;
406 }
407 }
408 return true;
409}
410
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800411bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
412 const SessionDescription& desc2) {
413 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800414}
415
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700416void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
417 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 // Array of structs needed to map {KeyExchangeProtocolType,
419 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
420 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
421 static constexpr struct {
422 KeyExchangeProtocolType protocol_type;
423 cricket::MediaType media_type;
424 KeyExchangeProtocolMedia protocol_media;
425 } kEnumCounterKeyProtocolMediaMap[] = {
426 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
427 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
428 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
429 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
431 kEnumCounterKeyProtocolMediaTypeDtlsData},
432 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
433 kEnumCounterKeyProtocolMediaTypeSdesAudio},
434 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
435 kEnumCounterKeyProtocolMediaTypeSdesVideo},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
437 kEnumCounterKeyProtocolMediaTypeSdesData},
438 };
439
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700440 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
441 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100442
Mirko Bonadeiab499822018-09-11 10:43:20 +0200443 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
444 if (i.protocol_type == protocol_type && i.media_type == media_type) {
445 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
446 i.protocol_media,
447 kEnumCounterKeyProtocolMediaTypeMax);
448 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100449 }
450}
451
Harald Alvestrand76829d72018-07-18 23:24:36 +0200452void NoteAddIceCandidateResult(int result) {
453 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
454 kAddIceCandidateMax);
455}
456
Steve Anton75737c02017-11-06 10:37:17 -0800457// Checks that each non-rejected content has SDES crypto keys or a DTLS
458// fingerprint, unless it's in a BUNDLE group, in which case only the
459// BUNDLE-tag section (first media section/description in the BUNDLE group)
460// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
461// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
462// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700463RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800464 const cricket::ContentGroup* bundle =
465 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800466 for (const cricket::ContentInfo& content_info : desc->contents()) {
467 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 continue;
469 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100470 // Note what media is used with each crypto protocol, for all sections.
471 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
472 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700473 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800474 const std::string& mid = content_info.name;
475 if (bundle && bundle->HasContentName(mid) &&
476 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800477 // This isn't the first media section in the BUNDLE group, so it's not
478 // required to have crypto attributes, since only the crypto attributes
479 // from the first section actually get used.
480 continue;
481 }
482
483 // If the content isn't rejected or bundled into another m= section, crypto
484 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800485 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800486 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800487 if (!media || !tinfo) {
488 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800489 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800490 }
491 if (dtls_enabled) {
492 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100493 RTC_LOG(LS_WARNING)
494 << "Session description must have DTLS fingerprint if "
495 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800496 return RTCError(RTCErrorType::INVALID_PARAMETER,
497 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800498 }
499 } else {
500 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100501 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800502 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800503 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800504 }
505 }
506 }
Steve Anton8a006912017-12-04 15:25:56 -0800507 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800508}
509
510// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
511// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
512// media section/description in the BUNDLE group) needs a ufrag and pwd.
513bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
514 const cricket::ContentGroup* bundle =
515 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800516 for (const cricket::ContentInfo& content_info : desc->contents()) {
517 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800518 continue;
519 }
Steve Anton8a006912017-12-04 15:25:56 -0800520 const std::string& mid = content_info.name;
521 if (bundle && bundle->HasContentName(mid) &&
522 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800523 // This isn't the first media section in the BUNDLE group, so it's not
524 // required to have ufrag/password, since only the ufrag/password from
525 // the first section actually get used.
526 continue;
527 }
528
529 // If the content isn't rejected or bundled into another m= section,
530 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800531 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800532 if (!tinfo) {
533 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100534 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800535 return false;
536 }
537 if (tinfo->description.ice_ufrag.empty() ||
538 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100539 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800540 return false;
541 }
542 }
543 return true;
544}
545
Steve Anton75737c02017-11-06 10:37:17 -0800546// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
547bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
548 const SessionDescriptionInterface* new_desc,
549 const std::string& content_name) {
550 if (!old_desc) {
551 return false;
552 }
553 const SessionDescription* new_sd = new_desc->description();
554 const SessionDescription* old_sd = old_desc->description();
555 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
556 if (!cinfo || cinfo->rejected) {
557 return false;
558 }
559 // If the content isn't rejected, check if ufrag and password has changed.
560 const cricket::TransportDescription* new_transport_desc =
561 new_sd->GetTransportDescriptionByName(content_name);
562 const cricket::TransportDescription* old_transport_desc =
563 old_sd->GetTransportDescriptionByName(content_name);
564 if (!new_transport_desc || !old_transport_desc) {
565 // No transport description exists. This is not an ICE restart.
566 return false;
567 }
568 if (cricket::IceCredentialsChanged(
569 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
570 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100571 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
572 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800573 return true;
574 }
575 return false;
576}
577
Steve Anton80dd7b52018-02-16 17:08:42 -0800578// Generates a string error message for SetLocalDescription/SetRemoteDescription
579// from an RTCError.
580std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
581 SdpType type,
582 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200583 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800584 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
585 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200586 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800587}
588
Seth Hampson5b4f0752018-04-02 16:31:36 -0700589std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
590 std::string output = "streams=[";
591 const char* separator = "";
592 for (const auto& stream_id : stream_ids) {
593 output.append(separator).append(stream_id);
594 separator = ", ";
595 }
596 output.append("]");
597 return output;
598}
599
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200600absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700601 int rtc_configuration_parameter) {
602 if (rtc_configuration_parameter ==
603 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200604 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700605 }
606 return rtc_configuration_parameter;
607}
608
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800609cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
610 switch (type) {
611 case DataMessageType::kText:
612 return cricket::DMT_TEXT;
613 case DataMessageType::kBinary:
614 return cricket::DMT_BINARY;
615 case DataMessageType::kControl:
616 return cricket::DMT_CONTROL;
617 default:
618 return cricket::DMT_NONE;
619 }
620 return cricket::DMT_NONE;
621}
622
623DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
624 switch (type) {
625 case cricket::DMT_TEXT:
626 return DataMessageType::kText;
627 case cricket::DMT_BINARY:
628 return DataMessageType::kBinary;
629 case cricket::DMT_CONTROL:
630 return DataMessageType::kControl;
631 case cricket::DMT_NONE:
632 default:
633 RTC_NOTREACHED();
634 }
635 return DataMessageType::kControl;
636}
637
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800638void ReportSimulcastApiVersion(const char* name,
639 const SessionDescription& session) {
640 bool has_legacy = false;
641 bool has_spec_compliant = false;
642 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200643 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800644 continue;
645 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200646 has_spec_compliant |= content.media_description()->HasSimulcast();
647 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800648 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
649 }
650 }
651
652 if (has_legacy) {
653 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
654 kSimulcastApiVersionMax);
655 }
656 if (has_spec_compliant) {
657 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
658 kSimulcastApiVersionMax);
659 }
660 if (!has_legacy && !has_spec_compliant) {
661 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
662 kSimulcastApiVersionMax);
663 }
664}
665
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200666const ContentInfo* FindTransceiverMSection(
667 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
668 const SessionDescriptionInterface* session_description) {
669 return transceiver->mid()
670 ? session_description->description()->GetContentByName(
671 *transceiver->mid())
672 : nullptr;
673}
674
Steve Anton75737c02017-11-06 10:37:17 -0800675} // namespace
676
Henrik Boström79b69802019-07-18 11:16:56 +0200677class PeerConnection::LocalIceCredentialsToReplace {
678 public:
679 // Sets the ICE credentials that need restarting to the ICE credentials of
680 // the current and pending descriptions.
681 void SetIceCredentialsFromLocalDescriptions(
682 const SessionDescriptionInterface* current_local_description,
683 const SessionDescriptionInterface* pending_local_description) {
684 ice_credentials_.clear();
685 if (current_local_description) {
686 AppendIceCredentialsFromSessionDescription(*current_local_description);
687 }
688 if (pending_local_description) {
689 AppendIceCredentialsFromSessionDescription(*pending_local_description);
690 }
691 }
692
693 void ClearIceCredentials() { ice_credentials_.clear(); }
694
695 // Returns true if we have ICE credentials that need restarting.
696 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
697
698 // Returns true if |local_description| shares no ICE credentials with the
699 // ICE credentials that need restarting.
700 bool SatisfiesIceRestart(
701 const SessionDescriptionInterface& local_description) const {
702 for (const auto& transport_info :
703 local_description.description()->transport_infos()) {
704 if (ice_credentials_.find(std::make_pair(
705 transport_info.description.ice_ufrag,
706 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
707 return false;
708 }
709 }
710 return true;
711 }
712
713 private:
714 void AppendIceCredentialsFromSessionDescription(
715 const SessionDescriptionInterface& desc) {
716 for (const auto& transport_info : desc.description()->transport_infos()) {
717 ice_credentials_.insert(
718 std::make_pair(transport_info.description.ice_ufrag,
719 transport_info.description.ice_pwd));
720 }
721 }
722
723 std::set<std::pair<std::string, std::string>> ice_credentials_;
724};
725
Henrik Boström31638672017-11-23 17:48:32 +0100726// Upon completion, posts a task to execute the callback of the
727// SetSessionDescriptionObserver asynchronously on the same thread. At this
728// point, the state of the peer connection might no longer reflect the effects
729// of the SetRemoteDescription operation, as the peer connection could have been
730// modified during the post.
731// TODO(hbos): Remove this class once we remove the version of
732// PeerConnectionInterface::SetRemoteDescription() that takes a
733// SetSessionDescriptionObserver as an argument.
734class PeerConnection::SetRemoteDescriptionObserverAdapter
735 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
736 public:
737 SetRemoteDescriptionObserverAdapter(
738 rtc::scoped_refptr<PeerConnection> pc,
739 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
740 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
741
742 // SetRemoteDescriptionObserverInterface implementation.
743 void OnSetRemoteDescriptionComplete(RTCError error) override {
744 if (error.ok())
745 pc_->PostSetSessionDescriptionSuccess(wrapper_);
746 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100747 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100748 }
749
750 private:
751 rtc::scoped_refptr<PeerConnection> pc_;
752 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
753};
754
deadbeef293e9262017-01-11 12:28:30 -0800755bool PeerConnectionInterface::RTCConfiguration::operator==(
756 const PeerConnectionInterface::RTCConfiguration& o) const {
757 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700758 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800759 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000760 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700761 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800762 BundlePolicy bundle_policy;
763 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700764 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
765 int ice_candidate_pool_size;
766 bool disable_ipv6;
767 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700768 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100769 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700770 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200771 absl::optional<int> screencast_min_bitrate;
772 absl::optional<bool> combined_audio_video_bwe;
773 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800774 TcpCandidatePolicy tcp_candidate_policy;
775 CandidateNetworkPolicy candidate_network_policy;
776 int audio_jitter_buffer_max_packets;
777 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100778 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100779 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800780 int ice_connection_receiving_timeout;
781 int ice_backup_candidate_pair_ping_interval;
782 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800783 bool prioritize_most_likely_ice_candidate_pairs;
784 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800785 bool prune_turn_ports;
786 bool presume_writable_when_fully_relayed;
787 bool enable_ice_renomination;
788 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700789 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200790 absl::optional<int> ice_check_interval_strong_connectivity;
791 absl::optional<int> ice_check_interval_weak_connectivity;
792 absl::optional<int> ice_check_min_interval;
793 absl::optional<int> ice_unwritable_timeout;
794 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800795 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200796 absl::optional<int> stun_candidate_keepalive_interval;
797 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200798 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800799 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200800 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700801 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700802 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700803 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700804 absl::optional<bool> use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700805 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100806 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800807 };
808 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
809 "Did you add something to RTCConfiguration and forget to "
810 "update operator==?");
811 return type == o.type && servers == o.servers &&
812 bundle_policy == o.bundle_policy &&
813 rtcp_mux_policy == o.rtcp_mux_policy &&
814 tcp_candidate_policy == o.tcp_candidate_policy &&
815 candidate_network_policy == o.candidate_network_policy &&
816 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
817 audio_jitter_buffer_fast_accelerate ==
818 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100819 audio_jitter_buffer_min_delay_ms ==
820 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100821 audio_jitter_buffer_enable_rtx_handling ==
822 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800823 ice_connection_receiving_timeout ==
824 o.ice_connection_receiving_timeout &&
825 ice_backup_candidate_pair_ping_interval ==
826 o.ice_backup_candidate_pair_ping_interval &&
827 continual_gathering_policy == o.continual_gathering_policy &&
828 certificates == o.certificates &&
829 prioritize_most_likely_ice_candidate_pairs ==
830 o.prioritize_most_likely_ice_candidate_pairs &&
831 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800832 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700833 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100834 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800835 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800836 screencast_min_bitrate == o.screencast_min_bitrate &&
837 combined_audio_video_bwe == o.combined_audio_video_bwe &&
838 enable_dtls_srtp == o.enable_dtls_srtp &&
839 ice_candidate_pool_size == o.ice_candidate_pool_size &&
840 prune_turn_ports == o.prune_turn_ports &&
841 presume_writable_when_fully_relayed ==
842 o.presume_writable_when_fully_relayed &&
843 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800844 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700845 surface_ice_candidates_on_ice_transport_type_changed ==
846 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800847 ice_check_interval_strong_connectivity ==
848 o.ice_check_interval_strong_connectivity &&
849 ice_check_interval_weak_connectivity ==
850 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700851 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700852 ice_unwritable_timeout == o.ice_unwritable_timeout &&
853 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800854 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800855 stun_candidate_keepalive_interval ==
856 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200857 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800858 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800859 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700860 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700861 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700862 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700863 use_media_transport_for_data_channels ==
864 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700865 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100866 crypto_options == o.crypto_options &&
867 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800868}
869
870bool PeerConnectionInterface::RTCConfiguration::operator!=(
871 const PeerConnectionInterface::RTCConfiguration& o) const {
872 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800873}
874
zhihuang8f65cdf2016-05-06 18:40:30 -0700875// Generate a RTCP CNAME when a PeerConnection is created.
876std::string GenerateRtcpCname() {
877 std::string cname;
878 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100879 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800880 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700881 }
882 return cname;
883}
884
zhihuang1c378ed2017-08-17 14:10:50 -0700885bool ValidateOfferAnswerOptions(
886 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
887 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
888 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700889}
890
zhihuang1c378ed2017-08-17 14:10:50 -0700891// From |rtc_options|, fill parts of |session_options| shared by all generated
892// m= sections (in other words, nothing that involves a map/array).
893void ExtractSharedMediaSessionOptions(
894 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
895 cricket::MediaSessionOptions* session_options) {
896 session_options->vad_enabled = rtc_options.voice_activity_detection;
897 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200898 session_options->raw_packetization_for_video =
899 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700900}
zhihuanga77e6bb2017-08-14 18:17:48 -0700901
zhihuang38ede132017-06-15 12:52:32 -0700902PeerConnection::PeerConnection(PeerConnectionFactory* factory,
903 std::unique_ptr<RtcEventLog> event_log,
904 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700906 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100907 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700908 datagram_transport_config_(
909 field_trial::FindFullName(kDatagramTransportFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700910 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700911 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700912 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100913 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200914 call_ptr_(call_.get()),
915 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916
917PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100918 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800919 RTC_DCHECK_RUN_ON(signaling_thread());
920
Steve Anton8af21862017-12-15 11:20:13 -0800921 // Need to stop transceivers before destroying the stats collector because
922 // AudioRtpSender has a reference to the StatsCollector it will update when
923 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100924 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800925 transceiver->Stop();
926 }
Steve Anton4171afb2017-11-20 10:20:22 -0800927
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700928 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800929 if (stats_collector_) {
930 stats_collector_->WaitForPendingRequest();
931 stats_collector_ = nullptr;
932 }
Steve Anton75737c02017-11-06 10:37:17 -0800933
Steve Anton8af21862017-12-15 11:20:13 -0800934 // Don't destroy BaseChannels until after stats has been cleaned up so that
935 // the last stats request can still read from the channels.
936 DestroyAllChannels();
937
Mirko Bonadei675513b2017-11-09 11:09:25 +0100938 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800939
940 webrtc_session_desc_factory_.reset();
941 sctp_invoker_.reset();
942 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800943 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800944 transport_controller_.reset();
945
deadbeef91dd5672016-05-18 16:55:30 -0700946 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100947 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
948 RTC_DCHECK_RUN_ON(network_thread());
949 port_allocator_.reset();
950 });
eladalon248fd4f2017-09-06 05:18:15 -0700951 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700952 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100953 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700954 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800955 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700956 event_log_.reset();
957 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958}
959
Steve Anton8af21862017-12-15 11:20:13 -0800960void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800961 // Destroy video channels first since they may have a pointer to a voice
962 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100963 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800964 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800965 DestroyTransceiverChannel(transceiver);
966 }
967 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100968 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800969 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800970 DestroyTransceiverChannel(transceiver);
971 }
972 }
973 DestroyDataChannel();
974}
975
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000977 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700978 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100979 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100980 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100981 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700982
983 RTCError config_error = ValidateConfiguration(configuration);
984 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100985 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700986 return false;
987 }
988
Benjamin Wrightcab58882018-05-02 15:12:47 -0700989 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100990 RTC_LOG(LS_ERROR)
991 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100992 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800993 return false;
994 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200995
Benjamin Wrightcab58882018-05-02 15:12:47 -0700996 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800997 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100998 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100999 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001000 return false;
1001 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001002
Benjamin Wrightcab58882018-05-02 15:12:47 -07001003 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001004 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001005 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001006 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001007
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001008 cricket::ServerAddresses stun_servers;
1009 std::vector<cricket::RelayServerConfig> turn_servers;
1010
1011 RTCErrorType parse_error =
1012 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1013 if (parse_error != RTCErrorType::NONE) {
1014 return false;
1015 }
1016
deadbeef91dd5672016-05-18 16:55:30 -07001017 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001018 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001019 const auto pa_result =
1020 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001021 RTC_FROM_HERE,
1022 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001023 stun_servers, turn_servers, configuration));
1024
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001025 // If initialization was successful, note if STUN or TURN servers
1026 // were supplied.
1027 if (!stun_servers.empty()) {
1028 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1029 }
1030 if (!turn_servers.empty()) {
1031 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001034 // Send information about IPv4/IPv6 status.
1035 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001036 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001037 address_family = kPeerConnection_IPv6;
1038 } else {
1039 address_family = kPeerConnection_IPv4;
1040 }
1041 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1042 kPeerConnectionAddressFamilyCounter_Max);
1043
Zhi Huange830e682018-03-30 10:48:35 -07001044 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1045
Steve Anton75737c02017-11-06 10:37:17 -08001046 // RFC 3264: The numeric value of the session id and version in the
1047 // o line MUST be representable with a "64 bit signed integer".
1048 // Due to this constraint session id |session_id_| is max limited to
1049 // LLONG_MAX.
1050 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001051 JsepTransportController::Config config;
1052 config.redetermine_role_on_ice_restart =
1053 configuration.redetermine_role_on_ice_restart;
1054 config.ssl_max_version = factory_->options().ssl_max_version;
1055 config.disable_encryption = options.disable_encryption;
1056 config.bundle_policy = configuration.bundle_policy;
1057 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001058 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1059 // stub.
1060 config.crypto_options = configuration.crypto_options.has_value()
1061 ? *configuration.crypto_options
1062 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001063 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001064 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001065#if defined(ENABLE_EXTERNAL_AUTH)
1066 config.enable_external_auth = true;
1067#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001068 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001069
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001070 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001071 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001072 datagram_transport_config_.default_value);
1073 if (use_datagram_transport_ || configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001074 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001075 if (!factory_->media_transport_factory()) {
1076 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001077 << "PeerConnecton is initialized with use_media_transport = true or "
1078 << "use_media_transport_for_data_channels = true "
1079 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001080 return false;
1081 }
1082
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001083 if (configuration.use_media_transport ||
1084 configuration.use_media_transport_for_data_channels) {
1085 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1086 // RTP media transport is introduced. But until then, we require SDES to
1087 // be enabled.
1088 if (configuration.enable_dtls_srtp.has_value() &&
1089 configuration.enable_dtls_srtp.value()) {
1090 RTC_LOG(LS_WARNING)
1091 << "When media transport is used, SDES must be enabled. Set "
1092 "configuration.enable_dtls_srtp to false. use_media_transport="
1093 << configuration.use_media_transport
1094 << ", use_media_transport_for_data_channels="
1095 << configuration.use_media_transport_for_data_channels;
1096 return false;
1097 }
1098 }
1099
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001100 config.use_media_transport_for_media = configuration.use_media_transport;
1101 config.use_media_transport_for_data_channels =
1102 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001103 config.use_datagram_transport = use_datagram_transport_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001104 config.media_transport_factory = factory_->media_transport_factory();
1105 }
1106
Zhi Huange830e682018-03-30 10:48:35 -07001107 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001108 signaling_thread(), network_thread(), port_allocator_.get(),
1109 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001110 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001111 this, &PeerConnection::OnTransportControllerConnectionState);
1112 transport_controller_->SignalStandardizedIceConnectionState.connect(
1113 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001114 transport_controller_->SignalConnectionState.connect(
1115 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001116 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001117 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001118 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001119 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001120 transport_controller_->SignalIceCandidateError.connect(
1121 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001122 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001123 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1124 transport_controller_->SignalDtlsHandshakeError.connect(
1125 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001126 transport_controller_->SignalIceCandidatePairChanged.connect(
1127 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001128
1129 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001130
deadbeefab9b2d12015-10-14 11:33:11 -07001131 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001132 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133
Steve Antonba818672017-11-06 10:21:57 -08001134 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001135 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001136
Steve Anton75737c02017-11-06 10:37:17 -08001137 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1138 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1139 if (!configuration.certificates.empty()) {
1140 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1141 // just picking the first one. The decision should be made based on the DTLS
1142 // handshake. The DTLS negotiations need to know about all certificates.
1143 certificate = configuration.certificates[0];
1144 }
1145
Steve Antond25da372017-11-06 14:50:29 -08001146 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001147
1148 if (options.disable_encryption) {
1149 dtls_enabled_ = false;
1150 } else {
1151 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001152 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001153 // |configuration| can override the default |dtls_enabled_| value.
1154 if (configuration.enable_dtls_srtp) {
1155 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1156 }
1157 }
1158
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001159 if (configuration.use_media_transport_for_data_channels) {
1160 if (configuration.enable_rtp_data_channel) {
1161 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1162 "use_media_transport_for_data_channels are "
1163 "incompatible and cannot both be set to true";
1164 return false;
1165 }
1166 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1167 } else if (configuration.enable_rtp_data_channel) {
1168 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1169 // set. It takes precendence over the disable_sctp_data_channels
1170 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001171 data_channel_type_ = cricket::DCT_RTP;
1172 } else {
1173 // DTLS has to be enabled to use SCTP.
1174 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1175 data_channel_type_ = cricket::DCT_SCTP;
1176 }
1177 }
1178
1179 video_options_.screencast_min_bitrate_kbps =
1180 configuration.screencast_min_bitrate;
1181 audio_options_.combined_audio_video_bwe =
1182 configuration.combined_audio_video_bwe;
1183
1184 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001185 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001186
1187 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001188 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001189
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001190 audio_options_.audio_jitter_buffer_min_delay_ms =
1191 configuration.audio_jitter_buffer_min_delay_ms;
1192
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001193 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1194 configuration.audio_jitter_buffer_enable_rtx_handling;
1195
Steve Anton75737c02017-11-06 10:37:17 -08001196 // Whether the certificate generator/certificate is null or not determines
1197 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1198 // the right instructions by clearing the variables if needed.
1199 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001200 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001201 certificate = nullptr;
1202 } else if (certificate) {
1203 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001204 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001205 }
1206
1207 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1208 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001209 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001210 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1211 this, &PeerConnection::OnCertificateReady);
1212
1213 if (options.disable_encryption) {
1214 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1215 }
1216
1217 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001218 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001219 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220
Steve Anton4171afb2017-11-20 10:20:22 -08001221 // Add default audio/video transceivers for Plan B SDP.
1222 if (!IsUnifiedPlan()) {
1223 transceivers_.push_back(
1224 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1225 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1226 transceivers_.push_back(
1227 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1228 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1229 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001230 int delay_ms =
1231 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001232 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1233 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001234
1235 if (dependencies.video_bitrate_allocator_factory) {
1236 video_bitrate_allocator_factory_ =
1237 std::move(dependencies.video_bitrate_allocator_factory);
1238 } else {
1239 video_bitrate_allocator_factory_ =
1240 CreateBuiltinVideoBitrateAllocatorFactory();
1241 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242 return true;
1243}
1244
Steve Anton038834f2017-07-14 15:59:59 -07001245RTCError PeerConnection::ValidateConfiguration(
1246 const RTCConfiguration& config) const {
1247 if (config.ice_regather_interval_range &&
1248 config.continual_gathering_policy == GATHER_ONCE) {
1249 return RTCError(RTCErrorType::INVALID_PARAMETER,
1250 "ice_regather_interval_range specified but continual "
1251 "gathering policy is GATHER_ONCE");
1252 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001253 auto result =
1254 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1255 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001256}
1257
Yves Gerey665174f2018-06-19 15:03:05 +02001258rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001259 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001260 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1261 "Plan SdpSemantics. Please use GetSenders "
1262 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001263 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264}
1265
Yves Gerey665174f2018-06-19 15:03:05 +02001266rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001267 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001268 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1269 "Plan SdpSemantics. Please use GetReceivers "
1270 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001271 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272}
1273
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001274bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001275 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001276 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1277 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001278 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279 if (IsClosed()) {
1280 return false;
1281 }
deadbeefab9b2d12015-10-14 11:33:11 -07001282 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 return false;
1284 }
deadbeefab9b2d12015-10-14 11:33:11 -07001285
1286 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001287 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1288 observer->SignalAudioTrackAdded.connect(this,
1289 &PeerConnection::OnAudioTrackAdded);
1290 observer->SignalAudioTrackRemoved.connect(
1291 this, &PeerConnection::OnAudioTrackRemoved);
1292 observer->SignalVideoTrackAdded.connect(this,
1293 &PeerConnection::OnVideoTrackAdded);
1294 observer->SignalVideoTrackRemoved.connect(
1295 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001296 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001297
deadbeefab9b2d12015-10-14 11:33:11 -07001298 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001299 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001300 }
1301 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001302 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001303 }
1304
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001305 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001306 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 return true;
1308}
1309
1310void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001311 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001312 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1313 "Plan SdpSemantics. Please use RemoveTrack "
1314 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001315 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001316 if (!IsClosed()) {
1317 for (const auto& track : local_stream->GetAudioTracks()) {
1318 RemoveAudioTrack(track.get(), local_stream);
1319 }
1320 for (const auto& track : local_stream->GetVideoTracks()) {
1321 RemoveVideoTrack(track.get(), local_stream);
1322 }
deadbeefab9b2d12015-10-14 11:33:11 -07001323 }
deadbeefab9b2d12015-10-14 11:33:11 -07001324 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001325 stream_observers_.erase(
1326 std::remove_if(
1327 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001328 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001329 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001330 }),
1331 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001332
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333 if (IsClosed()) {
1334 return;
1335 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001336 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337}
1338
Steve Anton2d6c76a2018-01-05 17:10:52 -08001339RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001340 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001341 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001342 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001343 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001344 if (!track) {
1345 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1346 }
1347 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1348 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1349 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1350 "Track has invalid kind: " + track->kind());
1351 }
Steve Antonf9381f02017-12-14 10:23:57 -08001352 if (IsClosed()) {
1353 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1354 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001355 }
Steve Anton4171afb2017-11-20 10:20:22 -08001356 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001357 LOG_AND_RETURN_ERROR(
1358 RTCErrorType::INVALID_PARAMETER,
1359 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001360 }
Steve Antonf9381f02017-12-14 10:23:57 -08001361 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001362 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1363 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001364 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001365 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001366 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001367 }
1368 return sender_or_error;
1369}
deadbeefe1f9d832016-01-14 15:35:42 -08001370
Steve Antonf9381f02017-12-14 10:23:57 -08001371RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1372PeerConnection::AddTrackPlanB(
1373 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001374 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001375 if (stream_ids.size() > 1u) {
1376 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1377 "AddTrack with more than one stream is not "
1378 "supported with Plan B semantics.");
1379 }
1380 std::vector<std::string> adjusted_stream_ids = stream_ids;
1381 if (adjusted_stream_ids.empty()) {
1382 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1383 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001384 cricket::MediaType media_type =
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind
1386 ? cricket::MEDIA_TYPE_AUDIO
1387 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001388 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001389 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001390 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001391 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001392 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001393 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001394 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001395 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001396 if (sender_info) {
1397 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001398 }
Steve Antonf9381f02017-12-14 10:23:57 -08001399 } else {
1400 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001401 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001402 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001403 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001404 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001405 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001406 if (sender_info) {
1407 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001408 }
deadbeefe1f9d832016-01-14 15:35:42 -08001409 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001410 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001411}
deadbeefe1f9d832016-01-14 15:35:42 -08001412
Steve Antonf9381f02017-12-14 10:23:57 -08001413RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1414PeerConnection::AddTrackUnifiedPlan(
1415 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001416 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001417 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1418 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001419 RTC_LOG(LS_INFO) << "Reusing an existing "
1420 << cricket::MediaTypeToString(transceiver->media_type())
1421 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001422 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001423 transceiver->internal()->set_direction(
1424 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001425 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001426 transceiver->internal()->set_direction(
1427 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001428 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001429 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001430 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001431 } else {
1432 cricket::MediaType media_type =
1433 (track->kind() == MediaStreamTrackInterface::kAudioKind
1434 ? cricket::MEDIA_TYPE_AUDIO
1435 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001436 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1437 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001438 std::string sender_id = track->id();
1439 // Avoid creating a sender with an existing ID by generating a random ID.
1440 // This can happen if this is the second time AddTrack has created a sender
1441 // for this track.
1442 if (FindSenderById(sender_id)) {
1443 sender_id = rtc::CreateRandomUuid();
1444 }
Florent Castelli892acf02018-10-01 22:47:20 +02001445 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001446 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1447 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001448 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001449 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001450 }
Steve Antonf9381f02017-12-14 10:23:57 -08001451 return transceiver->sender();
1452}
1453
1454rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1455PeerConnection::FindFirstTransceiverForAddedTrack(
1456 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1457 RTC_DCHECK(track);
1458 for (auto transceiver : transceivers_) {
1459 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001460 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001461 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001462 !transceiver->internal()->has_ever_been_used_to_send() &&
1463 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001464 return transceiver;
1465 }
1466 }
1467 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001468}
1469
1470bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1471 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001472 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001473}
1474
Steve Anton24db5732018-07-23 10:27:33 -07001475RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001476 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001477 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001478 if (!sender) {
1479 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1480 }
deadbeefe1f9d832016-01-14 15:35:42 -08001481 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001482 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1483 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001484 }
Steve Antonf9381f02017-12-14 10:23:57 -08001485 if (IsUnifiedPlan()) {
1486 auto transceiver = FindTransceiverBySender(sender);
1487 if (!transceiver || !sender->track()) {
1488 return RTCError::OK();
1489 }
1490 sender->SetTrack(nullptr);
1491 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001492 transceiver->internal()->set_direction(
1493 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001494 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001495 transceiver->internal()->set_direction(
1496 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001497 }
Steve Anton4171afb2017-11-20 10:20:22 -08001498 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001499 bool removed;
1500 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1501 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1502 } else {
1503 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1504 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1505 }
1506 if (!removed) {
1507 LOG_AND_RETURN_ERROR(
1508 RTCErrorType::INVALID_PARAMETER,
1509 "Couldn't find sender " + sender->id() + " to remove.");
1510 }
Steve Anton4171afb2017-11-20 10:20:22 -08001511 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001512 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001513 return RTCError::OK();
1514}
1515
1516rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1517PeerConnection::FindTransceiverBySender(
1518 rtc::scoped_refptr<RtpSenderInterface> sender) {
1519 for (auto transceiver : transceivers_) {
1520 if (transceiver->sender() == sender) {
1521 return transceiver;
1522 }
1523 }
1524 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001525}
1526
Steve Anton9158ef62017-11-27 13:01:52 -08001527RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1528PeerConnection::AddTransceiver(
1529 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1530 return AddTransceiver(track, RtpTransceiverInit());
1531}
1532
1533RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1534PeerConnection::AddTransceiver(
1535 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1536 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001537 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001538 RTC_CHECK(IsUnifiedPlan())
1539 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001540 if (!track) {
1541 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1542 }
1543 cricket::MediaType media_type;
1544 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1545 media_type = cricket::MEDIA_TYPE_AUDIO;
1546 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1547 media_type = cricket::MEDIA_TYPE_VIDEO;
1548 } else {
1549 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1550 "Track kind is not audio or video");
1551 }
1552 return AddTransceiver(media_type, track, init);
1553}
1554
1555RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1556PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1557 return AddTransceiver(media_type, RtpTransceiverInit());
1558}
1559
1560RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1561PeerConnection::AddTransceiver(cricket::MediaType media_type,
1562 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001563 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001564 RTC_CHECK(IsUnifiedPlan())
1565 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001566 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1567 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1568 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1569 "media type is not audio or video");
1570 }
1571 return AddTransceiver(media_type, nullptr, init);
1572}
1573
1574RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1575PeerConnection::AddTransceiver(
1576 cricket::MediaType media_type,
1577 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001578 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001579 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001580 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1581 media_type == cricket::MEDIA_TYPE_VIDEO));
1582 if (track) {
1583 RTC_DCHECK_EQ(media_type,
1584 (track->kind() == MediaStreamTrackInterface::kAudioKind
1585 ? cricket::MEDIA_TYPE_AUDIO
1586 : cricket::MEDIA_TYPE_VIDEO));
1587 }
1588
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001589 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1590 init.send_encodings.size(), 0, 7, 8);
1591
Amit Hilbuchaa584152019-02-06 17:09:52 -08001592 size_t num_rids = absl::c_count_if(init.send_encodings,
1593 [](const RtpEncodingParameters& encoding) {
1594 return !encoding.rid.empty();
1595 });
1596 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001597 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001598 RTCErrorType::INVALID_PARAMETER,
1599 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001600 }
1601
Amit Hilbuchf4770402019-04-08 14:11:57 -07001602 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1603 [](const RtpEncodingParameters& encoding) {
1604 return !IsLegalRsidName(encoding.rid);
1605 })) {
1606 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1607 "Invalid RID value provided.");
1608 }
1609
Amit Hilbuchaa584152019-02-06 17:09:52 -08001610 if (absl::c_any_of(init.send_encodings,
1611 [](const RtpEncodingParameters& encoding) {
1612 return encoding.ssrc.has_value();
1613 })) {
1614 LOG_AND_RETURN_ERROR(
1615 RTCErrorType::UNSUPPORTED_PARAMETER,
1616 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001617 }
1618
1619 RtpParameters parameters;
1620 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001621
1622 // Encodings are dropped from the tail if too many are provided.
1623 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1624 parameters.encodings.erase(
1625 parameters.encodings.begin() + kMaxSimulcastStreams,
1626 parameters.encodings.end());
1627 }
1628
1629 // Single RID should be removed.
1630 if (parameters.encodings.size() == 1 &&
1631 !parameters.encodings[0].rid.empty()) {
1632 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1633 parameters.encodings[0].rid.clear();
1634 }
1635
1636 // If RIDs were not provided, they are generated for simulcast scenario.
1637 if (parameters.encodings.size() > 1 && num_rids == 0) {
1638 rtc::UniqueStringGenerator rid_generator;
1639 for (RtpEncodingParameters& encoding : parameters.encodings) {
1640 encoding.rid = rid_generator();
1641 }
1642 }
1643
Florent Castelli892acf02018-10-01 22:47:20 +02001644 if (UnimplementedRtpParameterHasValue(parameters)) {
1645 LOG_AND_RETURN_ERROR(
1646 RTCErrorType::UNSUPPORTED_PARAMETER,
1647 "Attempted to set an unimplemented parameter of RtpParameters.");
1648 }
Steve Anton9158ef62017-11-27 13:01:52 -08001649
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001650 auto result = cricket::CheckRtpParametersValues(parameters);
1651 if (!result.ok()) {
1652 LOG_AND_RETURN_ERROR(result.type(), result.message());
1653 }
1654
Steve Anton3d954a62018-04-02 11:27:23 -07001655 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1656 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001657 // Set the sender ID equal to the track ID if the track is specified unless
1658 // that sender ID is already in use.
1659 std::string sender_id =
1660 (track && !FindSenderById(track->id()) ? track->id()
1661 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001662 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001663 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001664 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1665 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1666 transceiver->internal()->set_direction(init.direction);
1667
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001668 if (update_negotiation_needed) {
1669 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001670 }
Steve Antonf9381f02017-12-14 10:23:57 -08001671
1672 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1673}
1674
Steve Anton02ee47c2018-01-10 16:26:06 -08001675rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1676PeerConnection::CreateSender(
1677 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001678 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001679 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001680 const std::vector<std::string>& stream_ids,
1681 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001682 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001683 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001684 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1685 RTC_DCHECK(!track ||
1686 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1687 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1688 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001689 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001690 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001691 } else {
1692 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1693 RTC_DCHECK(!track ||
1694 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1695 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001696 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001697 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001698 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001699 bool set_track_succeeded = sender->SetTrack(track);
1700 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001701 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001702 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001703 return sender;
1704}
1705
1706rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1707PeerConnection::CreateReceiver(cricket::MediaType media_type,
1708 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001709 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1710 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001711 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001712 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001713 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1714 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001715 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001716 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001717 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001718 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001719 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1720 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001721 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001722 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001723 return receiver;
1724}
1725
1726rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1727PeerConnection::CreateAndAddTransceiver(
1728 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1729 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1730 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001731 // Ensure that the new sender does not have an ID that is already in use by
1732 // another sender.
1733 // Allow receiver IDs to conflict since those come from remote SDP (which
1734 // could be invalid, but should not cause a crash).
1735 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001736 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001737 signaling_thread(),
1738 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001739 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001740 transceiver->internal()->SignalNegotiationNeeded.connect(
1741 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001742 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001743}
1744
Steve Anton52d86772018-02-20 15:48:12 -08001745void PeerConnection::OnNegotiationNeeded() {
1746 RTC_DCHECK_RUN_ON(signaling_thread());
1747 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001748 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001749}
1750
deadbeeffac06552015-11-25 11:26:01 -08001751rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001752 const std::string& kind,
1753 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001754 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001755 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1756 "Plan SdpSemantics. Please use AddTransceiver "
1757 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001758 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001759 if (IsClosed()) {
1760 return nullptr;
1761 }
Steve Anton4171afb2017-11-20 10:20:22 -08001762
Seth Hampson5b4f0752018-04-02 16:31:36 -07001763 // Internally we need to have one stream with Plan B semantics, so we
1764 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001765 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001766 if (stream_id.empty()) {
1767 stream_ids.push_back(rtc::CreateRandomUuid());
1768 RTC_LOG(LS_INFO)
1769 << "No stream_id specified for sender. Generated stream ID: "
1770 << stream_ids[0];
1771 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001772 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001773 }
1774
Steve Anton4171afb2017-11-20 10:20:22 -08001775 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001776 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001777 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001778 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001779 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001780 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001781 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001782 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001783 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001784 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001785 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001786 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001787 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001788 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001789 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001790 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001791 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001792 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001793 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001794 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001795 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001796
deadbeefe1f9d832016-01-14 15:35:42 -08001797 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001798}
1799
deadbeef70ab1a12015-09-28 16:53:55 -07001800std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1801 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001802 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001803 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001804 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001805 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001806 }
1807 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001808}
1809
Steve Anton4171afb2017-11-20 10:20:22 -08001810std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1811PeerConnection::GetSendersInternal() const {
1812 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1813 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001814 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001815 auto senders = transceiver->internal()->senders();
1816 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1817 }
1818 return all_senders;
1819}
1820
deadbeef70ab1a12015-09-28 16:53:55 -07001821std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1822PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001823 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001824 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001825 for (const auto& receiver : GetReceiversInternal()) {
1826 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001827 }
1828 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001829}
1830
Steve Anton4171afb2017-11-20 10:20:22 -08001831std::vector<
1832 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1833PeerConnection::GetReceiversInternal() const {
1834 std::vector<
1835 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1836 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001837 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001838 auto receivers = transceiver->internal()->receivers();
1839 all_receivers.insert(all_receivers.end(), receivers.begin(),
1840 receivers.end());
1841 }
1842 return all_receivers;
1843}
1844
Steve Anton9158ef62017-11-27 13:01:52 -08001845std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1846PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001847 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001848 RTC_CHECK(IsUnifiedPlan())
1849 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001850 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001851 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001852 all_transceivers.push_back(transceiver);
1853 }
1854 return all_transceivers;
1855}
1856
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001858 MediaStreamTrackInterface* track,
1859 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001860 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001861 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001862 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001863 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864 return false;
1865 }
1866
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001867 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001868 // The StatsCollector is used to tell if a track is valid because it may
1869 // remember tracks that the PeerConnection previously removed.
1870 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001871 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1872 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001873 return false;
1874 }
Steve Antonad182762018-09-05 20:22:40 +00001875 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1876 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877 return true;
1878}
1879
hbos74e1a4f2016-09-15 23:33:01 -07001880void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001881 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001882 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001883 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001884 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001885 stats_collector_->GetStatsReport(callback);
1886}
1887
Henrik Boström1df1bf82018-03-20 13:24:20 +01001888void PeerConnection::GetStats(
1889 rtc::scoped_refptr<RtpSenderInterface> selector,
1890 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1891 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001892 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001893 RTC_DCHECK(callback);
1894 RTC_DCHECK(stats_collector_);
1895 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1896 if (selector) {
1897 for (const auto& proxy_transceiver : transceivers_) {
1898 for (const auto& proxy_sender :
1899 proxy_transceiver->internal()->senders()) {
1900 if (proxy_sender == selector) {
1901 internal_sender = proxy_sender->internal();
1902 break;
1903 }
1904 }
1905 if (internal_sender)
1906 break;
1907 }
1908 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001909 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001910 // belong to the PeerConnection (in Plan B, senders can be removed from the
1911 // PeerConnection). This means that "all the stats objects representing the
1912 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1913 // produces an empty stats report.
1914 stats_collector_->GetStatsReport(internal_sender, callback);
1915}
1916
1917void PeerConnection::GetStats(
1918 rtc::scoped_refptr<RtpReceiverInterface> selector,
1919 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1920 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001922 RTC_DCHECK(callback);
1923 RTC_DCHECK(stats_collector_);
1924 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1925 if (selector) {
1926 for (const auto& proxy_transceiver : transceivers_) {
1927 for (const auto& proxy_receiver :
1928 proxy_transceiver->internal()->receivers()) {
1929 if (proxy_receiver == selector) {
1930 internal_receiver = proxy_receiver->internal();
1931 break;
1932 }
1933 }
1934 if (internal_receiver)
1935 break;
1936 }
1937 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001938 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001939 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1940 // the PeerConnection). This means that "all the stats objects representing
1941 // the selector" is an empty set. Invoking GetStatsReport() with a null
1942 // selector produces an empty stats report.
1943 stats_collector_->GetStatsReport(internal_receiver, callback);
1944}
1945
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001947 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001948 return signaling_state_;
1949}
1950
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951PeerConnectionInterface::IceConnectionState
1952PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001953 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 return ice_connection_state_;
1955}
1956
Alex Loiko9289eda2018-11-23 16:18:59 +00001957PeerConnectionInterface::IceConnectionState
1958PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001959 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001960 return standardized_ice_connection_state_;
1961}
1962
Jonas Olsson635474e2018-10-18 15:58:17 +02001963PeerConnectionInterface::PeerConnectionState
1964PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001965 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001966 return connection_state_;
1967}
1968
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969PeerConnectionInterface::IceGatheringState
1970PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001971 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 return ice_gathering_state_;
1973}
1974
Yves Gerey665174f2018-06-19 15:03:05 +02001975rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 const std::string& label,
1977 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001978 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001979 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001980
deadbeefab9b2d12015-10-14 11:33:11 -07001981 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001982
kwibergd1fe2812016-04-27 06:47:29 -07001983 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001984 if (config) {
1985 internal_config.reset(new InternalDataChannelInit(*config));
1986 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001987 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001988 InternalCreateDataChannel(label, internal_config.get()));
1989 if (!channel.get()) {
1990 return nullptr;
1991 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001993 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1994 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001995 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001996 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001997 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001998 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001999 return DataChannelProxy::Create(signaling_thread(), channel.get());
2000}
2001
Henrik Boström79b69802019-07-18 11:16:56 +02002002void PeerConnection::RestartIce() {
2003 RTC_DCHECK_RUN_ON(signaling_thread());
2004 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2005 current_local_description_.get(), pending_local_description_.get());
2006 UpdateNegotiationNeeded();
2007}
2008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002010 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002011 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002012 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002013
nisse7ce109a2017-01-31 00:57:56 -08002014 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002015 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002016 return;
2017 }
deadbeefab9b2d12015-10-14 11:33:11 -07002018
Steve Anton8d3444d2017-10-20 15:30:51 -07002019 if (IsClosed()) {
2020 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002021 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002022 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002023 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002024 return;
2025 }
2026
Steve Anton25ca0ac2019-06-25 10:40:48 -07002027 // If a session error has occurred the PeerConnection is in a possibly
2028 // inconsistent state so fail right away.
2029 if (session_error() != SessionError::kNone) {
2030 std::string error_message = GetSessionErrorMsg();
2031 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2032 PostCreateSessionDescriptionFailure(
2033 observer,
2034 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2035 return;
2036 }
2037
zhihuang1c378ed2017-08-17 14:10:50 -07002038 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002039 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002040 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002041 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002042 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002043 return;
2044 }
2045
Steve Anton22da89f2018-01-25 13:58:07 -08002046 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2047 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2048 if (IsUnifiedPlan()) {
2049 RTCError error = HandleLegacyOfferOptions(options);
2050 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002051 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002052 return;
2053 }
2054 }
2055
zhihuang1c378ed2017-08-17 14:10:50 -07002056 cricket::MediaSessionOptions session_options;
2057 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002058 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002059}
2060
Steve Anton22da89f2018-01-25 13:58:07 -08002061RTCError PeerConnection::HandleLegacyOfferOptions(
2062 const RTCOfferAnswerOptions& options) {
2063 RTC_DCHECK(IsUnifiedPlan());
2064
2065 if (options.offer_to_receive_audio == 0) {
2066 RemoveRecvDirectionFromReceivingTransceiversOfType(
2067 cricket::MEDIA_TYPE_AUDIO);
2068 } else if (options.offer_to_receive_audio == 1) {
2069 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2070 } else if (options.offer_to_receive_audio > 1) {
2071 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2072 "offer_to_receive_audio > 1 is not supported.");
2073 }
2074
2075 if (options.offer_to_receive_video == 0) {
2076 RemoveRecvDirectionFromReceivingTransceiversOfType(
2077 cricket::MEDIA_TYPE_VIDEO);
2078 } else if (options.offer_to_receive_video == 1) {
2079 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2080 } else if (options.offer_to_receive_video > 1) {
2081 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2082 "offer_to_receive_video > 1 is not supported.");
2083 }
2084
2085 return RTCError::OK();
2086}
2087
2088void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2089 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002090 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002091 RtpTransceiverDirection new_direction =
2092 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2093 if (new_direction != transceiver->direction()) {
2094 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2095 << " transceiver (MID="
2096 << transceiver->mid().value_or("<not set>") << ") from "
2097 << RtpTransceiverDirectionToString(
2098 transceiver->direction())
2099 << " to "
2100 << RtpTransceiverDirectionToString(new_direction)
2101 << " since CreateOffer specified offer_to_receive=0";
2102 transceiver->internal()->set_direction(new_direction);
2103 }
Steve Anton22da89f2018-01-25 13:58:07 -08002104 }
2105}
2106
2107void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2108 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002109 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002110 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002111 RTC_LOG(LS_INFO)
2112 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2113 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002114 RtpTransceiverInit init;
2115 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002116 AddTransceiver(media_type, nullptr, init,
2117 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002118 }
2119}
2120
2121std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2122PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2123 std::vector<
2124 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2125 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002126 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002127 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002128 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2129 receiving_transceivers.push_back(transceiver);
2130 }
2131 }
2132 return receiving_transceivers;
2133}
2134
htaa2a49d92016-03-04 02:51:39 -08002135void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2136 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002137 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002138 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002139 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002140 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002141 return;
2142 }
2143
Steve Anton25ca0ac2019-06-25 10:40:48 -07002144 // If a session error has occurred the PeerConnection is in a possibly
2145 // inconsistent state so fail right away.
2146 if (session_error() != SessionError::kNone) {
2147 std::string error_message = GetSessionErrorMsg();
2148 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2149 PostCreateSessionDescriptionFailure(
2150 observer,
2151 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2152 return;
2153 }
2154
Steve Antondffead82018-02-06 10:31:29 -08002155 if (!(signaling_state_ == kHaveRemoteOffer ||
2156 signaling_state_ == kHaveLocalPrAnswer)) {
2157 std::string error =
2158 "PeerConnection cannot create an answer in a state other than "
2159 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002160 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002161 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002162 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002163 return;
2164 }
2165
Steve Antondffead82018-02-06 10:31:29 -08002166 // The remote description should be set if we're in the right state.
2167 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002168
Steve Anton22da89f2018-01-25 13:58:07 -08002169 if (IsUnifiedPlan()) {
2170 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2171 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2172 "supported with Unified Plan semantics. Use the "
2173 "RtpTransceiver API instead.";
2174 }
2175 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2176 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2177 "supported with Unified Plan semantics. Use the "
2178 "RtpTransceiver API instead.";
2179 }
2180 }
2181
htaa2a49d92016-03-04 02:51:39 -08002182 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002183 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002184
Steve Antond25da372017-11-06 14:50:29 -08002185 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002186}
2187
2188void PeerConnection::SetLocalDescription(
2189 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002190 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002191 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002192 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002193
Steve Anton80dd7b52018-02-16 17:08:42 -08002194 // The SetLocalDescription contract is that we take ownership of the session
2195 // description regardless of the outcome, so wrap it in a unique_ptr right
2196 // away. Ideally, SetLocalDescription's signature will be changed to take the
2197 // description as a unique_ptr argument to formalize this agreement.
2198 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2199
nisse7ce109a2017-01-31 00:57:56 -08002200 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002201 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202 return;
2203 }
Steve Anton8a006912017-12-04 15:25:56 -08002204
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002206 PostSetSessionDescriptionFailure(
2207 observer,
2208 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 return;
2210 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002211
Steve Anton80dd7b52018-02-16 17:08:42 -08002212 // If a session error has occurred the PeerConnection is in a possibly
2213 // inconsistent state so fail right away.
2214 if (session_error() != SessionError::kNone) {
2215 std::string error_message = GetSessionErrorMsg();
2216 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002217 PostSetSessionDescriptionFailure(
2218 observer,
2219 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002220 return;
2221 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002222
Steve Anton80dd7b52018-02-16 17:08:42 -08002223 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2224 if (!error.ok()) {
2225 std::string error_message = GetSetDescriptionErrorMessage(
2226 cricket::CS_LOCAL, desc->GetType(), error);
2227 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002228 PostSetSessionDescriptionFailure(
2229 observer,
2230 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002231 return;
2232 }
2233
2234 // Grab the description type before moving ownership to ApplyLocalDescription,
2235 // which may destroy it before returning.
2236 const SdpType type = desc->GetType();
2237
2238 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002239 // |desc| may be destroyed at this point.
2240
2241 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002242 // If ApplyLocalDescription fails, the PeerConnection could be in an
2243 // inconsistent state, so act conservatively here and set the session error
2244 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2245 SetSessionError(SessionError::kContent, error.message());
2246 std::string error_message =
2247 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2248 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002249 PostSetSessionDescriptionFailure(
2250 observer,
2251 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002252 return;
2253 }
Steve Anton8a006912017-12-04 15:25:56 -08002254 RTC_DCHECK(local_description());
2255
2256 PostSetSessionDescriptionSuccess(observer);
2257
Steve Antonad182762018-09-05 20:22:40 +00002258 // MaybeStartGathering needs to be called after posting
2259 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2260 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002261 transport_controller_->MaybeStartGathering();
2262
Steve Antona3a92c22017-12-07 10:27:41 -08002263 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002264 // TODO(deadbeef): We already had to hop to the network thread for
2265 // MaybeStartGathering...
2266 network_thread()->Invoke<void>(
2267 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2268 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002269 // Make UMA notes about what was agreed to.
2270 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002271 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002272
2273 if (IsUnifiedPlan()) {
2274 bool was_negotiation_needed = is_negotiation_needed_;
2275 UpdateNegotiationNeeded();
2276 if (signaling_state() == kStable && was_negotiation_needed &&
2277 is_negotiation_needed_) {
2278 Observer()->OnRenegotiationNeeded();
2279 }
2280 }
2281
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002282 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002283}
2284
2285RTCError PeerConnection::ApplyLocalDescription(
2286 std::unique_ptr<SessionDescriptionInterface> desc) {
2287 RTC_DCHECK_RUN_ON(signaling_thread());
2288 RTC_DCHECK(desc);
2289
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002290 // Update stats here so that we have the most recent stats for tracks and
2291 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002292 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002293
Steve Antondcc3c022017-12-22 16:02:54 -08002294 // Take a reference to the old local description since it's used below to
2295 // compare against the new local description. When setting the new local
2296 // description, grab ownership of the replaced session description in case it
2297 // is the same as |old_local_description|, to keep it alive for the duration
2298 // of the method.
2299 const SessionDescriptionInterface* old_local_description =
2300 local_description();
2301 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002302 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002303 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002304 replaced_local_description = pending_local_description_
2305 ? std::move(pending_local_description_)
2306 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002307 current_local_description_ = std::move(desc);
2308 pending_local_description_ = nullptr;
2309 current_remote_description_ = std::move(pending_remote_description_);
2310 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002311 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002312 pending_local_description_ = std::move(desc);
2313 }
2314 // The session description to apply now must be accessed by
2315 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002316 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002317
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002318 // Report statistics about any use of simulcast.
2319 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2320 *local_description()->description());
2321
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002322 if (!is_caller_) {
2323 if (remote_description()) {
2324 // Remote description was applied first, so this PC is the callee.
2325 is_caller_ = false;
2326 } else {
2327 // Local description is applied first, so this PC is the caller.
2328 is_caller_ = true;
2329 }
2330 }
2331
Zhi Huange830e682018-03-30 10:48:35 -07002332 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2333 if (!error.ok()) {
2334 return error;
2335 }
2336
Steve Antondcc3c022017-12-22 16:02:54 -08002337 if (IsUnifiedPlan()) {
2338 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002339 cricket::CS_LOCAL, *local_description(), old_local_description,
2340 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002341 if (!error.ok()) {
2342 return error;
2343 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002344 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2345 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002346 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002347 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2348 // Note that code paths that don't set MID won't be able to use
2349 // information about DTLS transports.
2350 if (transceiver->mid()) {
2351 auto dtls_transport =
2352 LookupDtlsTransportByMidInternal(*transceiver->mid());
2353 transceiver->internal()->sender_internal()->set_transport(
2354 dtls_transport);
2355 transceiver->internal()->receiver_internal()->set_transport(
2356 dtls_transport);
2357 }
2358
Steve Antondcc3c022017-12-22 16:02:54 -08002359 const ContentInfo* content =
2360 FindMediaSectionForTransceiver(transceiver, local_description());
2361 if (!content) {
2362 continue;
2363 }
2364 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002365 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2366 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002367 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002368 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2369 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2370 // "recvonly", process the removal of a remote track for the media
2371 // description, given transceiver, removeList, and muteTracks.
2372 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2373 (transceiver->internal()->fired_direction() &&
2374 RtpTransceiverDirectionHasRecv(
2375 *transceiver->internal()->fired_direction()))) {
2376 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2377 &removed_streams);
2378 }
2379 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2380 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002381 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002382 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002383 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002384 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002385 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002386 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002387 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002388 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002389 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002390 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002391 }
2392 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002393 // Media channels will be created only when offer is set. These may use new
2394 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002395 if (type == SdpType::kOffer) {
2396 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2397 // description is applied. Restore back to old description.
2398 RTCError error = CreateChannels(*local_description()->description());
2399 if (!error.ok()) {
2400 return error;
2401 }
2402 }
Steve Antondcc3c022017-12-22 16:02:54 -08002403 // Remove unused channels if MediaContentDescription is rejected.
2404 RemoveUnusedChannels(local_description()->description());
2405 }
Steve Anton8a006912017-12-04 15:25:56 -08002406
Zhi Huange830e682018-03-30 10:48:35 -07002407 error = UpdateSessionState(type, cricket::CS_LOCAL,
2408 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002409 if (!error.ok()) {
2410 return error;
2411 }
Steve Antondcc3c022017-12-22 16:02:54 -08002412
Steve Anton8a006912017-12-04 15:25:56 -08002413 if (remote_description()) {
2414 // Now that we have a local description, we can push down remote candidates.
2415 UseCandidatesInSessionDescription(remote_description());
2416 }
2417
2418 pending_ice_restarts_.clear();
2419 if (session_error() != SessionError::kNone) {
2420 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2421 }
2422
deadbeefab9b2d12015-10-14 11:33:11 -07002423 // If setting the description decided our SSL role, allocate any necessary
2424 // SCTP sids.
2425 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002426 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002427 AllocateSctpSids(role);
2428 }
2429
Steve Antond3679212018-01-17 17:41:02 -08002430 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002431 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002432 const ContentInfo* content =
2433 FindMediaSectionForTransceiver(transceiver, local_description());
2434 if (!content) {
2435 continue;
2436 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002437 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2438 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002439 // 0 is a special value meaning "this sender has no associated send
2440 // stream". Need to call this so the sender won't attempt to configure
2441 // a no longer existing stream and run into DCHECKs in the lower
2442 // layers.
2443 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002444 } else {
2445 // Get the StreamParams from the channel which could generate SSRCs.
2446 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002447 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002448 streams[0].stream_ids());
2449 transceiver->internal()->sender_internal()->SetSsrc(
2450 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002451 }
2452 }
2453 } else {
2454 // Plan B semantics.
2455
Steve Antondcc3c022017-12-22 16:02:54 -08002456 // Update state and SSRC of local MediaStreams and DataChannels based on the
2457 // local session description.
2458 const cricket::ContentInfo* audio_content =
2459 GetFirstAudioContent(local_description()->description());
2460 if (audio_content) {
2461 if (audio_content->rejected) {
2462 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2463 } else {
2464 const cricket::AudioContentDescription* audio_desc =
2465 audio_content->media_description()->as_audio();
2466 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2467 }
deadbeeffaac4972015-11-12 15:33:07 -08002468 }
deadbeefab9b2d12015-10-14 11:33:11 -07002469
Steve Antondcc3c022017-12-22 16:02:54 -08002470 const cricket::ContentInfo* video_content =
2471 GetFirstVideoContent(local_description()->description());
2472 if (video_content) {
2473 if (video_content->rejected) {
2474 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2475 } else {
2476 const cricket::VideoContentDescription* video_desc =
2477 video_content->media_description()->as_video();
2478 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2479 }
deadbeeffaac4972015-11-12 15:33:07 -08002480 }
deadbeefab9b2d12015-10-14 11:33:11 -07002481 }
2482
2483 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002484 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002485 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002486 const cricket::RtpDataContentDescription* rtp_data_desc =
2487 data_content->media_description()->as_rtp_data();
2488 // rtp_data_desc will be null if this is an SCTP description.
2489 if (rtp_data_desc) {
2490 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002491 }
2492 }
2493
Henrik Boström79b69802019-07-18 11:16:56 +02002494 if (type == SdpType::kAnswer &&
2495 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2496 *current_local_description_)) {
2497 local_ice_credentials_to_replace_->ClearIceCredentials();
2498 }
2499
Steve Anton8a006912017-12-04 15:25:56 -08002500 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501}
2502
Steve Anton06817cd2018-12-18 15:55:30 -08002503// The SDP parser used to populate these values by default for the 'content
2504// name' if an a=mid line was absent.
2505static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2506 switch (media_type) {
2507 case cricket::MEDIA_TYPE_AUDIO:
2508 return cricket::CN_AUDIO;
2509 case cricket::MEDIA_TYPE_VIDEO:
2510 return cricket::CN_VIDEO;
2511 case cricket::MEDIA_TYPE_DATA:
2512 return cricket::CN_DATA;
2513 }
2514 RTC_NOTREACHED();
2515 return "";
2516}
2517
2518void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002519 cricket::SessionDescription* new_remote_description) {
2520 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002521 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002522 const cricket::ContentInfos& local_contents =
2523 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002524 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002525 const cricket::ContentInfos& remote_contents =
2526 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002527 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002528 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2529 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002530 if (!content.name.empty()) {
2531 continue;
2532 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002533 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002534 absl::string_view source_explanation;
2535 if (IsUnifiedPlan()) {
2536 if (i < local_contents.size()) {
2537 new_mid = local_contents[i].name;
2538 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002539 } else if (i < remote_contents.size()) {
2540 new_mid = remote_contents[i].name;
2541 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002542 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002543 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002544 source_explanation = "generated just now";
2545 }
2546 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002547 new_mid = std::string(
2548 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002549 source_explanation = "to match pre-existing behavior";
2550 }
Steve Antond7180cc2019-02-07 10:44:53 -08002551 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002552 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002553 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002554 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2555 << " is missing an a=mid line. Filling in the value '"
2556 << new_mid << "' " << source_explanation << ".";
2557 }
2558}
2559
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002560void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002561 SetSessionDescriptionObserver* observer,
2562 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002563 SetRemoteDescription(
2564 std::unique_ptr<SessionDescriptionInterface>(desc),
2565 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2566 new SetRemoteDescriptionObserverAdapter(this, observer)));
2567}
2568
2569void PeerConnection::SetRemoteDescription(
2570 std::unique_ptr<SessionDescriptionInterface> desc,
2571 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002572 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002573 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002574
nisse7ce109a2017-01-31 00:57:56 -08002575 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002576 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002577 return;
2578 }
Steve Anton8a006912017-12-04 15:25:56 -08002579
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002580 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002581 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002582 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002583 return;
2584 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002585
Steve Anton80dd7b52018-02-16 17:08:42 -08002586 // If a session error has occurred the PeerConnection is in a possibly
2587 // inconsistent state so fail right away.
2588 if (session_error() != SessionError::kNone) {
2589 std::string error_message = GetSessionErrorMsg();
2590 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2591 observer->OnSetRemoteDescriptionComplete(
2592 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2593 return;
2594 }
Steve Anton71439a62018-02-15 11:53:06 -08002595
Steve Antonba42e992018-04-09 14:10:01 -07002596 if (desc->GetType() == SdpType::kOffer) {
2597 // Report to UMA the format of the received offer.
2598 ReportSdpFormatReceived(*desc);
2599 }
2600
Steve Anton06817cd2018-12-18 15:55:30 -08002601 // Handle remote descriptions missing a=mid lines for interop with legacy end
2602 // points.
2603 FillInMissingRemoteMids(desc->description());
2604
Steve Anton80dd7b52018-02-16 17:08:42 -08002605 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002606 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002607 std::string error_message = GetSetDescriptionErrorMessage(
2608 cricket::CS_REMOTE, desc->GetType(), error);
2609 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002610 observer->OnSetRemoteDescriptionComplete(
2611 RTCError(error.type(), std::move(error_message)));
2612 return;
2613 }
Steve Anton71439a62018-02-15 11:53:06 -08002614
Steve Anton80dd7b52018-02-16 17:08:42 -08002615 // Grab the description type before moving ownership to
2616 // ApplyRemoteDescription, which may destroy it before returning.
2617 const SdpType type = desc->GetType();
2618
2619 error = ApplyRemoteDescription(std::move(desc));
2620 // |desc| may be destroyed at this point.
2621
2622 if (!error.ok()) {
2623 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2624 // inconsistent state, so act conservatively here and set the session error
2625 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2626 SetSessionError(SessionError::kContent, error.message());
2627 std::string error_message =
2628 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2629 RTC_LOG(LS_ERROR) << error_message;
2630 observer->OnSetRemoteDescriptionComplete(
2631 RTCError(error.type(), std::move(error_message)));
2632 return;
2633 }
2634 RTC_DCHECK(remote_description());
2635
2636 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002637 // TODO(deadbeef): We already had to hop to the network thread for
2638 // MaybeStartGathering...
2639 network_thread()->Invoke<void>(
2640 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2641 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002642 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002643 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002644 }
2645
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002646 if (IsUnifiedPlan()) {
2647 bool was_negotiation_needed = is_negotiation_needed_;
2648 UpdateNegotiationNeeded();
2649 if (signaling_state() == kStable && was_negotiation_needed &&
2650 is_negotiation_needed_) {
2651 Observer()->OnRenegotiationNeeded();
2652 }
2653 }
2654
Steve Anton8a006912017-12-04 15:25:56 -08002655 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002656 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002657}
2658
2659RTCError PeerConnection::ApplyRemoteDescription(
2660 std::unique_ptr<SessionDescriptionInterface> desc) {
2661 RTC_DCHECK_RUN_ON(signaling_thread());
2662 RTC_DCHECK(desc);
2663
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002664 // Update stats here so that we have the most recent stats for tracks and
2665 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002666 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002667
Steve Antondcc3c022017-12-22 16:02:54 -08002668 // Take a reference to the old remote description since it's used below to
2669 // compare against the new remote description. When setting the new remote
2670 // description, grab ownership of the replaced session description in case it
2671 // is the same as |old_remote_description|, to keep it alive for the duration
2672 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002673 const SessionDescriptionInterface* old_remote_description =
2674 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002675 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002676 SdpType type = desc->GetType();
2677 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002678 replaced_remote_description = pending_remote_description_
2679 ? std::move(pending_remote_description_)
2680 : std::move(current_remote_description_);
2681 current_remote_description_ = std::move(desc);
2682 pending_remote_description_ = nullptr;
2683 current_local_description_ = std::move(pending_local_description_);
2684 } else {
2685 replaced_remote_description = std::move(pending_remote_description_);
2686 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002687 }
Steve Anton8a006912017-12-04 15:25:56 -08002688 // The session description to apply now must be accessed by
2689 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002690 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002691
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002692 // Report statistics about any use of simulcast.
2693 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2694 *remote_description()->description());
2695
Zhi Huange830e682018-03-30 10:48:35 -07002696 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2697 if (!error.ok()) {
2698 return error;
2699 }
Steve Anton8a006912017-12-04 15:25:56 -08002700 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002701 if (IsUnifiedPlan()) {
2702 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002703 cricket::CS_REMOTE, *remote_description(), local_description(),
2704 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002705 if (!error.ok()) {
2706 return error;
2707 }
Steve Antondcc3c022017-12-22 16:02:54 -08002708 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002709 // Media channels will be created only when offer is set. These may use new
2710 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002711 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002712 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002713 // description is applied. Restore back to old description.
2714 RTCError error = CreateChannels(*remote_description()->description());
2715 if (!error.ok()) {
2716 return error;
2717 }
2718 }
Steve Antondcc3c022017-12-22 16:02:54 -08002719 // Remove unused channels if MediaContentDescription is rejected.
2720 RemoveUnusedChannels(remote_description()->description());
2721 }
Steve Anton8a006912017-12-04 15:25:56 -08002722
Zhi Huange830e682018-03-30 10:48:35 -07002723 // NOTE: Candidates allocation will be initiated only when
2724 // SetLocalDescription is called.
2725 error = UpdateSessionState(type, cricket::CS_REMOTE,
2726 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002727 if (!error.ok()) {
2728 return error;
2729 }
2730
2731 if (local_description() &&
2732 !UseCandidatesInSessionDescription(remote_description())) {
2733 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2734 }
2735
2736 if (old_remote_description) {
2737 for (const cricket::ContentInfo& content :
2738 old_remote_description->description()->contents()) {
2739 // Check if this new SessionDescription contains new ICE ufrag and
2740 // password that indicates the remote peer requests an ICE restart.
2741 // TODO(deadbeef): When we start storing both the current and pending
2742 // remote description, this should reset pending_ice_restarts and compare
2743 // against the current description.
2744 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2745 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002746 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002747 pending_ice_restarts_.insert(content.name);
2748 }
2749 } else {
2750 // We retain all received candidates only if ICE is not restarted.
2751 // When ICE is restarted, all previous candidates belong to an old
2752 // generation and should not be kept.
2753 // TODO(deadbeef): This goes against the W3C spec which says the remote
2754 // description should only contain candidates from the last set remote
2755 // description plus any candidates added since then. We should remove
2756 // this once we're sure it won't break anything.
2757 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2758 old_remote_description, content.name, mutable_remote_description());
2759 }
2760 }
2761 }
2762
2763 if (session_error() != SessionError::kNone) {
2764 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2765 }
2766
2767 // Set the the ICE connection state to connecting since the connection may
2768 // become writable with peer reflexive candidates before any remote candidate
2769 // is signaled.
2770 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2771 // is to have a new signal the indicates a change in checking state from the
2772 // transport and expose a new checking() member from transport that can be
2773 // read to determine the current checking state. The existing SignalConnecting
2774 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002775 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002776 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002777 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2778 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2779 }
2780
deadbeefab9b2d12015-10-14 11:33:11 -07002781 // If setting the description decided our SSL role, allocate any necessary
2782 // SCTP sids.
2783 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002784 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002785 AllocateSctpSids(role);
2786 }
2787
Steve Antondcc3c022017-12-22 16:02:54 -08002788 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002789 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002790 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002791 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002792 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002793 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002794 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002795 const ContentInfo* content =
2796 FindMediaSectionForTransceiver(transceiver, remote_description());
2797 if (!content) {
2798 continue;
2799 }
2800 const MediaContentDescription* media_desc = content->media_description();
2801 RtpTransceiverDirection local_direction =
2802 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002803 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2804 // RTCSessionDescription: Set the associated remote streams given
2805 // transceiver.[[Receiver]], msids, addList, and removeList".
2806 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2807 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2808 std::vector<std::string> stream_ids;
2809 if (!media_desc->streams().empty()) {
2810 // The remote description has signaled the stream IDs.
2811 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002812 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002813 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2814 << " (" << GetStreamIdsString(stream_ids) << ").";
2815 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2816 stream_ids, &added_streams,
2817 &removed_streams);
2818 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2819 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2820 // and transceiver's current direction is neither sendrecv nor recvonly,
2821 // process the addition of a remote track for the media description.
2822 if (!transceiver->fired_direction() ||
2823 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2824 RTC_LOG(LS_INFO)
2825 << "Processing the addition of a remote track for MID="
2826 << content->name << ".";
2827 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002828 }
Steve Antondcc3c022017-12-22 16:02:54 -08002829 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002830 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002831 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2832 // removal of a remote track for the media description, given transceiver,
2833 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002834 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002835 (transceiver->fired_direction() &&
2836 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2837 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2838 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002839 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002840 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002841 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002842 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002843 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002844 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002845 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002846 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002847 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002848 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2849 if (transceiver->mid()) {
2850 auto dtls_transport =
2851 LookupDtlsTransportByMidInternal(*transceiver->mid());
2852 transceiver->internal()->sender_internal()->set_transport(
2853 dtls_transport);
2854 transceiver->internal()->receiver_internal()->set_transport(
2855 dtls_transport);
2856 }
Steve Antondcc3c022017-12-22 16:02:54 -08002857 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002858 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002859 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002860 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002861 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2862 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002863 transceiver->Stop();
2864 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002865 if (!content->rejected &&
2866 RtpTransceiverDirectionHasRecv(local_direction)) {
2867 // Set ssrc to 0 in the case of an unsignalled ssrc.
2868 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002869 if (!media_desc->streams().empty() &&
2870 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002871 ssrc = media_desc->streams()[0].first_ssrc();
2872 }
2873 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002874 }
Steve Antondcc3c022017-12-22 16:02:54 -08002875 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002876 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002877 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002878 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002879 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002880 observer->OnTrack(transceiver);
2881 observer->OnAddTrack(transceiver->receiver(),
2882 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002883 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002884 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002885 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002886 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002887 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002888 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002889 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002890 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002891 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002892 }
Steve Antondcc3c022017-12-22 16:02:54 -08002893 }
2894
Henrik Boströmfdb92012017-11-09 19:55:44 +01002895 const cricket::ContentInfo* audio_content =
2896 GetFirstAudioContent(remote_description()->description());
2897 const cricket::ContentInfo* video_content =
2898 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002899 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002900 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002901 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002902 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002903 const cricket::RtpDataContentDescription* rtp_data_desc =
2904 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002905
2906 // Check if the descriptions include streams, just in case the peer supports
2907 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002908 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002909 (audio_desc && !audio_desc->streams().empty()) ||
2910 (video_desc && !video_desc->streams().empty())) {
2911 remote_peer_supports_msid_ = true;
2912 }
deadbeefab9b2d12015-10-14 11:33:11 -07002913
2914 // We wait to signal new streams until we finish processing the description,
2915 // since only at that point will new streams have all their tracks.
2916 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2917
Steve Antondcc3c022017-12-22 16:02:54 -08002918 if (!IsUnifiedPlan()) {
2919 // TODO(steveanton): When removing RTP senders/receivers in response to a
2920 // rejected media section, there is some cleanup logic that expects the
2921 // voice/ video channel to still be set. But in this method the voice/video
2922 // channel would have been destroyed by the SetRemoteDescription caller
2923 // above so the cleanup that relies on them fails to run. The RemoveSenders
2924 // calls should be moved to right before the DestroyChannel calls to fix
2925 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002926
Steve Antondcc3c022017-12-22 16:02:54 -08002927 // Find all audio rtp streams and create corresponding remote AudioTracks
2928 // and MediaStreams.
2929 if (audio_content) {
2930 if (audio_content->rejected) {
2931 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2932 } else {
2933 bool default_audio_track_needed =
2934 !remote_peer_supports_msid_ &&
2935 RtpTransceiverDirectionHasSend(audio_desc->direction());
2936 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2937 default_audio_track_needed, audio_desc->type(),
2938 new_streams);
2939 }
deadbeeffaac4972015-11-12 15:33:07 -08002940 }
deadbeefab9b2d12015-10-14 11:33:11 -07002941
Steve Antondcc3c022017-12-22 16:02:54 -08002942 // Find all video rtp streams and create corresponding remote VideoTracks
2943 // and MediaStreams.
2944 if (video_content) {
2945 if (video_content->rejected) {
2946 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2947 } else {
2948 bool default_video_track_needed =
2949 !remote_peer_supports_msid_ &&
2950 RtpTransceiverDirectionHasSend(video_desc->direction());
2951 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2952 default_video_track_needed, video_desc->type(),
2953 new_streams);
2954 }
deadbeeffaac4972015-11-12 15:33:07 -08002955 }
deadbeefab9b2d12015-10-14 11:33:11 -07002956
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002957 // If this is an RTP data transport, update the DataChannels with the
2958 // information from the remote peer.
2959 if (rtp_data_desc) {
2960 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002961 }
deadbeefab9b2d12015-10-14 11:33:11 -07002962
Steve Antondcc3c022017-12-22 16:02:54 -08002963 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002964 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002965 for (size_t i = 0; i < new_streams->count(); ++i) {
2966 MediaStreamInterface* new_stream = new_streams->at(i);
2967 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002968 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002969 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2970 }
deadbeefab9b2d12015-10-14 11:33:11 -07002971
Steve Antondcc3c022017-12-22 16:02:54 -08002972 UpdateEndedRemoteMediaStreams();
2973 }
deadbeefab9b2d12015-10-14 11:33:11 -07002974
Henrik Boström79b69802019-07-18 11:16:56 +02002975 if (type == SdpType::kAnswer &&
2976 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2977 *current_local_description_)) {
2978 local_ice_credentials_to_replace_->ClearIceCredentials();
2979 }
2980
Steve Anton8a006912017-12-04 15:25:56 -08002981 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002982}
2983
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002984void PeerConnection::SetAssociatedRemoteStreams(
2985 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2986 const std::vector<std::string>& stream_ids,
2987 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2988 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2989 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2990 for (const std::string& stream_id : stream_ids) {
2991 rtc::scoped_refptr<MediaStreamInterface> stream =
2992 remote_streams_->find(stream_id);
2993 if (!stream) {
2994 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2995 MediaStream::Create(stream_id));
2996 remote_streams_->AddStream(stream);
2997 added_streams->push_back(stream);
2998 }
2999 media_streams.push_back(stream);
3000 }
3001 // Special case: "a=msid" missing, use random stream ID.
3002 if (media_streams.empty() &&
3003 !(remote_description()->description()->msid_signaling() &
3004 cricket::kMsidSignalingMediaSection)) {
3005 if (!missing_msid_default_stream_) {
3006 missing_msid_default_stream_ = MediaStreamProxy::Create(
3007 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3008 added_streams->push_back(missing_msid_default_stream_);
3009 }
3010 media_streams.push_back(missing_msid_default_stream_);
3011 }
3012 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3013 receiver->streams();
3014 // SetStreams() will add/remove the receiver's track to/from the streams. This
3015 // differs from the spec - the spec uses an "addList" and "removeList" to
3016 // update the stream-track relationships in a later step. We do this earlier,
3017 // changing the order of things, but the end-result is the same.
3018 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3019 // instead. https://crbug.com/webrtc/9480
3020 receiver->SetStreams(media_streams);
3021 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3022}
3023
Steve Anton0f5400a2018-07-17 14:25:36 -07003024void PeerConnection::ProcessRemovalOfRemoteTrack(
3025 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3026 transceiver,
3027 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3028 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3029 RTC_DCHECK(transceiver->mid());
3030 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3031 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003032 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003033 transceiver->internal()->receiver_internal()->streams();
3034 // This will remove the remote track from the streams.
3035 transceiver->internal()->receiver_internal()->set_stream_ids({});
3036 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003037 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3038}
3039
3040void PeerConnection::RemoveRemoteStreamsIfEmpty(
3041 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3042 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3043 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3044 // streams, see if the stream was removed by checking if this was the last
3045 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003046 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003047 if (remote_stream->GetAudioTracks().empty() &&
3048 remote_stream->GetVideoTracks().empty()) {
3049 remote_streams_->RemoveStream(remote_stream);
3050 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003051 }
3052 }
3053}
3054
Steve Antondcc3c022017-12-22 16:02:54 -08003055RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3056 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003057 const SessionDescriptionInterface& new_session,
3058 const SessionDescriptionInterface* old_local_description,
3059 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003060 RTC_DCHECK(IsUnifiedPlan());
3061
Steve Anton7464fca2018-01-19 11:10:37 -08003062 const cricket::ContentGroup* bundle_group = nullptr;
3063 if (new_session.GetType() == SdpType::kOffer) {
3064 auto bundle_group_or_error =
3065 GetEarlyBundleGroup(*new_session.description());
3066 if (!bundle_group_or_error.ok()) {
3067 return bundle_group_or_error.MoveError();
3068 }
3069 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003070 }
Steve Antondcc3c022017-12-22 16:02:54 -08003071
Steve Antondcc3c022017-12-22 16:02:54 -08003072 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003073 for (size_t i = 0; i < new_contents.size(); ++i) {
3074 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003075 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003076 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003077 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3078 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003079 const cricket::ContentInfo* old_local_content = nullptr;
3080 if (old_local_description &&
3081 i < old_local_description->description()->contents().size()) {
3082 old_local_content =
3083 &old_local_description->description()->contents()[i];
3084 }
3085 const cricket::ContentInfo* old_remote_content = nullptr;
3086 if (old_remote_description &&
3087 i < old_remote_description->description()->contents().size()) {
3088 old_remote_content =
3089 &old_remote_description->description()->contents()[i];
3090 }
Steve Antondcc3c022017-12-22 16:02:54 -08003091 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003092 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3093 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003094 if (!transceiver_or_error.ok()) {
3095 return transceiver_or_error.MoveError();
3096 }
3097 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003098 RTCError error =
3099 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3100 if (!error.ok()) {
3101 return error;
3102 }
3103 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003104 if (GetDataMid() && new_content.name != *GetDataMid()) {
3105 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003106 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3107 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003108 continue;
3109 }
3110 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3111 if (!error.ok()) {
3112 return error;
3113 }
Steve Antondcc3c022017-12-22 16:02:54 -08003114 } else {
3115 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3116 "Unknown section type.");
3117 }
3118 }
3119
3120 return RTCError::OK();
3121}
3122
3123RTCError PeerConnection::UpdateTransceiverChannel(
3124 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3125 transceiver,
3126 const cricket::ContentInfo& content,
3127 const cricket::ContentGroup* bundle_group) {
3128 RTC_DCHECK(IsUnifiedPlan());
3129 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003130 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003131 if (content.rejected) {
3132 if (channel) {
3133 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003134 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003135 }
3136 } else {
3137 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003138 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003139 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003140 } else {
Steve Anton69470252018-02-09 11:43:08 -08003141 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003142 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003143 }
3144 if (!channel) {
3145 LOG_AND_RETURN_ERROR(
3146 RTCErrorType::INTERNAL_ERROR,
3147 "Failed to create channel for mid=" + content.name);
3148 }
3149 transceiver->internal()->SetChannel(channel);
3150 }
3151 }
3152 return RTCError::OK();
3153}
3154
Steve Antonfa2260d2017-12-28 16:38:23 -08003155RTCError PeerConnection::UpdateDataChannel(
3156 cricket::ContentSource source,
3157 const cricket::ContentInfo& content,
3158 const cricket::ContentGroup* bundle_group) {
3159 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003160 // If data channels are disabled, ignore this media section. CreateAnswer
3161 // will take care of rejecting it.
3162 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003163 }
3164 if (content.rejected) {
3165 DestroyDataChannel();
3166 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003167 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003168 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003169 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3170 "Failed to create data channel.");
3171 }
3172 }
3173 if (source == cricket::CS_REMOTE) {
3174 const MediaContentDescription* data_desc = content.media_description();
3175 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3176 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3177 }
3178 }
3179 }
3180 return RTCError::OK();
3181}
3182
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003183// This method will extract any send encodings that were sent by the remote
3184// connection. This is currently only relevant for Simulcast scenario (where
3185// the number of layers may be communicated by the server).
3186static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3187 const MediaContentDescription& desc) {
3188 if (!desc.HasSimulcast()) {
3189 return {};
3190 }
3191 std::vector<RtpEncodingParameters> result;
3192 const SimulcastDescription& simulcast = desc.simulcast_description();
3193
3194 // This is a remote description, the parameters we are after should appear
3195 // as receive streams.
3196 for (const auto& alternatives : simulcast.receive_layers()) {
3197 RTC_DCHECK(!alternatives.empty());
3198 // There is currently no way to specify or choose from alternatives.
3199 // We will always use the first alternative, which is the most preferred.
3200 const SimulcastLayer& layer = alternatives[0];
3201 RtpEncodingParameters parameters;
3202 parameters.rid = layer.rid;
3203 parameters.active = !layer.is_paused;
3204 result.push_back(parameters);
3205 }
3206
3207 return result;
3208}
3209
3210static RTCError UpdateSimulcastLayerStatusInSender(
3211 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003212 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003213 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003214 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003215 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003216
3217 // The simulcast envelope cannot be changed, only the status of the streams.
3218 // So we will iterate over the send encodings rather than the layers.
3219 for (RtpEncodingParameters& encoding : parameters.encodings) {
3220 auto iter = std::find_if(layers.begin(), layers.end(),
3221 [&encoding](const SimulcastLayer& layer) {
3222 return layer.rid == encoding.rid;
3223 });
3224 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003225 if (iter == layers.end()) {
3226 disabled_layers.push_back(encoding.rid);
3227 continue;
3228 }
3229
3230 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003231 }
3232
Amit Hilbuch619b2942019-02-26 15:55:19 -08003233 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003234 if (result.ok()) {
3235 result = sender->DisableEncodingLayers(disabled_layers);
3236 }
3237
3238 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003239}
3240
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003241static bool SimulcastIsRejected(
3242 const ContentInfo* local_content,
3243 const MediaContentDescription& answer_media_desc) {
3244 bool simulcast_offered = local_content &&
3245 local_content->media_description() &&
3246 local_content->media_description()->HasSimulcast();
3247 bool simulcast_answered = answer_media_desc.HasSimulcast();
3248 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3249 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3250 return simulcast_offered && (!simulcast_answered || !rids_supported);
3251}
3252
Amit Hilbuch2297d332019-02-19 12:49:22 -08003253static RTCError DisableSimulcastInSender(
3254 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003255 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003256 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003257 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003258 return RTCError::OK();
3259 }
3260
Amit Hilbuch2297d332019-02-19 12:49:22 -08003261 std::vector<std::string> disabled_layers;
3262 std::transform(
3263 parameters.encodings.begin() + 1, parameters.encodings.end(),
3264 std::back_inserter(disabled_layers),
3265 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3266 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003267}
3268
Steve Antondcc3c022017-12-22 16:02:54 -08003269RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3270PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003271 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003272 size_t mline_index,
3273 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003274 const ContentInfo* old_local_content,
3275 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003276 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003277 // If this is an offer then the m= section might be recycled. If the m=
3278 // section is being recycled (defined as: rejected in the current local or
3279 // remote description and not rejected in new description), dissociate the
3280 // currently associated RtpTransceiver by setting its mid property to null,
3281 // and discard the mapping between the transceiver and its m= section index.
3282 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3283 old_remote_content)) {
3284 // We want to dissociate the transceiver that has the rejected mid.
3285 const std::string& old_mid =
3286 (old_local_content && old_local_content->rejected)
3287 ? old_local_content->name
3288 : old_remote_content->name;
3289 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003290 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003291 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3292 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003293 old_transceiver->internal()->set_mid(absl::nullopt);
3294 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003295 }
3296 }
3297 const MediaContentDescription* media_desc = content.media_description();
3298 auto transceiver = GetAssociatedTransceiver(content.name);
3299 if (source == cricket::CS_LOCAL) {
3300 // Find the RtpTransceiver that corresponds to this m= section, using the
3301 // mapping between transceivers and m= section indices established when
3302 // creating the offer.
3303 if (!transceiver) {
3304 transceiver = GetTransceiverByMLineIndex(mline_index);
3305 }
3306 if (!transceiver) {
3307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3308 "Unknown transceiver");
3309 }
3310 } else {
3311 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3312 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3313 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003314 // When simulcast is requested, a transceiver cannot be associated because
3315 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003316 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003317 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3318 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003319 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3320 }
3321 // If no RtpTransceiver was found in the previous step, create one with a
3322 // recvonly direction.
3323 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003324 RTC_LOG(LS_INFO) << "Adding "
3325 << cricket::MediaTypeToString(media_desc->type())
3326 << " transceiver for MID=" << content.name
3327 << " at i=" << mline_index
3328 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003329 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003330 std::vector<RtpEncodingParameters> send_encodings =
3331 GetSendEncodingsFromRemoteDescription(*media_desc);
3332 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3333 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003334 std::string receiver_id;
3335 if (!media_desc->streams().empty()) {
3336 receiver_id = media_desc->streams()[0].id;
3337 } else {
3338 receiver_id = rtc::CreateRandomUuid();
3339 }
3340 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003341 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003342 transceiver->internal()->set_direction(
3343 RtpTransceiverDirection::kRecvOnly);
3344 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003345
3346 // Check if the offer indicated simulcast but the answer rejected it.
3347 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003348 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003349 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003350 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003351 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003352 if (!error.ok()) {
3353 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3354 return std::move(error);
3355 }
3356 }
Steve Antondcc3c022017-12-22 16:02:54 -08003357 }
3358 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003359 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003360 LOG_AND_RETURN_ERROR(
3361 RTCErrorType::INVALID_PARAMETER,
3362 "Transceiver type does not match media description type.");
3363 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003364 if (media_desc->HasSimulcast()) {
3365 std::vector<SimulcastLayer> layers =
3366 source == cricket::CS_LOCAL
3367 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3368 : media_desc->simulcast_description()
3369 .receive_layers()
3370 .GetAllLayers();
3371 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003372 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003373 if (!error.ok()) {
3374 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3375 return std::move(error);
3376 }
3377 }
Steve Antondcc3c022017-12-22 16:02:54 -08003378 // Associate the found or created RtpTransceiver with the m= section by
3379 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3380 // section, and establish a mapping between the transceiver and the index of
3381 // the m= section.
3382 transceiver->internal()->set_mid(content.name);
3383 transceiver->internal()->set_mline_index(mline_index);
3384 return std::move(transceiver);
3385}
3386
3387rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3388PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3389 RTC_DCHECK(IsUnifiedPlan());
3390 for (auto transceiver : transceivers_) {
3391 if (transceiver->mid() == mid) {
3392 return transceiver;
3393 }
3394 }
3395 return nullptr;
3396}
3397
3398rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3399PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3400 RTC_DCHECK(IsUnifiedPlan());
3401 for (auto transceiver : transceivers_) {
3402 if (transceiver->internal()->mline_index() == mline_index) {
3403 return transceiver;
3404 }
3405 }
3406 return nullptr;
3407}
3408
3409rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3410PeerConnection::FindAvailableTransceiverToReceive(
3411 cricket::MediaType media_type) const {
3412 RTC_DCHECK(IsUnifiedPlan());
3413 // From JSEP section 5.10 (Applying a Remote Description):
3414 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3415 // the same type that were added to the PeerConnection by addTrack and are not
3416 // associated with any m= section and are not stopped, find the first such
3417 // RtpTransceiver.
3418 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003419 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003420 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3421 !transceiver->stopped()) {
3422 return transceiver;
3423 }
3424 }
3425 return nullptr;
3426}
3427
Steve Antoned10bd92017-12-05 10:52:59 -08003428const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3429 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3430 transceiver,
3431 const SessionDescriptionInterface* sdesc) const {
3432 RTC_DCHECK(transceiver);
3433 RTC_DCHECK(sdesc);
3434 if (IsUnifiedPlan()) {
3435 if (!transceiver->internal()->mid()) {
3436 // This transceiver is not associated with a media section yet.
3437 return nullptr;
3438 }
3439 return sdesc->description()->GetContentByName(
3440 *transceiver->internal()->mid());
3441 } else {
3442 // Plan B only allows at most one audio and one video section, so use the
3443 // first media section of that type.
3444 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003445 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003446 }
3447}
3448
deadbeef46c73892016-11-16 19:42:04 -08003449PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003450 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003451 return configuration_;
3452}
3453
deadbeef293e9262017-01-11 12:28:30 -08003454bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3455 RTCError* error) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003456 RTCError result = SetConfiguration(configuration);
3457 bool success = result.ok();
3458 if (error) {
3459 *error = std::move(result);
3460 }
3461 return success;
3462}
3463
3464RTCError PeerConnection::SetConfiguration(
3465 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003466 RTC_DCHECK_RUN_ON(signaling_thread());
3467 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003468 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003469 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003470 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3471 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003472 }
3473
Qingsi Wanga2d60672018-04-11 16:57:45 -07003474 // According to JSEP, after setLocalDescription, changing the candidate pool
3475 // size is not allowed, and changing the set of ICE servers will not result
3476 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003477 if (local_description() && configuration.ice_candidate_pool_size !=
3478 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003479 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3480 "Can't change candidate pool size after calling "
3481 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003482 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003483
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003484 if (local_description() &&
3485 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003486 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3487 "Can't change media_transport after calling "
3488 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003489 }
3490
3491 if (remote_description() &&
3492 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3494 "Can't change media_transport after calling "
3495 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003496 }
3497
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003498 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003499 configuration.use_media_transport_for_data_channels !=
3500 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3502 "Can't change media_transport_for_data_channels "
3503 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003504 }
3505
3506 if (remote_description() &&
3507 configuration.use_media_transport_for_data_channels !=
3508 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003509 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3510 "Can't change media_transport_for_data_channels "
3511 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003512 }
3513
3514 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003515 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003516 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3517 "Can't change crypto_options after calling "
3518 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003519 }
3520
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003521 if (local_description() && configuration.use_datagram_transport !=
3522 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003523 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3524 "Can't change use_datagram_transport "
3525 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003526 }
3527
3528 if (remote_description() && configuration.use_datagram_transport !=
3529 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003530 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3531 "Can't change use_datagram_transport "
3532 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003533 }
3534
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003535 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003536 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003537 (configuration.use_datagram_transport &&
3538 *configuration.use_datagram_transport)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003539 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3540 << "Media transport requires MaxBundle policy.";
3541 }
3542
deadbeef293e9262017-01-11 12:28:30 -08003543 // The simplest (and most future-compatible) way to tell if the config was
3544 // modified in an invalid way is to copy each property we do support
3545 // modifying, then use operator==. There are far more properties we don't
3546 // support modifying than those we do, and more could be added.
3547 RTCConfiguration modified_config = configuration_;
3548 modified_config.servers = configuration.servers;
3549 modified_config.type = configuration.type;
3550 modified_config.ice_candidate_pool_size =
3551 configuration.ice_candidate_pool_size;
3552 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003553 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3554 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003555 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003556 modified_config.ice_check_interval_strong_connectivity =
3557 configuration.ice_check_interval_strong_connectivity;
3558 modified_config.ice_check_interval_weak_connectivity =
3559 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003560 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3561 modified_config.ice_unwritable_min_checks =
3562 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003563 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003564 modified_config.stun_candidate_keepalive_interval =
3565 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003566 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003567 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003568 modified_config.active_reset_srtp_params =
3569 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003570 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003571 modified_config.use_media_transport_for_data_channels =
3572 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003573 modified_config.use_datagram_transport = configuration.use_datagram_transport;
deadbeef293e9262017-01-11 12:28:30 -08003574 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003575 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3576 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003577 }
3578
Steve Anton038834f2017-07-14 15:59:59 -07003579 // Validate the modified configuration.
3580 RTCError validate_error = ValidateConfiguration(modified_config);
3581 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003582 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003583 }
3584
deadbeef293e9262017-01-11 12:28:30 -08003585 // Note that this isn't possible through chromium, since it's an unsigned
3586 // short in WebIDL.
3587 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003588 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003589 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003590 }
3591
3592 // Parse ICE servers before hopping to network thread.
3593 cricket::ServerAddresses stun_servers;
3594 std::vector<cricket::RelayServerConfig> turn_servers;
3595 RTCErrorType parse_error =
3596 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3597 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003598 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003599 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003600 // Note if STUN or TURN servers were supplied.
3601 if (!stun_servers.empty()) {
3602 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3603 }
3604 if (!turn_servers.empty()) {
3605 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3606 }
deadbeef293e9262017-01-11 12:28:30 -08003607
3608 // In theory this shouldn't fail.
3609 if (!network_thread()->Invoke<bool>(
3610 RTC_FROM_HERE,
3611 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3612 stun_servers, turn_servers, modified_config.type,
3613 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003614 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003615 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003616 modified_config.stun_candidate_keepalive_interval,
3617 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003618 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3619 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003620 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003621
deadbeefd1a38b52016-12-10 13:15:33 -08003622 // As described in JSEP, calling setConfiguration with new ICE servers or
3623 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3624 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003625 if (modified_config.servers != configuration_.servers ||
3626 modified_config.type != configuration_.type ||
3627 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003628 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003629 }
skvladd1f5fda2017-02-03 16:54:05 -08003630
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003631 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003632
3633 use_datagram_transport_ = datagram_transport_config_.enabled &&
3634 modified_config.use_datagram_transport.value_or(
3635 datagram_transport_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003636 transport_controller_->SetMediaTransportSettings(
3637 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003638 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003639 use_datagram_transport_);
skvladd1f5fda2017-02-03 16:54:05 -08003640
Zhi Huangb57e1692018-06-12 11:41:11 -07003641 if (configuration_.active_reset_srtp_params !=
3642 modified_config.active_reset_srtp_params) {
3643 transport_controller_->SetActiveResetSrtpParams(
3644 modified_config.active_reset_srtp_params);
3645 }
3646
deadbeef293e9262017-01-11 12:28:30 -08003647 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003648 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003649 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003650}
3651
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003652bool PeerConnection::AddIceCandidate(
3653 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003654 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003655 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003656 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003657 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003658 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003659 return false;
3660 }
Steve Antond25da372017-11-06 14:50:29 -08003661
3662 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003663 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003664 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003665 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003666 return false;
3667 }
3668
3669 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003670 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003671 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003672 return false;
3673 }
3674
3675 bool valid = false;
3676 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3677 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003678 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003679 return false;
3680 }
3681
3682 // Add this candidate to the remote session description.
3683 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003684 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003685 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003686 return false;
3687 }
3688
3689 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003690 bool result = UseCandidate(ice_candidate);
3691 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003692 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003693 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3694 } else {
3695 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3696 }
3697 return result;
Steve Antond25da372017-11-06 14:50:29 -08003698 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003699 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003700 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003701 return true;
3702 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003703}
3704
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003705bool PeerConnection::RemoveIceCandidates(
3706 const std::vector<cricket::Candidate>& candidates) {
3707 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003708 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003709 if (IsClosed()) {
3710 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3711 return false;
3712 }
3713
Steve Antond25da372017-11-06 14:50:29 -08003714 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003715 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3716 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003717 return false;
3718 }
3719
3720 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003721 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003722 return false;
3723 }
3724
3725 size_t number_removed =
3726 mutable_remote_description()->RemoveCandidates(candidates);
3727 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003728 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003729 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003730 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003731 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003732 }
3733
3734 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003735 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3736 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003737 RTC_LOG(LS_ERROR)
3738 << "RemoveIceCandidates: Error when removing remote candidates: "
3739 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003740 }
3741 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003742}
3743
Niels Möller0c4f7be2018-05-07 14:01:37 +02003744RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003745 if (!worker_thread()->IsCurrent()) {
3746 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003747 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003748 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003749 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003750
Niels Möller0c4f7be2018-05-07 14:01:37 +02003751 const bool has_min = bitrate.min_bitrate_bps.has_value();
3752 const bool has_start = bitrate.start_bitrate_bps.has_value();
3753 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003754 if (has_min && *bitrate.min_bitrate_bps < 0) {
3755 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3756 "min_bitrate_bps <= 0");
3757 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003758 if (has_start) {
3759 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003760 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003761 "start_bitrate_bps < min_bitrate_bps");
3762 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003763 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3764 "curent_bitrate_bps < 0");
3765 }
3766 }
3767 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003768 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003769 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003770 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003771 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3772 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3773 "max_bitrate_bps < min_bitrate_bps");
3774 } else if (*bitrate.max_bitrate_bps < 0) {
3775 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3776 "max_bitrate_bps < 0");
3777 }
3778 }
3779
zstein4b979802017-06-02 14:37:37 -07003780 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003781 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003782
3783 return RTCError::OK();
3784}
3785
henrika5f6bf242017-11-01 11:06:56 +01003786void PeerConnection::SetAudioPlayout(bool playout) {
3787 if (!worker_thread()->IsCurrent()) {
3788 worker_thread()->Invoke<void>(
3789 RTC_FROM_HERE,
3790 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3791 return;
3792 }
3793 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003794 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003795 audio_state->SetPlayout(playout);
3796}
3797
3798void PeerConnection::SetAudioRecording(bool recording) {
3799 if (!worker_thread()->IsCurrent()) {
3800 worker_thread()->Invoke<void>(
3801 RTC_FROM_HERE,
3802 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3803 return;
3804 }
3805 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003806 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003807 audio_state->SetRecording(recording);
3808}
3809
Steve Anton8c0f7a72017-10-03 10:03:10 -07003810std::unique_ptr<rtc::SSLCertificate>
3811PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003812 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3813 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003814 return nullptr;
3815 }
Steve Antonf25303e2018-10-16 15:23:31 -07003816 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003817}
3818
Zhi Huang70b820f2018-01-27 14:16:15 -08003819std::unique_ptr<rtc::SSLCertChain>
3820PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003821 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003822 auto audio_transceiver = GetFirstAudioTransceiver();
3823 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003824 return nullptr;
3825 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003826 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003827 audio_transceiver->internal()->channel()->transport_name());
3828}
3829
3830rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3831PeerConnection::GetFirstAudioTransceiver() const {
3832 for (auto transceiver : transceivers_) {
3833 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3834 return transceiver;
3835 }
3836 }
3837 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003838}
3839
Bjorn Tereliusde939432017-11-20 17:38:14 +01003840bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3841 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003842 // TODO(eladalon): In C++14, this can be done with a lambda.
3843 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003844 bool operator()() {
3845 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3846 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003847 PeerConnection* const pc;
3848 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003849 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003850 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003851 return worker_thread()->Invoke<bool>(
3852 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003853}
3854
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003855bool PeerConnection::StartRtcEventLog(
3856 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003857 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3858 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3859 output_period_ms = 5000;
3860 }
3861 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003862}
3863
ivoc14d5dbe2016-07-04 07:06:55 -07003864void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003865 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003866 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3867}
3868
Harald Alvestrandad88c882018-11-28 16:47:46 +01003869rtc::scoped_refptr<DtlsTransportInterface>
3870PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003871 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003872 return transport_controller_->LookupDtlsTransportByMid(mid);
3873}
3874
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003875rtc::scoped_refptr<DtlsTransport>
3876PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003877 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003878 return transport_controller_->LookupDtlsTransportByMid(mid);
3879}
3880
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003881rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3882 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003883 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003884 return sctp_transport_;
3885}
3886
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003887const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003888 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003889 return pending_local_description_ ? pending_local_description_.get()
3890 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003891}
3892
3893const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003894 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003895 return pending_remote_description_ ? pending_remote_description_.get()
3896 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003897}
3898
deadbeeffe4a8a42016-12-20 17:56:17 -08003899const SessionDescriptionInterface* PeerConnection::current_local_description()
3900 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003901 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003902 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003903}
3904
3905const SessionDescriptionInterface* PeerConnection::current_remote_description()
3906 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003907 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003908 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003909}
3910
3911const SessionDescriptionInterface* PeerConnection::pending_local_description()
3912 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003913 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003914 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003915}
3916
3917const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3918 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003919 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003920 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003921}
3922
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003923void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003924 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003925 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003926 // Update stats here so that we have the most recent stats for tracks and
3927 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003928 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003929
Steve Anton75737c02017-11-06 10:37:17 -08003930 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003931 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003932
Mirko Bonadei739baf02019-01-27 17:29:42 +01003933 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003934 transceiver->Stop();
3935 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003936
3937 // Ensure that all asynchronous stats requests are completed before destroying
3938 // the transport controller below.
3939 if (stats_collector_) {
3940 stats_collector_->WaitForPendingRequest();
3941 }
3942
3943 // Don't destroy BaseChannels until after stats has been cleaned up so that
3944 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003945 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003946
Qingsi Wang93a84392018-01-30 17:13:09 -08003947 // The event log is used in the transport controller, which must be outlived
3948 // by the former. CreateOffer by the peer connection is implemented
3949 // asynchronously and if the peer connection is closed without resetting the
3950 // WebRTC session description factory, the session description factory would
3951 // call the transport controller.
3952 webrtc_session_desc_factory_.reset();
3953 transport_controller_.reset();
3954
deadbeef42a42632017-03-10 15:18:00 -08003955 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003956 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3957 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003958
Steve Anton978b8762017-09-29 12:15:02 -07003959 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003960 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003961 call_.reset();
3962 // The event log must outlive call (and any other object that uses it).
3963 event_log_.reset();
3964 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003965 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003966 // The .h file says that observer can be discarded after close() returns.
3967 // Make sure this is true.
3968 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003969}
3970
Steve Antonad182762018-09-05 20:22:40 +00003971void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003972 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003973 switch (msg->message_id) {
3974 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3975 SetSessionDescriptionMsg* param =
3976 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3977 param->observer->OnSuccess();
3978 delete param;
3979 break;
3980 }
3981 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3982 SetSessionDescriptionMsg* param =
3983 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3984 param->observer->OnFailure(std::move(param->error));
3985 delete param;
3986 break;
3987 }
3988 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3989 CreateSessionDescriptionMsg* param =
3990 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3991 param->observer->OnFailure(std::move(param->error));
3992 delete param;
3993 break;
3994 }
3995 case MSG_GETSTATS: {
3996 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3997 StatsReports reports;
3998 stats_->GetStats(param->track, &reports);
3999 param->observer->OnComplete(reports);
4000 delete param;
4001 break;
4002 }
4003 case MSG_FREE_DATACHANNELS: {
4004 sctp_data_channels_to_free_.clear();
4005 break;
4006 }
4007 case MSG_REPORT_USAGE_PATTERN: {
4008 ReportUsagePattern();
4009 break;
4010 }
4011 default:
4012 RTC_NOTREACHED() << "Not implemented";
4013 break;
4014 }
4015}
4016
Steve Antonafb0bb72018-02-20 11:35:37 -08004017cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4018 RTC_DCHECK(!IsUnifiedPlan());
4019 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4020 GetAudioTransceiver()->internal()->channel());
4021 if (voice_channel) {
4022 return voice_channel->media_channel();
4023 } else {
4024 return nullptr;
4025 }
4026}
4027
4028cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4029 RTC_DCHECK(!IsUnifiedPlan());
4030 auto* video_channel = static_cast<cricket::VideoChannel*>(
4031 GetVideoTransceiver()->internal()->channel());
4032 if (video_channel) {
4033 return video_channel->media_channel();
4034 } else {
4035 return nullptr;
4036 }
4037}
4038
Steve Anton4171afb2017-11-20 10:20:22 -08004039void PeerConnection::CreateAudioReceiver(
4040 MediaStreamInterface* stream,
4041 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004042 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4043 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004044 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4045 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004046 auto* audio_receiver = new AudioRtpReceiver(
4047 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004048 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004049 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4050 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4051 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004052 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004053 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004054 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004055}
4056
Steve Anton4171afb2017-11-20 10:20:22 -08004057void PeerConnection::CreateVideoReceiver(
4058 MediaStreamInterface* stream,
4059 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004060 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4061 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004062 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4063 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004064 auto* video_receiver = new VideoRtpReceiver(
4065 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004066 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004067 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4068 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4069 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004070 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004071 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004072 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004073}
4074
deadbeef70ab1a12015-09-28 16:53:55 -07004075// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4076// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004077rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004078 const RtpSenderInfo& remote_sender_info) {
4079 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4080 if (!receiver) {
4081 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4082 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004083 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004084 }
Steve Anton4171afb2017-11-20 10:20:22 -08004085 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4086 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4087 } else {
4088 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4089 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004090 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004091}
4092
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004093void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4094 MediaStreamInterface* stream) {
4095 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004096 RTC_DCHECK(track);
4097 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004098 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004099 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004100 // We already have a sender for this track, so just change the stream_id
4101 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004102 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004103 return;
4104 }
4105
4106 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004107 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004108 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004109 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004110 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004111 // If the sender has already been configured in SDP, we call SetSsrc,
4112 // which will connect the sender to the underlying transport. This can
4113 // occur if a local session description that contains the ID of the sender
4114 // is set before AddStream is called. It can also occur if the local
4115 // session description is not changed and RemoveStream is called, and
4116 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004117 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004118 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004119 if (sender_info) {
4120 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004121 }
4122}
4123
4124// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4125// indefinitely, when we have unified plan SDP.
4126void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4127 MediaStreamInterface* stream) {
4128 RTC_DCHECK(!IsClosed());
4129 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004130 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004131 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4132 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004133 return;
4134 }
Steve Anton4171afb2017-11-20 10:20:22 -08004135 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004136}
4137
4138void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4139 MediaStreamInterface* stream) {
4140 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004141 RTC_DCHECK(track);
4142 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004143 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004144 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004145 // We already have a sender for this track, so just change the stream_id
4146 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004147 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004148 return;
4149 }
4150
4151 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004152 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004153 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004154 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004155 GetVideoTransceiver()->internal()->AddSender(new_sender);
4156 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004157 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004158 if (sender_info) {
4159 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004160 }
4161}
4162
4163void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4164 MediaStreamInterface* stream) {
4165 RTC_DCHECK(!IsClosed());
4166 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004167 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004168 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4169 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004170 return;
4171 }
Steve Anton4171afb2017-11-20 10:20:22 -08004172 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004173}
4174
Steve Antonba818672017-11-06 10:21:57 -08004175void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004176 if (ice_connection_state_ == new_state) {
4177 return;
4178 }
4179
deadbeefcbecd352015-09-23 11:50:27 -07004180 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004181 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004182 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004183 return;
4184 }
Steve Antonba818672017-11-06 10:21:57 -08004185
Mirko Bonadei675513b2017-11-09 11:09:25 +01004186 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4187 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004188 RTC_DCHECK(ice_connection_state_ !=
4189 PeerConnectionInterface::kIceConnectionClosed);
4190
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004191 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004192 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004193}
4194
Alex Loiko9289eda2018-11-23 16:18:59 +00004195void PeerConnection::SetStandardizedIceConnectionState(
4196 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004197 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004198 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004199 }
4200
4201 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004202 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004203 }
4204
4205 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4206 << standardized_ice_connection_state_ << " => " << new_state;
4207
Alex Loiko9289eda2018-11-23 16:18:59 +00004208 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004209 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004210}
4211
Jonas Olsson635474e2018-10-18 15:58:17 +02004212void PeerConnection::SetConnectionState(
4213 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004214 if (connection_state_ == new_state)
4215 return;
4216 if (IsClosed())
4217 return;
4218 connection_state_ = new_state;
4219 Observer()->OnConnectionChange(new_state);
4220}
4221
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004222void PeerConnection::OnIceGatheringChange(
4223 PeerConnectionInterface::IceGatheringState new_state) {
4224 if (IsClosed()) {
4225 return;
4226 }
4227 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004228 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004229}
4230
jbauch81bf7b02017-03-25 08:31:12 -07004231void PeerConnection::OnIceCandidate(
4232 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004233 if (IsClosed()) {
4234 return;
4235 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004236 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004237 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004238}
4239
Eldar Relloda13ea22019-06-01 12:23:43 +03004240void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4241 const std::string& url,
4242 int error_code,
4243 const std::string& error_text) {
4244 if (IsClosed()) {
4245 return;
4246 }
4247 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4248}
4249
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004250void PeerConnection::OnIceCandidatesRemoved(
4251 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004252 if (IsClosed()) {
4253 return;
4254 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004255 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004256}
4257
Alex Drake00c7ecf2019-08-06 10:54:47 -07004258void PeerConnection::OnSelectedCandidatePairChanged(
4259 const cricket::CandidatePairChangeEvent& event) {
4260 if (IsClosed()) {
4261 return;
4262 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004263
Alex Drake00c7ecf2019-08-06 10:54:47 -07004264 Observer()->OnIceSelectedCandidatePairChanged(event);
4265}
4266
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004267void PeerConnection::ChangeSignalingState(
4268 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004269 if (signaling_state_ == signaling_state) {
4270 return;
4271 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004272 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4273 << GetSignalingStateString(signaling_state_)
4274 << " New state: "
4275 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004276 signaling_state_ = signaling_state;
4277 if (signaling_state == kClosed) {
4278 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004279 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004280 standardized_ice_connection_state_ =
4281 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004282 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4283 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004284 if (ice_gathering_state_ != kIceGatheringComplete) {
4285 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004286 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004287 }
4288 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004289 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004290}
4291
deadbeefeb459812015-12-15 19:24:43 -08004292void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4293 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004294 if (IsClosed()) {
4295 return;
4296 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004297 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004298 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004299}
4300
deadbeefeb459812015-12-15 19:24:43 -08004301void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4302 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004303 if (IsClosed()) {
4304 return;
4305 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004306 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004307 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004308}
4309
4310void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4311 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004312 if (IsClosed()) {
4313 return;
4314 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004315 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004316 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004317}
4318
4319void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4320 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004321 if (IsClosed()) {
4322 return;
4323 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004324 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004325 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004326}
4327
Henrik Boström31638672017-11-23 17:48:32 +01004328void PeerConnection::PostSetSessionDescriptionSuccess(
4329 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004330 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4331 signaling_thread()->Post(RTC_FROM_HERE, this,
4332 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004333}
4334
deadbeefab9b2d12015-10-14 11:33:11 -07004335void PeerConnection::PostSetSessionDescriptionFailure(
4336 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004337 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004338 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004339 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4340 msg->error = std::move(error);
4341 signaling_thread()->Post(RTC_FROM_HERE, this,
4342 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004343}
4344
4345void PeerConnection::PostCreateSessionDescriptionFailure(
4346 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004347 RTCError error) {
4348 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004349 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4350 msg->error = std::move(error);
4351 signaling_thread()->Post(RTC_FROM_HERE, this,
4352 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004353}
4354
zhihuang1c378ed2017-08-17 14:10:50 -07004355void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004356 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004357 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004358 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004359
Steve Antondcc3c022017-12-22 16:02:54 -08004360 if (IsUnifiedPlan()) {
4361 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4362 } else {
4363 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4364 }
4365
Steve Antonfa2260d2017-12-28 16:38:23 -08004366 // Intentionally unset the data channel type for RTP data channel with the
4367 // second condition. Otherwise the RTP data channels would be successfully
4368 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4369 // when building with chromium. We want to leave RTP data channels broken, so
4370 // people won't try to use them.
4371 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4372 session_options->data_channel_type = data_channel_type();
4373 }
4374
Steve Antondcc3c022017-12-22 16:02:54 -08004375 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004376 bool ice_restart = offer_answer_options.ice_restart ||
4377 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004378 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004379 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004380 options.transport_options.enable_ice_renomination =
4381 configuration_.enable_ice_renomination;
4382 }
4383
4384 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004385 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004386 session_options->pooled_ice_credentials =
4387 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4388 RTC_FROM_HERE,
4389 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4390 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004391 session_options->offer_extmap_allow_mixed =
4392 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004393
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004394 if (configuration_.use_media_transport ||
4395 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004396 session_options->media_transport_settings =
4397 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4398 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004399
4400 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004401 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004402 for (auto& options : session_options->media_description_options) {
4403 options.transport_options.opaque_parameters =
4404 transport_controller_->GetTransportParameters(options.mid);
4405 }
4406 }
4407
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004408 // Allow fallback for using obsolete SCTP syntax.
4409 // Note that the default in |session_options| is true, while
4410 // the default in |options| is false.
4411 session_options->use_obsolete_sctp_sdp =
4412 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004413}
4414
4415void PeerConnection::GetOptionsForPlanBOffer(
4416 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4417 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004418 // Figure out transceiver directional preferences.
4419 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4420 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4421
4422 // By default, generate sendrecv/recvonly m= sections.
4423 bool recv_audio = true;
4424 bool recv_video = true;
4425
4426 // By default, only offer a new m= section if we have media to send with it.
4427 bool offer_new_audio_description = send_audio;
4428 bool offer_new_video_description = send_video;
4429 bool offer_new_data_description = HasDataChannels();
4430
4431 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004432 if (offer_answer_options.offer_to_receive_audio !=
4433 RTCOfferAnswerOptions::kUndefined) {
4434 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004435 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004436 offer_new_audio_description ||
4437 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004438 }
Steve Antondcc3c022017-12-22 16:02:54 -08004439 if (offer_answer_options.offer_to_receive_video !=
4440 RTCOfferAnswerOptions::kUndefined) {
4441 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004442 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004443 offer_new_video_description ||
4444 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004445 }
4446
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004447 absl::optional<size_t> audio_index;
4448 absl::optional<size_t> video_index;
4449 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004450 // If a current description exists, generate m= sections in the same order,
4451 // using the first audio/video/data section that appears and rejecting
4452 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004453 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004454 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004455 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004456 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4457 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4458 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004459 }
4460
zhihuang1c378ed2017-08-17 14:10:50 -07004461 // Add audio/video/data m= sections to the end if needed.
4462 if (!audio_index && offer_new_audio_description) {
4463 session_options->media_description_options.push_back(
4464 cricket::MediaDescriptionOptions(
4465 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004466 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4467 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004468 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004469 }
zhihuang1c378ed2017-08-17 14:10:50 -07004470 if (!video_index && offer_new_video_description) {
4471 session_options->media_description_options.push_back(
4472 cricket::MediaDescriptionOptions(
4473 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004474 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4475 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004476 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004477 }
zhihuang1c378ed2017-08-17 14:10:50 -07004478 if (!data_index && offer_new_data_description) {
4479 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004480 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004481 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004482 }
4483
4484 cricket::MediaDescriptionOptions* audio_media_description_options =
4485 !audio_index ? nullptr
4486 : &session_options->media_description_options[*audio_index];
4487 cricket::MediaDescriptionOptions* video_media_description_options =
4488 !video_index ? nullptr
4489 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004490
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004491 AddPlanBRtpSenderOptions(GetSendersInternal(),
4492 audio_media_description_options,
4493 video_media_description_options,
4494 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004495}
4496
Steve Antondcc3c022017-12-22 16:02:54 -08004497static cricket::MediaDescriptionOptions
4498GetMediaDescriptionOptionsForTransceiver(
4499 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4500 transceiver,
4501 const std::string& mid) {
4502 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004503 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004504 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004505 media_description_options.codec_preferences =
4506 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004507 // This behavior is specified in JSEP. The gist is that:
4508 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4509 // sendrecv.
4510 // 2. If the MSID is included, then it must be included in any subsequent
4511 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004512 if (transceiver->stopped() ||
4513 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4514 !transceiver->internal()->has_ever_been_used_to_send())) {
4515 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004516 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004517
4518 cricket::SenderOptions sender_options;
4519 sender_options.track_id = transceiver->sender()->id();
4520 sender_options.stream_ids = transceiver->sender()->stream_ids();
4521
4522 // The following sets up RIDs and Simulcast.
4523 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004524 RtpParameters send_parameters =
4525 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004526 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4527 send_parameters.encodings.end(),
4528 [](const RtpEncodingParameters& encoding) {
4529 return !encoding.rid.empty();
4530 });
4531
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004532 std::vector<RidDescription> send_rids;
4533 SimulcastLayerList send_layers;
4534 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4535 if (encoding.rid.empty()) {
4536 continue;
4537 }
4538 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4539 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4540 }
4541
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004542 if (has_rids) {
4543 sender_options.rids = send_rids;
4544 }
4545
4546 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004547 // When RIDs are configured, we must set num_sim_layers to 0 to.
4548 // Otherwise, num_sim_layers must be 1 because either there is no
4549 // simulcast, or simulcast is acheived by munging the SDP.
4550 sender_options.num_sim_layers = has_rids ? 0 : 1;
4551 media_description_options.sender_options.push_back(sender_options);
4552
Steve Antondcc3c022017-12-22 16:02:54 -08004553 return media_description_options;
4554}
4555
Steve Anton5c72e712018-12-10 14:25:30 -08004556// Returns the ContentInfo at mline index |i|, or null if none exists.
4557static const ContentInfo* GetContentByIndex(
4558 const SessionDescriptionInterface* sdesc,
4559 size_t i) {
4560 if (!sdesc) {
4561 return nullptr;
4562 }
4563 const ContentInfos& contents = sdesc->description()->contents();
4564 return (i < contents.size() ? &contents[i] : nullptr);
4565}
4566
Steve Antondcc3c022017-12-22 16:02:54 -08004567void PeerConnection::GetOptionsForUnifiedPlanOffer(
4568 const RTCOfferAnswerOptions& offer_answer_options,
4569 cricket::MediaSessionOptions* session_options) {
4570 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4571 // Offers) and 5.2.2 (Subsequent Offers).
4572 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004573 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004574 const ContentInfos& local_contents =
4575 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004576 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004577 const ContentInfos& remote_contents =
4578 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004579 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004580 // The mline indices that can be recycled. New transceivers should reuse these
4581 // slots first.
4582 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004583 // First, go through each media section that exists in either the local or
4584 // remote description and generate a media section in this offer for the
4585 // associated transceiver. If a media section can be recycled, generate a
4586 // default, rejected media section here that can be later overwritten.
4587 for (size_t i = 0;
4588 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4589 // Either |local_content| or |remote_content| is non-null.
4590 const ContentInfo* local_content =
4591 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004592 const ContentInfo* current_local_content =
4593 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004594 const ContentInfo* remote_content =
4595 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004596 const ContentInfo* current_remote_content =
4597 GetContentByIndex(current_remote_description(), i);
4598 bool had_been_rejected =
4599 (current_local_content && current_local_content->rejected) ||
4600 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004601 const std::string& mid =
4602 (local_content ? local_content->name : remote_content->name);
4603 cricket::MediaType media_type =
4604 (local_content ? local_content->media_description()->type()
4605 : remote_content->media_description()->type());
4606 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4607 media_type == cricket::MEDIA_TYPE_VIDEO) {
4608 auto transceiver = GetAssociatedTransceiver(mid);
4609 RTC_CHECK(transceiver);
4610 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004611 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004612 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004613 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004614 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4615 RtpTransceiverDirection::kInactive,
4616 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004617 recycleable_mline_indices.push(i);
4618 } else {
4619 session_options->media_description_options.push_back(
4620 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4621 // CreateOffer shouldn't really cause any state changes in
4622 // PeerConnection, but we need a way to match new transceivers to new
4623 // media sections in SetLocalDescription and JSEP specifies this is done
4624 // by recording the index of the media section generated for the
4625 // transceiver in the offer.
4626 transceiver->internal()->set_mline_index(i);
4627 }
4628 } else {
4629 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004630 RTC_CHECK(GetDataMid());
4631 if (had_been_rejected || mid != *GetDataMid()) {
4632 session_options->media_description_options.push_back(
4633 GetMediaDescriptionOptionsForRejectedData(mid));
4634 } else {
4635 session_options->media_description_options.push_back(
4636 GetMediaDescriptionOptionsForActiveData(mid));
4637 }
Steve Antondcc3c022017-12-22 16:02:54 -08004638 }
4639 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004640
Steve Antondcc3c022017-12-22 16:02:54 -08004641 // Next, look for transceivers that are newly added (that is, are not stopped
4642 // and not associated). Reuse media sections marked as recyclable first,
4643 // otherwise append to the end of the offer. New media sections should be
4644 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004645 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004646 if (transceiver->mid() || transceiver->stopped()) {
4647 continue;
4648 }
4649 size_t mline_index;
4650 if (!recycleable_mline_indices.empty()) {
4651 mline_index = recycleable_mline_indices.front();
4652 recycleable_mline_indices.pop();
4653 session_options->media_description_options[mline_index] =
4654 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004655 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004656 } else {
4657 mline_index = session_options->media_description_options.size();
4658 session_options->media_description_options.push_back(
4659 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004660 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004661 }
4662 // See comment above for why CreateOffer changes the transceiver's state.
4663 transceiver->internal()->set_mline_index(mline_index);
4664 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004665 // Lastly, add a m-section if we have local data channels and an m section
4666 // does not already exist.
4667 if (!GetDataMid() && HasDataChannels()) {
4668 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004669 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004670 }
Steve Antondcc3c022017-12-22 16:02:54 -08004671}
4672
4673void PeerConnection::GetOptionsForAnswer(
4674 const RTCOfferAnswerOptions& offer_answer_options,
4675 cricket::MediaSessionOptions* session_options) {
4676 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4677
4678 if (IsUnifiedPlan()) {
4679 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4680 } else {
4681 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4682 }
4683
Steve Antonfa2260d2017-12-28 16:38:23 -08004684 // Intentionally unset the data channel type for RTP data channel. Otherwise
4685 // the RTP data channels would be successfully negotiated by default and the
4686 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4687 // We want to leave RTP data channels broken, so people won't try to use them.
4688 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4689 session_options->data_channel_type = data_channel_type();
4690 }
4691
Steve Antondcc3c022017-12-22 16:02:54 -08004692 // Apply ICE renomination flag.
4693 for (auto& options : session_options->media_description_options) {
4694 options.transport_options.enable_ice_renomination =
4695 configuration_.enable_ice_renomination;
4696 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004697
4698 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004699 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004700 session_options->pooled_ice_credentials =
4701 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4702 RTC_FROM_HERE,
4703 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4704 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004705
4706 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004707 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004708 for (auto& options : session_options->media_description_options) {
4709 options.transport_options.opaque_parameters =
4710 transport_controller_->GetTransportParameters(options.mid);
4711 }
4712 }
deadbeefab9b2d12015-10-14 11:33:11 -07004713}
4714
Steve Antondcc3c022017-12-22 16:02:54 -08004715void PeerConnection::GetOptionsForPlanBAnswer(
4716 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004717 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004718 // Figure out transceiver directional preferences.
4719 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4720 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4721
4722 // By default, generate sendrecv/recvonly m= sections. The direction is also
4723 // restricted by the direction in the offer.
4724 bool recv_audio = true;
4725 bool recv_video = true;
4726
4727 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004728 if (offer_answer_options.offer_to_receive_audio !=
4729 RTCOfferAnswerOptions::kUndefined) {
4730 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004731 }
Steve Antondcc3c022017-12-22 16:02:54 -08004732 if (offer_answer_options.offer_to_receive_video !=
4733 RTCOfferAnswerOptions::kUndefined) {
4734 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004735 }
4736
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004737 absl::optional<size_t> audio_index;
4738 absl::optional<size_t> video_index;
4739 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004740
4741 // Generate m= sections that match those in the offer.
4742 // Note that mediasession.cc will handle intersection our preferred
4743 // direction with the offered direction.
4744 GenerateMediaDescriptionOptions(
4745 remote_description(),
4746 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4747 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4748 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004749
4750 cricket::MediaDescriptionOptions* audio_media_description_options =
4751 !audio_index ? nullptr
4752 : &session_options->media_description_options[*audio_index];
4753 cricket::MediaDescriptionOptions* video_media_description_options =
4754 !video_index ? nullptr
4755 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004756
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004757 AddPlanBRtpSenderOptions(GetSendersInternal(),
4758 audio_media_description_options,
4759 video_media_description_options,
4760 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004761}
zhihuangaf388472016-11-02 16:49:48 -07004762
Steve Antondcc3c022017-12-22 16:02:54 -08004763void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4764 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4765 cricket::MediaSessionOptions* session_options) {
4766 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4767 // Answers) and 5.3.2 (Subsequent Answers).
4768 RTC_DCHECK(remote_description());
4769 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4770 for (const ContentInfo& content :
4771 remote_description()->description()->contents()) {
4772 cricket::MediaType media_type = content.media_description()->type();
4773 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4774 media_type == cricket::MEDIA_TYPE_VIDEO) {
4775 auto transceiver = GetAssociatedTransceiver(content.name);
4776 RTC_CHECK(transceiver);
4777 session_options->media_description_options.push_back(
4778 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4779 } else {
4780 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004781 // Reject all data sections if data channels are disabled.
4782 // Reject a data section if it has already been rejected.
4783 // Reject all data sections except for the first one.
4784 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4785 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004786 session_options->media_description_options.push_back(
4787 GetMediaDescriptionOptionsForRejectedData(content.name));
4788 } else {
4789 session_options->media_description_options.push_back(
4790 GetMediaDescriptionOptionsForActiveData(content.name));
4791 }
Steve Antondcc3c022017-12-22 16:02:54 -08004792 }
4793 }
htaa2a49d92016-03-04 02:51:39 -08004794}
4795
zhihuang1c378ed2017-08-17 14:10:50 -07004796void PeerConnection::GenerateMediaDescriptionOptions(
4797 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004798 RtpTransceiverDirection audio_direction,
4799 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004800 absl::optional<size_t>* audio_index,
4801 absl::optional<size_t>* video_index,
4802 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004803 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004804 for (const cricket::ContentInfo& content :
4805 session_desc->description()->contents()) {
4806 if (IsAudioContent(&content)) {
4807 // If we already have an audio m= section, reject this extra one.
4808 if (*audio_index) {
4809 session_options->media_description_options.push_back(
4810 cricket::MediaDescriptionOptions(
4811 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004812 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004813 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004814 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004815 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004816 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4817 content.name, audio_direction,
4818 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004819 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004820 }
4821 } else if (IsVideoContent(&content)) {
4822 // If we already have an video m= section, reject this extra one.
4823 if (*video_index) {
4824 session_options->media_description_options.push_back(
4825 cricket::MediaDescriptionOptions(
4826 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004827 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004828 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004829 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004830 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004831 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4832 content.name, video_direction,
4833 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004834 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004835 }
4836 } else {
4837 RTC_DCHECK(IsDataContent(&content));
4838 // If we already have an data m= section, reject this extra one.
4839 if (*data_index) {
4840 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004841 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004842 } else {
4843 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004844 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004845 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004846 }
4847 }
htaa2a49d92016-03-04 02:51:39 -08004848 }
deadbeefab9b2d12015-10-14 11:33:11 -07004849}
4850
Steve Antonfa2260d2017-12-28 16:38:23 -08004851cricket::MediaDescriptionOptions
4852PeerConnection::GetMediaDescriptionOptionsForActiveData(
4853 const std::string& mid) const {
4854 // Direction for data sections is meaningless, but legacy endpoints might
4855 // expect sendrecv.
4856 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4857 RtpTransceiverDirection::kSendRecv,
4858 /*stopped=*/false);
4859 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4860 return options;
4861}
4862
4863cricket::MediaDescriptionOptions
4864PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4865 const std::string& mid) const {
4866 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4867 RtpTransceiverDirection::kInactive,
4868 /*stopped=*/true);
4869 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4870 return options;
4871}
4872
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004873absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004874 switch (data_channel_type_) {
4875 case cricket::DCT_RTP:
4876 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004877 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004878 }
4879 return rtp_data_channel_->content_name();
4880 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004881 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004882 case cricket::DCT_MEDIA_TRANSPORT:
4883 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004884 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004885 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004886 }
4887}
4888
Steve Anton4171afb2017-11-20 10:20:22 -08004889void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4890 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4891 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004892 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004893}
4894
Steve Anton4171afb2017-11-20 10:20:22 -08004895void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004896 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004897 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004898 cricket::MediaType media_type,
4899 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004900 RTC_DCHECK(!IsUnifiedPlan());
4901
Steve Anton4171afb2017-11-20 10:20:22 -08004902 std::vector<RtpSenderInfo>* current_senders =
4903 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004904
Steve Anton4171afb2017-11-20 10:20:22 -08004905 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004906 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004907 for (auto sender_it = current_senders->begin();
4908 sender_it != current_senders->end();
4909 /* incremented manually */) {
4910 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004911 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004912 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004913 std::string params_stream_id;
4914 if (params) {
4915 params_stream_id =
4916 (!params->first_stream_id().empty() ? params->first_stream_id()
4917 : kDefaultStreamId);
4918 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004919 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004920 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004921 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004922 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004923 sender_exists) {
4924 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004925 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004926 OnRemoteSenderRemoved(info, media_type);
4927 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004928 }
4929 }
4930
Steve Anton4171afb2017-11-20 10:20:22 -08004931 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004932 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004933 if (!params.has_ssrcs()) {
4934 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4935 // sender, this means it is coming from a Unified Plan endpoint,so we just
4936 // create a default.
4937 default_sender_needed = true;
4938 break;
4939 }
4940
Seth Hampson845e8782018-03-02 11:34:10 -08004941 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004942 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004943 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4944 // not supported in Plan B, we just take the first here and create the
4945 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004946 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004947 (!params.first_stream_id().empty() ? params.first_stream_id()
4948 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004949 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004950 uint32_t ssrc = params.first_ssrc();
4951
4952 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004953 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004954 if (!stream) {
4955 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004956 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004957 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004958 remote_streams_->AddStream(stream);
4959 new_streams->AddStream(stream);
4960 }
4961
Steve Anton4171afb2017-11-20 10:20:22 -08004962 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004963 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004964 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004965 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004966 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004967 }
4968 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004969
Steve Anton4171afb2017-11-20 10:20:22 -08004970 // Add default sender if necessary.
4971 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004972 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004973 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004974 if (!default_stream) {
4975 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004976 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004977 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004978 remote_streams_->AddStream(default_stream);
4979 new_streams->AddStream(default_stream);
4980 }
Steve Anton4171afb2017-11-20 10:20:22 -08004981 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4982 ? kDefaultAudioSenderId
4983 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004984 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004985 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004986 if (!default_sender_info) {
4987 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004988 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004989 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004990 }
4991 }
deadbeefab9b2d12015-10-14 11:33:11 -07004992}
4993
Steve Anton4171afb2017-11-20 10:20:22 -08004994void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4995 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004996 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4997 << " receiver for track_id=" << sender_info.sender_id
4998 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004999
Steve Anton3d954a62018-04-02 11:27:23 -07005000 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005001 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005002 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005003 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005004 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005005 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005006 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005007 }
5008}
5009
Steve Anton4171afb2017-11-20 10:20:22 -08005010void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5011 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005012 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5013 << " receiver for track_id=" << sender_info.sender_id
5014 << " and stream_id=" << sender_info.stream_id;
5015
Seth Hampson845e8782018-03-02 11:34:10 -08005016 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005017
Henrik Boström933d8b02017-10-10 10:05:16 -07005018 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005019 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005020 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5021 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005022 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005023 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005024 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005025 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005026 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005027 }
5028 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005029 // Stopping or destroying a VideoRtpReceiver will end the
5030 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005031 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005032 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005033 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005034 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005035 // There's no guarantee the track is still available, e.g. the track may
5036 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005037 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005038 }
5039 } else {
nisseede5da42017-01-12 05:15:36 -08005040 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005041 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005042 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005043 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005044 }
deadbeefab9b2d12015-10-14 11:33:11 -07005045}
5046
5047void PeerConnection::UpdateEndedRemoteMediaStreams() {
5048 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5049 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5050 MediaStreamInterface* stream = remote_streams_->at(i);
5051 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5052 streams_to_remove.push_back(stream);
5053 }
5054 }
5055
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005056 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005057 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005058 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005059 }
5060}
5061
Steve Anton4171afb2017-11-20 10:20:22 -08005062void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005063 const std::vector<cricket::StreamParams>& streams,
5064 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005065 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005066
Seth Hampson845e8782018-03-02 11:34:10 -08005067 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005068 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005069 for (auto sender_it = current_senders->begin();
5070 sender_it != current_senders->end();
5071 /* incremented manually */) {
5072 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005073 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005074 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5075 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005076 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005077 OnLocalSenderRemoved(info, media_type);
5078 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005079 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005080 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005081 }
5082 }
5083
Steve Anton4171afb2017-11-20 10:20:22 -08005084 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005085 for (const cricket::StreamParams& params : streams) {
5086 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005087 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005088 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005089 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005090 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005091 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005092 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005093 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005094 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005095 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005096 }
5097 }
5098}
5099
Steve Anton4171afb2017-11-20 10:20:22 -08005100void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5101 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005102 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005103 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005104 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005105 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5106 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005107 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005108 return;
5109 }
5110
deadbeeffac06552015-11-25 11:26:01 -08005111 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005112 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005113 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005114 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005115 }
deadbeeffac06552015-11-25 11:26:01 -08005116
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005117 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005118 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005119}
5120
Steve Anton4171afb2017-11-20 10:20:22 -08005121void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5122 cricket::MediaType media_type) {
5123 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005124 if (!sender) {
5125 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005126 // SessionDescriptions has been renegotiated.
5127 return;
5128 }
deadbeeffac06552015-11-25 11:26:01 -08005129
5130 // A sender has been removed from the SessionDescription but it's still
5131 // associated with the PeerConnection. This only occurs if the SDP doesn't
5132 // match with the calls to CreateSender, AddStream and RemoveStream.
5133 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005134 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005135 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005136 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005137 }
deadbeeffac06552015-11-25 11:26:01 -08005138
Steve Anton4171afb2017-11-20 10:20:22 -08005139 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005140}
5141
5142void PeerConnection::UpdateLocalRtpDataChannels(
5143 const cricket::StreamParamsVec& streams) {
5144 std::vector<std::string> existing_channels;
5145
5146 // Find new and active data channels.
5147 for (const cricket::StreamParams& params : streams) {
5148 // |it->sync_label| is actually the data channel label. The reason is that
5149 // we use the same naming of data channels as we do for
5150 // MediaStreams and Tracks.
5151 // For MediaStreams, the sync_label is the MediaStream label and the
5152 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005153 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005154 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005155 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005156 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005157 continue;
5158 }
5159 // Set the SSRC the data channel should use for sending.
5160 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5161 existing_channels.push_back(data_channel_it->first);
5162 }
5163
5164 UpdateClosingRtpDataChannels(existing_channels, true);
5165}
5166
5167void PeerConnection::UpdateRemoteRtpDataChannels(
5168 const cricket::StreamParamsVec& streams) {
5169 std::vector<std::string> existing_channels;
5170
5171 // Find new and active data channels.
5172 for (const cricket::StreamParams& params : streams) {
5173 // The data channel label is either the mslabel or the SSRC if the mslabel
5174 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005175 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005176 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005177 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005178 auto data_channel_it = rtp_data_channels_.find(label);
5179 if (data_channel_it == rtp_data_channels_.end()) {
5180 // This is a new data channel.
5181 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5182 } else {
5183 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5184 }
5185 existing_channels.push_back(label);
5186 }
5187
5188 UpdateClosingRtpDataChannels(existing_channels, false);
5189}
5190
5191void PeerConnection::UpdateClosingRtpDataChannels(
5192 const std::vector<std::string>& active_channels,
5193 bool is_local_update) {
5194 auto it = rtp_data_channels_.begin();
5195 while (it != rtp_data_channels_.end()) {
5196 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005197 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005198 ++it;
5199 continue;
5200 }
5201
5202 if (is_local_update) {
5203 data_channel->SetSendSsrc(0);
5204 } else {
5205 data_channel->RemotePeerRequestClose();
5206 }
5207
5208 if (data_channel->state() == DataChannel::kClosed) {
5209 rtp_data_channels_.erase(it);
5210 it = rtp_data_channels_.begin();
5211 } else {
5212 ++it;
5213 }
5214 }
5215}
5216
5217void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5218 uint32_t remote_ssrc) {
5219 rtc::scoped_refptr<DataChannel> channel(
5220 InternalCreateDataChannel(label, nullptr));
5221 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005222 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005223 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005224 return;
5225 }
5226 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005227 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5228 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005229 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005230}
5231
5232rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5233 const std::string& label,
5234 const InternalDataChannelInit* config) {
5235 if (IsClosed()) {
5236 return nullptr;
5237 }
Steve Anton75737c02017-11-06 10:37:17 -08005238 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005239 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005240 << "InternalCreateDataChannel: Data is not supported in this call.";
5241 return nullptr;
5242 }
5243 InternalDataChannelInit new_config =
5244 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005245 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005246 if (new_config.id < 0) {
5247 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005248 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005249 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005250 RTC_LOG(LS_ERROR)
5251 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005252 return nullptr;
5253 }
5254 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005255 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005256 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005257 return nullptr;
5258 }
5259 }
5260
Steve Anton75737c02017-11-06 10:37:17 -08005261 rtc::scoped_refptr<DataChannel> channel(
5262 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005263 if (!channel) {
5264 sid_allocator_.ReleaseSid(new_config.id);
5265 return nullptr;
5266 }
5267
5268 if (channel->data_channel_type() == cricket::DCT_RTP) {
5269 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005270 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5271 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005272 return nullptr;
5273 }
5274 rtp_data_channels_[channel->label()] = channel;
5275 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005276 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005277 sctp_data_channels_.push_back(channel);
5278 channel->SignalClosed.connect(this,
5279 &PeerConnection::OnSctpDataChannelClosed);
5280 }
5281
Steve Anton2d8609c2018-01-23 16:38:46 -08005282 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005283 return channel;
5284}
5285
5286bool PeerConnection::HasDataChannels() const {
5287 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5288}
5289
5290void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005291 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005292 for (const auto& channel : sctp_data_channels_) {
5293 if (channel->id() < 0) {
5294 int sid;
5295 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005296 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5297 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005298 continue;
5299 }
5300 channel->SetSctpSid(sid);
5301 }
5302 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005303 // Since closing modifies the list of channels, we have to do the actual
5304 // closing outside the loop.
5305 for (const auto& channel : channels_to_close) {
5306 channel->CloseAbruptly();
5307 }
deadbeefab9b2d12015-10-14 11:33:11 -07005308}
5309
5310void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005311 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005312 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5313 ++it) {
5314 if (it->get() == channel) {
5315 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005316 // After the closing procedure is done, it's safe to use this ID for
5317 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005318 sid_allocator_.ReleaseSid(channel->id());
5319 }
deadbeefbd292462015-12-14 18:15:29 -08005320 // Since this method is triggered by a signal from the DataChannel,
5321 // we can't free it directly here; we need to free it asynchronously.
5322 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005323 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005324 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5325 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005326 return;
5327 }
5328 }
5329}
5330
deadbeefab9b2d12015-10-14 11:33:11 -07005331void PeerConnection::OnDataChannelDestroyed() {
5332 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5333 // DataChannel may callback to us and try to modify the list.
5334 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5335 temp_rtp_dcs.swap(rtp_data_channels_);
5336 for (const auto& kv : temp_rtp_dcs) {
5337 kv.second->OnTransportChannelDestroyed();
5338 }
5339
5340 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5341 temp_sctp_dcs.swap(sctp_data_channels_);
5342 for (const auto& channel : temp_sctp_dcs) {
5343 channel->OnTransportChannelDestroyed();
5344 }
5345}
5346
5347void PeerConnection::OnDataChannelOpenMessage(
5348 const std::string& label,
5349 const InternalDataChannelInit& config) {
5350 rtc::scoped_refptr<DataChannel> channel(
5351 InternalCreateDataChannel(label, &config));
5352 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005353 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005354 return;
5355 }
5356
deadbeefa601f5c2016-06-06 14:27:39 -07005357 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5358 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005359 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005360 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005361}
5362
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005363bool PeerConnection::HandleOpenMessage_s(
5364 const cricket::ReceiveDataParams& params,
5365 const rtc::CopyOnWriteBuffer& buffer) {
5366 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5367 // Received OPEN message; parse and signal that a new data channel should
5368 // be created.
5369 std::string label;
5370 InternalDataChannelInit config;
5371 config.id = params.ssrc;
5372 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5373 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5374 << params.ssrc;
5375 return true;
5376 }
5377 config.open_handshake_role = InternalDataChannelInit::kAcker;
5378 OnDataChannelOpenMessage(label, config);
5379 return true;
5380 }
5381 return false;
5382}
5383
Steve Anton4171afb2017-11-20 10:20:22 -08005384rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5385PeerConnection::GetAudioTransceiver() const {
5386 // This method only works with Plan B SDP, where there is a single
5387 // audio/video transceiver.
5388 RTC_DCHECK(!IsUnifiedPlan());
5389 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005390 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005391 return transceiver;
5392 }
5393 }
5394 RTC_NOTREACHED();
5395 return nullptr;
5396}
5397
5398rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5399PeerConnection::GetVideoTransceiver() const {
5400 // This method only works with Plan B SDP, where there is a single
5401 // audio/video transceiver.
5402 RTC_DCHECK(!IsUnifiedPlan());
5403 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005404 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005405 return transceiver;
5406 }
5407 }
5408 RTC_NOTREACHED();
5409 return nullptr;
5410}
5411
5412// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5413// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005414bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005415 switch (type) {
5416 case cricket::MEDIA_TYPE_AUDIO:
5417 return !GetAudioTransceiver()->internal()->senders().empty();
5418 case cricket::MEDIA_TYPE_VIDEO:
5419 return !GetVideoTransceiver()->internal()->senders().empty();
5420 case cricket::MEDIA_TYPE_DATA:
5421 return false;
5422 }
5423 RTC_NOTREACHED();
5424 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005425}
5426
Steve Anton4171afb2017-11-20 10:20:22 -08005427rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5428PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005429 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005430 for (auto sender : transceiver->internal()->senders()) {
5431 if (sender->track() == track) {
5432 return sender;
5433 }
5434 }
5435 }
5436 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005437}
5438
Steve Anton4171afb2017-11-20 10:20:22 -08005439rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5440PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005441 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005442 for (auto sender : transceiver->internal()->senders()) {
5443 if (sender->id() == sender_id) {
5444 return sender;
5445 }
5446 }
5447 }
5448 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005449}
5450
Steve Anton4171afb2017-11-20 10:20:22 -08005451rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5452PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005453 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005454 for (auto receiver : transceiver->internal()->receivers()) {
5455 if (receiver->id() == receiver_id) {
5456 return receiver;
5457 }
5458 }
5459 }
5460 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005461}
5462
Steve Anton4171afb2017-11-20 10:20:22 -08005463std::vector<PeerConnection::RtpSenderInfo>*
5464PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5465 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5466 media_type == cricket::MEDIA_TYPE_VIDEO);
5467 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5468 ? &remote_audio_sender_infos_
5469 : &remote_video_sender_infos_;
5470}
5471
5472std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005473 cricket::MediaType media_type) {
5474 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5475 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005476 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5477 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005478}
5479
Steve Anton4171afb2017-11-20 10:20:22 -08005480const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5481 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005482 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005483 const std::string sender_id) const {
5484 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005485 if (sender_info.stream_id == stream_id &&
5486 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005487 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005488 }
5489 }
5490 return nullptr;
5491}
5492
5493DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5494 for (const auto& channel : sctp_data_channels_) {
5495 if (channel->id() == sid) {
5496 return channel;
5497 }
5498 }
5499 return nullptr;
5500}
5501
Karl Wibergfb3be392019-03-22 14:13:22 +01005502PeerConnection::InitializePortAllocatorResult
5503PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005504 const cricket::ServerAddresses& stun_servers,
5505 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005506 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005507 RTC_DCHECK_RUN_ON(network_thread());
5508
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005509 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005510 // To handle both internal and externally created port allocator, we will
5511 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005512 int port_allocator_flags = port_allocator_->flags();
5513 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5514 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5515 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005516 // If the disable-IPv6 flag was specified, we'll not override it
5517 // by experiment.
5518 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005519 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005520 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5521 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005522 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005523 }
5524
zhihuangb09b3f92017-03-07 14:40:51 -08005525 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005526 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005527 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005528 }
5529
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005530 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005531 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005532 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005533 }
5534
honghaiz60347052016-05-31 18:29:12 -07005535 if (configuration.candidate_network_policy ==
5536 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005537 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005538 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005539 }
5540
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005541 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005542 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005543 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5544 }
5545
Karl Wibergfb3be392019-03-22 14:13:22 +01005546 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005547 // No step delay is used while allocating ports.
5548 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005549 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005550 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005551 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005552
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005553 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005554 for (auto& turn_server : turn_servers_copy) {
5555 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005556 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005557 // Call this last since it may create pooled allocator sessions using the
5558 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005559 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005560 stun_servers, std::move(turn_servers_copy),
5561 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5562 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005563 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005564
5565 InitializePortAllocatorResult res;
5566 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5567 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005568}
5569
deadbeef91dd5672016-05-18 16:55:30 -07005570bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005571 const cricket::ServerAddresses& stun_servers,
5572 const std::vector<cricket::RelayServerConfig>& turn_servers,
5573 IceTransportsType type,
5574 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005575 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005576 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005577 absl::optional<int> stun_candidate_keepalive_interval,
5578 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005579 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005580 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005581 // According to JSEP, after setLocalDescription, changing the candidate pool
5582 // size is not allowed, and changing the set of ICE servers will not result
5583 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005584 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005585 port_allocator_->FreezeCandidatePool();
5586 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005587 // Add the custom tls turn servers if they exist.
5588 auto turn_servers_copy = turn_servers;
5589 for (auto& turn_server : turn_servers_copy) {
5590 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5591 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005592 // Call this last since it may create pooled allocator sessions using the
5593 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005594 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005595 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5596 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005597}
5598
Steve Antonba818672017-11-06 10:21:57 -08005599cricket::ChannelManager* PeerConnection::channel_manager() const {
5600 return factory_->channel_manager();
5601}
5602
Elad Alon99c3fe52017-10-13 16:29:40 +02005603bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005604 std::unique_ptr<RtcEventLogOutput> output,
5605 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005606 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005607 if (!event_log_) {
5608 return false;
5609 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005610 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005611}
5612
5613void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005614 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005615 if (event_log_) {
5616 event_log_->StopLogging();
5617 }
ivoc14d5dbe2016-07-04 07:06:55 -07005618}
nisseeaabdf62017-05-05 02:23:02 -07005619
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005620cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005621 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005622 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005623 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005624 if (channel && channel->content_name() == content_name) {
5625 return channel;
5626 }
Steve Anton75737c02017-11-06 10:37:17 -08005627 }
5628 if (rtp_data_channel() &&
5629 rtp_data_channel()->content_name() == content_name) {
5630 return rtp_data_channel();
5631 }
5632 return nullptr;
5633}
5634
5635bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005636 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005637 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005638 RTC_LOG(LS_INFO)
5639 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005640 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005641 return false;
5642 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005643 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005644 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005645 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005646 return false;
5647 }
5648
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005649 absl::optional<rtc::SSLRole> dtls_role;
5650 if (sctp_mid_) {
5651 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5652 } else if (is_caller_) {
5653 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5654 }
Zhi Huange830e682018-03-30 10:48:35 -07005655 if (dtls_role) {
5656 *role = *dtls_role;
5657 return true;
5658 }
5659 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005660}
5661
5662bool PeerConnection::GetSslRole(const std::string& content_name,
5663 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005664 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005665 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005666 RTC_LOG(LS_INFO)
5667 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005668 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005669 return false;
5670 }
5671
Zhi Huange830e682018-03-30 10:48:35 -07005672 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5673 if (dtls_role) {
5674 *role = *dtls_role;
5675 return true;
5676 }
5677 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005678}
5679
Steve Antonf8470812017-12-04 10:46:21 -08005680void PeerConnection::SetSessionError(SessionError error,
5681 const std::string& error_desc) {
5682 RTC_DCHECK_RUN_ON(signaling_thread());
5683 if (error != session_error_) {
5684 session_error_ = error;
5685 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005686 }
5687}
5688
Zhi Huange830e682018-03-30 10:48:35 -07005689RTCError PeerConnection::UpdateSessionState(
5690 SdpType type,
5691 cricket::ContentSource source,
5692 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005693 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005694
5695 // If there's already a pending error then no state transition should happen.
5696 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005697 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005698
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005699 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005700 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005701 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005702 }
5703
5704 // Update the signaling state according to the specified state machine (see
5705 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005706 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005707 ChangeSignalingState(source == cricket::CS_LOCAL
5708 ? PeerConnectionInterface::kHaveLocalOffer
5709 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005710 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005711 ChangeSignalingState(source == cricket::CS_LOCAL
5712 ? PeerConnectionInterface::kHaveLocalPrAnswer
5713 : PeerConnectionInterface::kHaveRemotePrAnswer);
5714 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005715 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005716 ChangeSignalingState(PeerConnectionInterface::kStable);
5717 }
5718
5719 // Update internal objects according to the session description's media
5720 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005721 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005722 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005723 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005724 }
5725
Steve Anton8a006912017-12-04 15:25:56 -08005726 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005727}
5728
Steve Anton8a006912017-12-04 15:25:56 -08005729RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005730 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005731 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005732 const SessionDescriptionInterface* sdesc =
5733 (source == cricket::CS_LOCAL ? local_description()
5734 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005735 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005736
5737 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005738 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005739 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005740 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005741 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005742 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005743 continue;
5744 }
5745 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005746 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005747 if (!content_desc) {
5748 continue;
5749 }
5750 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005751 bool success = (source == cricket::CS_LOCAL)
5752 ? channel->SetLocalContent(content_desc, type, &error)
5753 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005754 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005755 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005756 }
5757 }
5758
5759 // If using the RtpDataChannel, push down the new SDP section for it too.
5760 if (rtp_data_channel_) {
5761 const ContentInfo* data_content =
5762 cricket::GetFirstDataContent(sdesc->description());
5763 if (data_content && !data_content->rejected) {
5764 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005765 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005766 if (data_desc) {
5767 std::string error;
5768 bool success =
5769 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005770 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005771 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005772 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005773 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005774 }
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776 }
5777 }
Steve Antoned10bd92017-12-05 10:52:59 -08005778
Steve Anton75737c02017-11-06 10:37:17 -08005779 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5780 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005781 if (sctp_transport_ && local_description() && remote_description()) {
5782 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5783 local_description()->description());
5784 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5785 remote_description()->description());
5786 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005787 int max_message_size;
5788 // A remote max message size of zero means "any size supported".
5789 // We configure the connection with our own max message size.
5790 if (remote_sctp_description->max_message_size() == 0) {
5791 max_message_size = local_sctp_description->max_message_size();
5792 } else {
5793 max_message_size =
5794 std::min(local_sctp_description->max_message_size(),
5795 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005796 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005797 sctp_transport_->Start(local_sctp_description->port(),
5798 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005799 }
Steve Anton75737c02017-11-06 10:37:17 -08005800 }
Steve Antoned10bd92017-12-05 10:52:59 -08005801
Steve Anton8a006912017-12-04 15:25:56 -08005802 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005803}
5804
Steve Anton8a006912017-12-04 15:25:56 -08005805RTCError PeerConnection::PushdownTransportDescription(
5806 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005807 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005808 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005809
Zhi Huange830e682018-03-30 10:48:35 -07005810 if (source == cricket::CS_LOCAL) {
5811 const SessionDescriptionInterface* sdesc = local_description();
5812 RTC_DCHECK(sdesc);
5813 return transport_controller_->SetLocalDescription(type,
5814 sdesc->description());
5815 } else {
5816 const SessionDescriptionInterface* sdesc = remote_description();
5817 RTC_DCHECK(sdesc);
5818 return transport_controller_->SetRemoteDescription(type,
5819 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005820 }
Steve Anton75737c02017-11-06 10:37:17 -08005821}
5822
5823bool PeerConnection::GetTransportDescription(
5824 const SessionDescription* description,
5825 const std::string& content_name,
5826 cricket::TransportDescription* tdesc) {
5827 if (!description || !tdesc) {
5828 return false;
5829 }
5830 const TransportInfo* transport_info =
5831 description->GetTransportInfoByName(content_name);
5832 if (!transport_info) {
5833 return false;
5834 }
5835 *tdesc = transport_info->description;
5836 return true;
5837}
5838
Steve Anton75737c02017-11-06 10:37:17 -08005839cricket::IceConfig PeerConnection::ParseIceConfig(
5840 const PeerConnectionInterface::RTCConfiguration& config) const {
5841 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005842 switch (config.continual_gathering_policy) {
5843 case PeerConnectionInterface::GATHER_ONCE:
5844 gathering_policy = cricket::GATHER_ONCE;
5845 break;
5846 case PeerConnectionInterface::GATHER_CONTINUALLY:
5847 gathering_policy = cricket::GATHER_CONTINUALLY;
5848 break;
5849 default:
5850 RTC_NOTREACHED();
5851 gathering_policy = cricket::GATHER_ONCE;
5852 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005853
Steve Anton75737c02017-11-06 10:37:17 -08005854 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005855 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5856 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005857 ice_config.prioritize_most_likely_candidate_pairs =
5858 config.prioritize_most_likely_ice_candidate_pairs;
5859 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005860 RTCConfigurationToIceConfigOptionalInt(
5861 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005862 ice_config.continual_gathering_policy = gathering_policy;
5863 ice_config.presume_writable_when_fully_relayed =
5864 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005865 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5866 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005867 ice_config.ice_check_interval_strong_connectivity =
5868 config.ice_check_interval_strong_connectivity;
5869 ice_config.ice_check_interval_weak_connectivity =
5870 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005871 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005872 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5873 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005874 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005875 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005876 ice_config.regather_all_networks_interval_range =
5877 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005878 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005879 return ice_config;
5880}
5881
Steve Anton75737c02017-11-06 10:37:17 -08005882bool PeerConnection::SendData(const cricket::SendDataParams& params,
5883 const rtc::CopyOnWriteBuffer& payload,
5884 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005885 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005886 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5887 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5888 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005889 return false;
5890 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005891 if (media_transport_) {
5892 SendDataParams send_params;
5893 send_params.type = ToWebrtcDataMessageType(params.type);
5894 send_params.ordered = params.ordered;
5895 if (params.max_rtx_count >= 0) {
5896 send_params.max_rtx_count = params.max_rtx_count;
5897 } else if (params.max_rtx_ms >= 0) {
5898 send_params.max_rtx_ms = params.max_rtx_ms;
5899 }
5900 return media_transport_->SendData(params.sid, send_params, payload).ok();
5901 }
Steve Anton75737c02017-11-06 10:37:17 -08005902 return rtp_data_channel_
5903 ? rtp_data_channel_->SendData(params, payload, result)
5904 : network_thread()->Invoke<bool>(
5905 RTC_FROM_HERE,
5906 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005907 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005908}
5909
5910bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005911 RTC_DCHECK_RUN_ON(signaling_thread());
5912 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005913 // Don't log an error here, because DataChannels are expected to call
5914 // ConnectDataChannel in this state. It's the only way to initially tell
5915 // whether or not the underlying transport is ready.
5916 return false;
5917 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005918 if (media_transport_) {
5919 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5920 &DataChannel::OnChannelReady);
5921 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5922 &DataChannel::OnDataReceived);
5923 SignalMediaTransportChannelClosing_s.connect(
5924 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5925 SignalMediaTransportChannelClosed_s.connect(
5926 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5927 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005928 rtp_data_channel_->SignalReadyToSendData.connect(
5929 webrtc_data_channel, &DataChannel::OnChannelReady);
5930 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5931 &DataChannel::OnDataReceived);
5932 } else {
5933 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5934 &DataChannel::OnChannelReady);
5935 SignalSctpDataReceived.connect(webrtc_data_channel,
5936 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005937 SignalSctpClosingProcedureStartedRemotely.connect(
5938 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5939 SignalSctpClosingProcedureComplete.connect(
5940 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005941 }
5942 return true;
5943}
5944
5945void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005946 RTC_DCHECK_RUN_ON(signaling_thread());
5947 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005948 RTC_LOG(LS_ERROR)
5949 << "DisconnectDataChannel called when rtp_data_channel_ and "
5950 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005951 return;
5952 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005953 if (media_transport_) {
5954 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5955 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5956 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5957 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5958 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005959 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5960 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5961 } else {
5962 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5963 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005964 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5965 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005966 }
5967}
5968
5969void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005970 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005971 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005972 return;
5973 }
Steve Anton75737c02017-11-06 10:37:17 -08005974 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005975 RTC_LOG(LS_ERROR)
5976 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005977 return;
5978 }
5979 network_thread()->Invoke<void>(
5980 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005981 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005982}
5983
5984void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005985 if (media_transport_) {
5986 media_transport_->CloseChannel(sid);
5987 return;
5988 }
Steve Anton75737c02017-11-06 10:37:17 -08005989 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005990 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005991 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005992 return;
5993 }
5994 network_thread()->Invoke<void>(
5995 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005996 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005997}
5998
5999bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006000 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006001 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006002 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08006003 sctp_ready_to_send_data_;
6004}
6005
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006006void PeerConnection::OnDataReceived(int channel_id,
6007 DataMessageType type,
6008 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006009 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006010 cricket::ReceiveDataParams params;
6011 params.sid = channel_id;
6012 params.type = ToCricketDataMessageType(type);
6013 media_transport_invoker_->AsyncInvoke<void>(
6014 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6015 RTC_DCHECK_RUN_ON(signaling_thread());
6016 if (!HandleOpenMessage_s(params, buffer)) {
6017 SignalMediaTransportReceivedData_s(params, buffer);
6018 }
6019 });
6020}
6021
6022void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006023 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006024 media_transport_invoker_->AsyncInvoke<void>(
6025 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6026 RTC_DCHECK_RUN_ON(signaling_thread());
6027 SignalMediaTransportChannelClosing_s(channel_id);
6028 });
6029}
6030
6031void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006032 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006033 media_transport_invoker_->AsyncInvoke<void>(
6034 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6035 RTC_DCHECK_RUN_ON(signaling_thread());
6036 SignalMediaTransportChannelClosed_s(channel_id);
6037 });
6038}
6039
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006040absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006041 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006042 if (sctp_mid_ && transport_controller_) {
6043 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6044 if (dtls_transport) {
6045 return dtls_transport->transport_name();
6046 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006047 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006048 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006049 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006050}
6051
Qingsi Wang72a43a12018-02-20 16:03:18 -08006052cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6053 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006054 network_thread()->Invoke<void>(
6055 RTC_FROM_HERE,
6056 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6057 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006058 return candidate_states_list;
6059}
6060
Steve Anton5dfde182018-02-06 10:34:40 -08006061std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6062 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006063 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006064 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006065 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006066 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006067 if (channel) {
6068 transport_names_by_mid[channel->content_name()] =
6069 channel->transport_name();
6070 }
Steve Anton75737c02017-11-06 10:37:17 -08006071 }
Steve Anton5dfde182018-02-06 10:34:40 -08006072 if (rtp_data_channel_) {
6073 transport_names_by_mid[rtp_data_channel_->content_name()] =
6074 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006075 }
6076 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006077 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006078 RTC_DCHECK(transport_name);
6079 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006080 }
Steve Anton5dfde182018-02-06 10:34:40 -08006081 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006082}
6083
Steve Anton5dfde182018-02-06 10:34:40 -08006084std::map<std::string, cricket::TransportStats>
6085PeerConnection::GetTransportStatsByNames(
6086 const std::set<std::string>& transport_names) {
6087 if (!network_thread()->IsCurrent()) {
6088 return network_thread()
6089 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6090 RTC_FROM_HERE,
6091 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006092 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006093 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006094 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6095 for (const std::string& transport_name : transport_names) {
6096 cricket::TransportStats transport_stats;
6097 bool success =
6098 transport_controller_->GetStats(transport_name, &transport_stats);
6099 if (success) {
6100 transport_stats_by_name[transport_name] = std::move(transport_stats);
6101 } else {
6102 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6103 << transport_name;
6104 }
6105 }
6106 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006107}
6108
6109bool PeerConnection::GetLocalCertificate(
6110 const std::string& transport_name,
6111 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006112 if (!certificate) {
6113 return false;
6114 }
6115 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6116 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006117}
6118
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006119std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006120 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006121 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006122}
6123
6124cricket::DataChannelType PeerConnection::data_channel_type() const {
6125 return data_channel_type_;
6126}
6127
6128bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006129 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006130 return pending_ice_restarts_.find(content_name) !=
6131 pending_ice_restarts_.end();
6132}
6133
Steve Anton75737c02017-11-06 10:37:17 -08006134bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6135 return transport_controller_->NeedsIceRestart(content_name);
6136}
6137
6138void PeerConnection::OnCertificateReady(
6139 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6140 transport_controller_->SetLocalCertificate(certificate);
6141}
6142
6143void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006144 SetSessionError(SessionError::kTransport,
6145 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006146}
6147
Alex Loiko9289eda2018-11-23 16:18:59 +00006148void PeerConnection::OnTransportControllerConnectionState(
6149 cricket::IceConnectionState state) {
6150 switch (state) {
6151 case cricket::kIceConnectionConnecting:
6152 // If the current state is Connected or Completed, then there were
6153 // writable channels but now there are not, so the next state must
6154 // be Disconnected.
6155 // kIceConnectionConnecting is currently used as the default,
6156 // un-connected state by the TransportController, so its only use is
6157 // detecting disconnections.
6158 if (ice_connection_state_ ==
6159 PeerConnectionInterface::kIceConnectionConnected ||
6160 ice_connection_state_ ==
6161 PeerConnectionInterface::kIceConnectionCompleted) {
6162 SetIceConnectionState(
6163 PeerConnectionInterface::kIceConnectionDisconnected);
6164 }
6165 break;
6166 case cricket::kIceConnectionFailed:
6167 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6168 break;
6169 case cricket::kIceConnectionConnected:
6170 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6171 "all transports are writable.";
6172 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6173 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6174 break;
6175 case cricket::kIceConnectionCompleted:
6176 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6177 "all transports are complete.";
6178 if (ice_connection_state_ !=
6179 PeerConnectionInterface::kIceConnectionConnected) {
6180 // If jumping directly from "checking" to "connected",
6181 // signal "connected" first.
6182 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6183 }
6184 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6185 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6186 ReportTransportStats();
6187 break;
6188 default:
6189 RTC_NOTREACHED();
6190 }
6191}
6192
Steve Anton75737c02017-11-06 10:37:17 -08006193void PeerConnection::OnTransportControllerCandidatesGathered(
6194 const std::string& transport_name,
6195 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006196 int sdp_mline_index;
6197 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006198 RTC_LOG(LS_ERROR)
6199 << "OnTransportControllerCandidatesGathered: content name "
6200 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006201 return;
6202 }
6203
6204 for (cricket::Candidates::const_iterator citer = candidates.begin();
6205 citer != candidates.end(); ++citer) {
6206 // Use transport_name as the candidate media id.
6207 std::unique_ptr<JsepIceCandidate> candidate(
6208 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6209 if (local_description()) {
6210 mutable_local_description()->AddCandidate(candidate.get());
6211 }
6212 OnIceCandidate(std::move(candidate));
6213 }
6214}
6215
Eldar Relloda13ea22019-06-01 12:23:43 +03006216void PeerConnection::OnTransportControllerCandidateError(
6217 const cricket::IceCandidateErrorEvent& event) {
6218 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6219 event.error_text);
6220}
6221
Steve Anton75737c02017-11-06 10:37:17 -08006222void PeerConnection::OnTransportControllerCandidatesRemoved(
6223 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006224 // Sanity check.
6225 for (const cricket::Candidate& candidate : candidates) {
6226 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006227 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006228 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006229 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006230 return;
6231 }
6232 }
6233
6234 if (local_description()) {
6235 mutable_local_description()->RemoveCandidates(candidates);
6236 }
6237 OnIceCandidatesRemoved(candidates);
6238}
6239
Alex Drake00c7ecf2019-08-06 10:54:47 -07006240void PeerConnection::OnTransportControllerCandidateChanged(
6241 const cricket::CandidatePairChangeEvent& event) {
6242 OnSelectedCandidatePairChanged(event);
6243}
6244
Steve Anton75737c02017-11-06 10:37:17 -08006245void PeerConnection::OnTransportControllerDtlsHandshakeError(
6246 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006247 RTC_HISTOGRAM_ENUMERATION(
6248 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6249 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006250}
6251
Steve Antoned10bd92017-12-05 10:52:59 -08006252void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006253 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006254 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006255 if (channel && !channel->enabled()) {
6256 channel->Enable(true);
6257 }
Steve Anton75737c02017-11-06 10:37:17 -08006258 }
6259
Steve Anton4171afb2017-11-20 10:20:22 -08006260 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006261 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006262 }
Steve Anton75737c02017-11-06 10:37:17 -08006263}
6264
6265// Returns the media index for a local ice candidate given the content name.
6266bool PeerConnection::GetLocalCandidateMediaIndex(
6267 const std::string& content_name,
6268 int* sdp_mline_index) {
6269 if (!local_description() || !sdp_mline_index) {
6270 return false;
6271 }
6272
6273 bool content_found = false;
6274 const ContentInfos& contents = local_description()->description()->contents();
6275 for (size_t index = 0; index < contents.size(); ++index) {
6276 if (contents[index].name == content_name) {
6277 *sdp_mline_index = static_cast<int>(index);
6278 content_found = true;
6279 break;
6280 }
6281 }
6282 return content_found;
6283}
6284
6285bool PeerConnection::UseCandidatesInSessionDescription(
6286 const SessionDescriptionInterface* remote_desc) {
6287 if (!remote_desc) {
6288 return true;
6289 }
6290 bool ret = true;
6291
6292 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6293 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6294 for (size_t n = 0; n < candidates->count(); ++n) {
6295 const IceCandidateInterface* candidate = candidates->at(n);
6296 bool valid = false;
6297 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6298 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006299 RTC_LOG(LS_INFO)
6300 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006301 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006302 }
6303 continue;
6304 }
6305 ret = UseCandidate(candidate);
6306 if (!ret) {
6307 break;
6308 }
6309 }
6310 }
6311 return ret;
6312}
6313
6314bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006315 RTCErrorOr<const cricket::ContentInfo*> result =
6316 FindContentInfo(remote_description(), candidate);
6317 if (!result.ok()) {
6318 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6319 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006320 return false;
6321 }
Steve Anton75737c02017-11-06 10:37:17 -08006322 std::vector<cricket::Candidate> candidates;
6323 candidates.push_back(candidate->candidate());
6324 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006325 RTCError error = transport_controller_->AddRemoteCandidates(
6326 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006327 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006328 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006329 // Candidates successfully submitted for checking.
6330 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6331 ice_connection_state_ ==
6332 PeerConnectionInterface::kIceConnectionDisconnected) {
6333 // If state is New, then the session has just gotten its first remote ICE
6334 // candidates, so go to Checking.
6335 // If state is Disconnected, the session is re-using old candidates or
6336 // receiving additional ones, so go to Checking.
6337 // If state is Connected, stay Connected.
6338 // TODO(bemasc): If state is Connected, and the new candidates are for a
6339 // newly added transport, then the state actually _should_ move to
6340 // checking. Add a way to distinguish that case.
6341 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6342 }
6343 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006344 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006345 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006346 }
6347 return true;
6348}
6349
Guido Urdaneta41633172019-05-23 20:12:29 +02006350RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6351 const SessionDescriptionInterface* description,
6352 const IceCandidateInterface* candidate) {
6353 if (candidate->sdp_mline_index() >= 0) {
6354 size_t mediacontent_index =
6355 static_cast<size_t>(candidate->sdp_mline_index());
6356 size_t content_size = description->description()->contents().size();
6357 if (mediacontent_index < content_size) {
6358 return &description->description()->contents()[mediacontent_index];
6359 } else {
6360 return RTCError(RTCErrorType::INVALID_RANGE,
6361 "Media line index (" +
6362 rtc::ToString(candidate->sdp_mline_index()) +
6363 ") out of range (number of mlines: " +
6364 rtc::ToString(content_size) + ").");
6365 }
6366 } else if (!candidate->sdp_mid().empty()) {
6367 auto& contents = description->description()->contents();
6368 auto it = absl::c_find_if(
6369 contents, [candidate](const cricket::ContentInfo& content_info) {
6370 return content_info.mid() == candidate->sdp_mid();
6371 });
6372 if (it == contents.end()) {
6373 return RTCError(
6374 RTCErrorType::INVALID_PARAMETER,
6375 "Mid " + candidate->sdp_mid() +
6376 " specified but no media section with that mid found.");
6377 } else {
6378 return &*it;
6379 }
6380 }
6381
6382 return RTCError(RTCErrorType::INVALID_PARAMETER,
6383 "Neither sdp_mline_index nor sdp_mid specified.");
6384}
6385
Steve Anton75737c02017-11-06 10:37:17 -08006386void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006387 // Destroy video channel first since it may have a pointer to the
6388 // voice channel.
6389 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006390 if (!video_info || video_info->rejected) {
6391 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006392 }
6393
Steve Anton6fec8802017-12-04 10:37:29 -08006394 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6395 if (!audio_info || audio_info->rejected) {
6396 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006397 }
6398
6399 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6400 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006401 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006402 }
6403}
6404
Steve Antondcc3c022017-12-22 16:02:54 -08006405RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6406 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006407 const cricket::ContentGroup* bundle_group = nullptr;
6408 if (configuration_.bundle_policy ==
6409 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006410 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006411 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6413 "max-bundle configured but session description "
6414 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006415 }
6416 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006417 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006418}
6419
6420RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006421 // Creating the media channels. Transports should already have been created
6422 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006423 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006424 if (voice && !voice->rejected &&
6425 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006426 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006427 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006428 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6429 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006430 }
6431 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6432 }
6433
Steve Antondcc3c022017-12-22 16:02:54 -08006434 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006435 if (video && !video->rejected &&
6436 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006437 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006438 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006439 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6440 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006441 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006442 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006443 }
6444
Steve Antondcc3c022017-12-22 16:02:54 -08006445 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006446 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006447 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006448 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006449 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6450 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006451 }
6452 }
6453
Steve Anton8a006912017-12-04 15:25:56 -08006454 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006455}
6456
Steve Anton4171afb2017-11-20 10:20:22 -08006457// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006458cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006459 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006460 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006461 MediaTransportConfig media_transport_config =
6462 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006463
Steve Anton75737c02017-11-06 10:37:17 -08006464 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006465 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006466 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6467 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006468 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006469 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006470 }
Steve Anton75737c02017-11-06 10:37:17 -08006471 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6472 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006473 voice_channel->SignalSentPacket.connect(this,
6474 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006475 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006476
Steve Antoneda6ccd2017-12-04 10:21:55 -08006477 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006478}
6479
Steve Anton4171afb2017-11-20 10:20:22 -08006480// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006481cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006482 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006483 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006484 MediaTransportConfig media_transport_config =
6485 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006486
Steve Anton75737c02017-11-06 10:37:17 -08006487 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006488 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006489 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6490 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006491 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006492 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006493 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006494 }
Steve Anton75737c02017-11-06 10:37:17 -08006495 video_channel->SignalDtlsSrtpSetupFailure.connect(
6496 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006497 video_channel->SignalSentPacket.connect(this,
6498 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006499 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006500
Steve Antoneda6ccd2017-12-04 10:21:55 -08006501 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006502}
6503
Zhi Huange830e682018-03-30 10:48:35 -07006504bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006505 switch (data_channel_type_) {
6506 case cricket::DCT_MEDIA_TRANSPORT:
6507 if (network_thread()->Invoke<bool>(
6508 RTC_FROM_HERE,
6509 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6510 this, mid))) {
6511 for (const auto& channel : sctp_data_channels_) {
6512 channel->OnTransportChannelCreated();
6513 }
6514 return true;
6515 }
Steve Anton75737c02017-11-06 10:37:17 -08006516 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006517 case cricket::DCT_SCTP:
6518 if (!sctp_factory_) {
6519 RTC_LOG(LS_ERROR)
6520 << "Trying to create SCTP transport, but didn't compile with "
6521 "SCTP support (HAVE_SCTP)";
6522 return false;
6523 }
6524 if (!network_thread()->Invoke<bool>(
6525 RTC_FROM_HERE,
6526 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6527 return false;
6528 }
6529 for (const auto& channel : sctp_data_channels_) {
6530 channel->OnTransportChannelCreated();
6531 }
6532 return true;
6533 case cricket::DCT_RTP:
6534 default:
6535 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6536 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6537 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006538 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006539 if (!rtp_data_channel_) {
6540 return false;
6541 }
6542 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6543 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6544 rtp_data_channel_->SignalSentPacket.connect(
6545 this, &PeerConnection::OnSentPacket_w);
6546 rtp_data_channel_->SetRtpTransport(rtp_transport);
6547 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006548 }
6549
Steve Anton75737c02017-11-06 10:37:17 -08006550 return true;
6551}
6552
6553Call::Stats PeerConnection::GetCallStats() {
6554 if (!worker_thread()->IsCurrent()) {
6555 return worker_thread()->Invoke<Call::Stats>(
6556 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6557 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006558 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006559 if (call_) {
6560 return call_->GetStats();
6561 } else {
6562 return Call::Stats();
6563 }
6564}
6565
Zhi Huange830e682018-03-30 10:48:35 -07006566bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006567 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006568 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006569 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6570 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006571 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006572 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006573 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006574 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6575 sctp_factory_->CreateSctpTransport(dtls_transport);
6576 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006577 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006578 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006579 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006580 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006581 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006582 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6583 // another thread. Would be nice if there was a helper class similar to
6584 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6585 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006586 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006587 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006588 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006589 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006590 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006591 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6592 std::move(cricket_sctp_transport));
6593 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006594 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006595}
6596
6597void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006598 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006599 sctp_transport_->Clear();
6600 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006601 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006602 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006603}
6604
6605void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006606 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006607 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006608 // Note: Cannot use rtc::Bind here because it will grab a reference to
6609 // PeerConnection and potentially cause PeerConnection to live longer than
6610 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6611 // be destroyed before PeerConnection is destroyed, and at that point all
6612 // pending tasks will be cleared.
6613 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6614 OnSctpTransportReadyToSendData_s(true);
6615 });
6616}
6617
6618void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006619 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006620 sctp_ready_to_send_data_ = ready;
6621 SignalSctpReadyToSendData(ready);
6622}
6623
6624void PeerConnection::OnSctpTransportDataReceived_n(
6625 const cricket::ReceiveDataParams& params,
6626 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006627 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006628 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006629 // Note: Cannot use rtc::Bind here because it will grab a reference to
6630 // PeerConnection and potentially cause PeerConnection to live longer than
6631 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6632 // be destroyed before PeerConnection is destroyed, and at that point all
6633 // pending tasks will be cleared.
6634 sctp_invoker_->AsyncInvoke<void>(
6635 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6636 OnSctpTransportDataReceived_s(params, payload);
6637 });
6638}
6639
6640void PeerConnection::OnSctpTransportDataReceived_s(
6641 const cricket::ReceiveDataParams& params,
6642 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006643 RTC_DCHECK_RUN_ON(signaling_thread());
6644 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006645 SignalSctpDataReceived(params, payload);
6646 }
6647}
6648
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006649void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006650 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006651 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006652 sctp_invoker_->AsyncInvoke<void>(
6653 RTC_FROM_HERE, signaling_thread(),
6654 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006655 &SignalSctpClosingProcedureStartedRemotely, sid));
6656}
6657
6658void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006659 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006660 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006661 sctp_invoker_->AsyncInvoke<void>(
6662 RTC_FROM_HERE, signaling_thread(),
6663 rtc::Bind(&sigslot::signal1<int>::operator(),
6664 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006665}
6666
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006667bool PeerConnection::SetupMediaTransportForDataChannels_n(
6668 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006669 media_transport_ =
6670 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006671 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006672 RTC_LOG(LS_ERROR)
6673 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006674 return false;
6675 }
6676
6677 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6678 media_transport_->SetDataSink(this);
6679 media_transport_data_mid_ = mid;
6680 transport_controller_->SignalMediaTransportStateChanged.connect(
6681 this, &PeerConnection::OnMediaTransportStateChanged_n);
6682 // Check the initial state right away, in case transport is already writable.
6683 OnMediaTransportStateChanged_n();
6684 return true;
6685}
6686
6687void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6688 if (!media_transport_) {
6689 return;
6690 }
6691 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6692 media_transport_data_mid_.reset();
6693 media_transport_->SetDataSink(nullptr);
6694 media_transport_invoker_ = nullptr;
6695 media_transport_ = nullptr;
6696}
6697
6698void PeerConnection::OnMediaTransportStateChanged_n() {
6699 if (!media_transport_data_mid_ ||
6700 transport_controller_->GetMediaTransportState(
6701 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6702 return;
6703 }
6704 media_transport_invoker_->AsyncInvoke<void>(
6705 RTC_FROM_HERE, signaling_thread(), [this] {
6706 RTC_DCHECK_RUN_ON(signaling_thread());
6707 media_transport_ready_to_send_data_ = true;
6708 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6709 });
6710}
6711
Steve Anton75737c02017-11-06 10:37:17 -08006712// Returns false if bundle is enabled and rtcp_mux is disabled.
6713bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6714 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6715 if (!bundle_enabled)
6716 return true;
6717
6718 const cricket::ContentGroup* bundle_group =
6719 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6720 RTC_DCHECK(bundle_group != NULL);
6721
6722 const cricket::ContentInfos& contents = desc->contents();
6723 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6724 citer != contents.end(); ++citer) {
6725 const cricket::ContentInfo* content = (&*citer);
6726 RTC_DCHECK(content != NULL);
6727 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006728 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006729 if (!HasRtcpMuxEnabled(content))
6730 return false;
6731 }
6732 }
6733 // RTCP-MUX is enabled in all the contents.
6734 return true;
6735}
6736
6737bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006738 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006739}
6740
Steve Anton06817cd2018-12-18 15:55:30 -08006741static RTCError ValidateMids(const cricket::SessionDescription& description) {
6742 std::set<std::string> mids;
6743 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006744 if (content.name.empty()) {
6745 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6746 "A media section is missing a MID attribute.");
6747 }
Steve Anton06817cd2018-12-18 15:55:30 -08006748 if (!mids.insert(content.name).second) {
6749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6750 "Duplicate a=mid value '" + content.name + "'.");
6751 }
6752 }
6753 return RTCError::OK();
6754}
6755
Steve Anton8a006912017-12-04 15:25:56 -08006756RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006757 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006758 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006759 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006760 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006761 }
6762
6763 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006764 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006765 }
6766
Steve Anton3828c062017-12-06 10:34:51 -08006767 SdpType type = sdesc->GetType();
6768 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6769 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006770 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006771 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006772 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006773 }
6774
Steve Anton06817cd2018-12-18 15:55:30 -08006775 RTCError error = ValidateMids(*sdesc->description());
6776 if (!error.ok()) {
6777 return error;
6778 }
6779
Steve Anton75737c02017-11-06 10:37:17 -08006780 // Verify crypto settings.
6781 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006782 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6783 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006784 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006785 if (!crypto_error.ok()) {
6786 return crypto_error;
6787 }
Steve Anton75737c02017-11-06 10:37:17 -08006788 }
6789
6790 // Verify ice-ufrag and ice-pwd.
6791 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6793 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006794 }
6795
6796 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6798 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006799 }
6800
6801 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6802 // m-lines that do not rtcp-mux enabled.
6803
6804 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006805 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006806 // With an answer we want to compare the new answer session description with
6807 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006808 const cricket::SessionDescription* offer_desc =
6809 (source == cricket::CS_LOCAL) ? remote_description()->description()
6810 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006811 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6812 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6813 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006814 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6815 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006816 }
6817 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006818 // The re-offers should respect the order of m= sections in current
6819 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006820 // With a re-offer, either the current local or current remote descriptions
6821 // could be the most up to date, so we would like to check against both of
6822 // them if they exist. It could be the case that one of them has a 0 port
6823 // for a media section, but the other does not. This is important to check
6824 // against in the case that we are recycling an m= section.
6825 const cricket::SessionDescription* current_desc = nullptr;
6826 const cricket::SessionDescription* secondary_current_desc = nullptr;
6827 if (local_description()) {
6828 current_desc = local_description()->description();
6829 if (remote_description()) {
6830 secondary_current_desc = remote_description()->description();
6831 }
6832 } else if (remote_description()) {
6833 current_desc = remote_description()->description();
6834 }
Steve Anton75737c02017-11-06 10:37:17 -08006835 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006836 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6837 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006838 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6839 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006840 }
6841 }
6842
Steve Antonba42e992018-04-09 14:10:01 -07006843 if (IsUnifiedPlan()) {
6844 // Ensure that each audio and video media section has at most one
6845 // "StreamParams". This will return an error if receiving a session
6846 // description from a "Plan B" endpoint which adds multiple tracks of the
6847 // same type. With Unified Plan, there can only be at most one track per
6848 // media section.
6849 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006850 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006851 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6852 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6853 desc.streams().size() > 1u) {
6854 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6855 "Media section has more than one track specified "
6856 "with a=ssrc lines which is not supported with "
6857 "Unified Plan.");
6858 }
6859 }
6860 }
6861
Steve Anton8a006912017-12-04 15:25:56 -08006862 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006863}
6864
Steve Anton3828c062017-12-06 10:34:51 -08006865bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006866 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006867 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006868 return (state == PeerConnectionInterface::kStable) ||
6869 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006870 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006871 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006872 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6873 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6874 }
6875}
6876
Steve Anton3828c062017-12-06 10:34:51 -08006877bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006878 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006879 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006880 return (state == PeerConnectionInterface::kStable) ||
6881 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006882 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006883 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006884 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6885 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6886 }
6887}
6888
Steve Antonf8470812017-12-04 10:46:21 -08006889const char* PeerConnection::SessionErrorToString(SessionError error) const {
6890 switch (error) {
6891 case SessionError::kNone:
6892 return "ERROR_NONE";
6893 case SessionError::kContent:
6894 return "ERROR_CONTENT";
6895 case SessionError::kTransport:
6896 return "ERROR_TRANSPORT";
6897 }
6898 RTC_NOTREACHED();
6899 return "";
6900}
6901
Steve Anton75737c02017-11-06 10:37:17 -08006902std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006903 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006904 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6905 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006906 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006907}
6908
Steve Anton8e20f172018-03-06 10:55:04 -08006909void PeerConnection::ReportSdpFormatReceived(
6910 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006911 int num_audio_mlines = 0;
6912 int num_video_mlines = 0;
6913 int num_audio_tracks = 0;
6914 int num_video_tracks = 0;
6915 for (const ContentInfo& content : remote_offer.description()->contents()) {
6916 cricket::MediaType media_type = content.media_description()->type();
6917 int num_tracks = std::max(
6918 1, static_cast<int>(content.media_description()->streams().size()));
6919 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6920 num_audio_mlines += 1;
6921 num_audio_tracks += num_tracks;
6922 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6923 num_video_mlines += 1;
6924 num_video_tracks += num_tracks;
6925 }
6926 }
6927 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6928 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6929 format = kSdpFormatReceivedComplexUnifiedPlan;
6930 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6931 format = kSdpFormatReceivedComplexPlanB;
6932 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6933 format = kSdpFormatReceivedSimple;
6934 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006935 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6936 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006937}
6938
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006939void PeerConnection::ReportIceCandidateCollected(
6940 const cricket::Candidate& candidate) {
6941 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
6942 if (candidate.address().IsPrivateIP()) {
6943 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
6944 }
6945 if (candidate.address().IsUnresolvedIP()) {
6946 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
6947 }
6948 if (candidate.address().family() == AF_INET6) {
6949 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
6950 }
6951}
6952
6953void PeerConnection::ReportRemoteIceCandidateAdded(
6954 const cricket::Candidate& candidate) {
6955 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
6956 if (candidate.address().IsPrivateIP()) {
6957 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
6958 }
6959 if (candidate.address().IsUnresolvedIP()) {
6960 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
6961 }
6962 if (candidate.address().family() == AF_INET6) {
6963 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
6964 }
6965}
6966
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006967void PeerConnection::NoteUsageEvent(UsageEvent event) {
6968 RTC_DCHECK_RUN_ON(signaling_thread());
6969 usage_event_accumulator_ |= static_cast<int>(event);
6970}
6971
6972void PeerConnection::ReportUsagePattern() const {
6973 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006974 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6975 usage_event_accumulator_,
6976 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006977 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006978 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006979 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6980 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006981 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006982 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6983 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6984 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6985 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006986 // If called after close(), we can't report, because observer may have
6987 // been deallocated, and therefore pointer is null. Write to log instead.
6988 if (observer_) {
6989 Observer()->OnInterestingUsage(usage_event_accumulator_);
6990 } else {
6991 RTC_LOG(LS_INFO) << "Interesting usage signature "
6992 << usage_event_accumulator_
6993 << " observed after observer shutdown";
6994 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006995 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006996}
6997
Steve Anton0ffaaa22018-02-23 10:31:30 -08006998void PeerConnection::ReportNegotiatedSdpSemantics(
6999 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007000 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007001 switch (answer.description()->msid_signaling()) {
7002 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007003 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007004 break;
7005 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007006 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007007 break;
7008 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007009 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007010 break;
7011 case cricket::kMsidSignalingMediaSection |
7012 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007013 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007014 break;
7015 default:
7016 RTC_NOTREACHED();
7017 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007018 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7019 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007020}
7021
Steve Anton75737c02017-11-06 10:37:17 -08007022// We need to check the local/remote description for the Transport instead of
7023// the session, because a new Transport added during renegotiation may have
7024// them unset while the session has them set from the previous negotiation.
7025// Not doing so may trigger the auto generation of transport description and
7026// mess up DTLS identity information, ICE credential, etc.
7027bool PeerConnection::ReadyToUseRemoteCandidate(
7028 const IceCandidateInterface* candidate,
7029 const SessionDescriptionInterface* remote_desc,
7030 bool* valid) {
7031 *valid = true;
7032
7033 const SessionDescriptionInterface* current_remote_desc =
7034 remote_desc ? remote_desc : remote_description();
7035
7036 if (!current_remote_desc) {
7037 return false;
7038 }
7039
Guido Urdaneta41633172019-05-23 20:12:29 +02007040 RTCErrorOr<const cricket::ContentInfo*> result =
7041 FindContentInfo(current_remote_desc, candidate);
7042 if (!result.ok()) {
7043 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7044 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007045
7046 *valid = false;
7047 return false;
7048 }
7049
Guido Urdaneta41633172019-05-23 20:12:29 +02007050 std::string transport_name = GetTransportName(result.value()->name);
7051 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007052}
7053
7054bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007055 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007056 (dtls_enabled_ ||
7057 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007058}
7059
7060void PeerConnection::OnTransportControllerGatheringState(
7061 cricket::IceGatheringState state) {
7062 RTC_DCHECK(signaling_thread()->IsCurrent());
7063 if (state == cricket::kIceGatheringGathering) {
7064 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7065 } else if (state == cricket::kIceGatheringComplete) {
7066 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7067 }
7068}
7069
7070void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007071 std::map<std::string, std::set<cricket::MediaType>>
7072 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007073 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007074 if (transceiver->internal()->channel()) {
7075 const std::string& transport_name =
7076 transceiver->internal()->channel()->transport_name();
7077 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007078 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007079 }
Steve Anton75737c02017-11-06 10:37:17 -08007080 }
7081 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007082 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7083 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007084 }
Zhi Huange830e682018-03-30 10:48:35 -07007085
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007086 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007087 if (transport_name) {
7088 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007089 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007090 }
Zhi Huange830e682018-03-30 10:48:35 -07007091
Steve Antonc7b964c2018-02-01 14:39:45 -08007092 for (const auto& entry : media_types_by_transport_name) {
7093 const std::string& transport_name = entry.first;
7094 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007095 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007096 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007097 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007098 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007099 }
7100 }
7101}
7102// Walk through the ConnectionInfos to gather best connection usage
7103// for IPv4 and IPv6.
7104void PeerConnection::ReportBestConnectionState(
7105 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007106 for (const cricket::TransportChannelStats& channel_stats :
7107 stats.channel_stats) {
7108 for (const cricket::ConnectionInfo& connection_info :
7109 channel_stats.connection_infos) {
7110 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007111 continue;
7112 }
7113
Steve Antonc7b964c2018-02-01 14:39:45 -08007114 const cricket::Candidate& local = connection_info.local_candidate;
7115 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007116
7117 // Increment the counter for IceCandidatePairType.
7118 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7119 (local.type() == RELAY_PORT_TYPE &&
7120 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007121 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7122 GetIceCandidatePairCounter(local, remote),
7123 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007124 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007125 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7126 GetIceCandidatePairCounter(local, remote),
7127 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007128 } else {
7129 RTC_CHECK(0);
7130 }
Steve Anton75737c02017-11-06 10:37:17 -08007131
7132 // Increment the counter for IP type.
7133 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007134 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7135 kBestConnections_IPv4,
7136 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007137 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007138 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7139 kBestConnections_IPv6,
7140 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007141 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007142 RTC_CHECK(!local.address().hostname().empty() &&
7143 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007144 }
7145
7146 return;
7147 }
7148 }
7149}
7150
7151void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007152 const cricket::TransportStats& stats,
7153 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007154 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7155 return;
7156 }
7157
7158 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7159 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7160 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7161 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7162 return;
7163 }
7164
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007165 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7166 for (cricket::MediaType media_type : media_types) {
7167 switch (media_type) {
7168 case cricket::MEDIA_TYPE_AUDIO:
7169 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7170 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7171 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7172 break;
7173 case cricket::MEDIA_TYPE_VIDEO:
7174 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7175 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7176 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7177 break;
7178 case cricket::MEDIA_TYPE_DATA:
7179 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7180 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7181 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7182 break;
7183 default:
7184 RTC_NOTREACHED();
7185 continue;
7186 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007187 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007188 }
7189
7190 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7191 for (cricket::MediaType media_type : media_types) {
7192 switch (media_type) {
7193 case cricket::MEDIA_TYPE_AUDIO:
7194 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7195 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7196 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7197 break;
7198 case cricket::MEDIA_TYPE_VIDEO:
7199 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7200 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7201 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7202 break;
7203 case cricket::MEDIA_TYPE_DATA:
7204 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7205 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7206 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7207 break;
7208 default:
7209 RTC_NOTREACHED();
7210 continue;
7211 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007212 }
Steve Anton75737c02017-11-06 10:37:17 -08007213 }
7214}
7215
7216void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007217 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007218 RTC_DCHECK(call_);
7219 call_->OnSentPacket(sent_packet);
7220}
7221
7222const std::string PeerConnection::GetTransportName(
7223 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007224 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007225 if (channel) {
7226 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007227 }
Steve Anton6fec8802017-12-04 10:37:29 -08007228 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007229 RTC_DCHECK(sctp_mid_);
7230 if (content_name == *sctp_mid_) {
7231 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007232 }
7233 }
7234 // Return an empty string if failed to retrieve the transport name.
7235 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007236}
7237
Steve Anton6fec8802017-12-04 10:37:29 -08007238void PeerConnection::DestroyTransceiverChannel(
7239 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7240 transceiver) {
7241 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007242
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007243 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007244 if (channel) {
7245 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007246 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007247 }
7248}
7249
7250void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007251 if (rtp_data_channel_) {
7252 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007253 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007254 rtp_data_channel_ = nullptr;
7255 }
7256
7257 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7258 // grab a reference to this PeerConnection. If this is called from the
7259 // PeerConnection destructor, the RefCountedObject vtable will have already
7260 // been destroyed (since it is a subclass of PeerConnection) and using
7261 // rtc::Bind will cause "Pure virtual function called" error to appear.
7262
7263 if (sctp_transport_) {
7264 OnDataChannelDestroyed();
7265 network_thread()->Invoke<void>(RTC_FROM_HERE,
7266 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007267 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007268 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007269
7270 if (media_transport_) {
7271 OnDataChannelDestroyed();
7272 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7273 RTC_DCHECK_RUN_ON(network_thread());
7274 TeardownMediaTransportForDataChannels_n();
7275 });
7276 }
Steve Anton6fec8802017-12-04 10:37:29 -08007277}
7278
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007279void PeerConnection::DestroyChannelInterface(
7280 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007281 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007282 switch (channel->media_type()) {
7283 case cricket::MEDIA_TYPE_AUDIO:
7284 channel_manager()->DestroyVoiceChannel(
7285 static_cast<cricket::VoiceChannel*>(channel));
7286 break;
7287 case cricket::MEDIA_TYPE_VIDEO:
7288 channel_manager()->DestroyVideoChannel(
7289 static_cast<cricket::VideoChannel*>(channel));
7290 break;
7291 case cricket::MEDIA_TYPE_DATA:
7292 channel_manager()->DestroyRtpDataChannel(
7293 static_cast<cricket::RtpDataChannel*>(channel));
7294 break;
7295 default:
7296 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7297 break;
7298 }
Zhi Huange830e682018-03-30 10:48:35 -07007299}
Steve Anton6fec8802017-12-04 10:37:29 -08007300
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007301bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007302 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007303 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007304 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007305 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007306 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007307 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007308 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007309 auto base_channel = GetChannel(mid);
7310 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007311 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007312 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007313 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007314 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007315 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007316
Karl Wiberg5966c502019-02-21 23:55:09 +01007317 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007318 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007319 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007320
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007321 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007322}
7323
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007324void PeerConnection::OnSetStreams() {
7325 RTC_DCHECK_RUN_ON(signaling_thread());
7326 if (IsUnifiedPlan())
7327 UpdateNegotiationNeeded();
7328}
7329
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007330PeerConnectionObserver* PeerConnection::Observer() const {
7331 // In earlier production code, the pointer was not cleared on close,
7332 // which might have led to undefined behavior if the observer was not
7333 // deallocated, or strange crashes if it was.
7334 // We use CHECK in order to catch such behavior if it exists.
7335 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7336 RTC_CHECK(observer_);
7337 return observer_;
7338}
7339
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007340CryptoOptions PeerConnection::GetCryptoOptions() {
7341 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7342 // after it has been removed.
7343 return configuration_.crypto_options.has_value()
7344 ? *configuration_.crypto_options
7345 : factory_->options().crypto_options;
7346}
7347
Harald Alvestrand89061872018-01-02 14:08:34 +01007348void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007349 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007350 if (stats_collector_) {
7351 stats_collector_->ClearCachedStatsReport();
7352 }
7353}
7354
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007355void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007356 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7357 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007358}
7359
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007360void PeerConnection::UpdateNegotiationNeeded() {
7361 RTC_DCHECK_RUN_ON(signaling_thread());
7362 if (!IsUnifiedPlan()) {
7363 Observer()->OnRenegotiationNeeded();
7364 return;
7365 }
7366
7367 // If connection's [[IsClosed]] slot is true, abort these steps.
7368 if (IsClosed())
7369 return;
7370
7371 // If connection's signaling state is not "stable", abort these steps.
7372 if (signaling_state() != kStable)
7373 return;
7374
7375 // NOTE
7376 // The negotiation-needed flag will be updated once the state transitions to
7377 // "stable", as part of the steps for setting an RTCSessionDescription.
7378
7379 // If the result of checking if negotiation is needed is false, clear the
7380 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7381 // to false, and abort these steps.
7382 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7383 if (!is_negotiation_needed) {
7384 is_negotiation_needed_ = false;
7385 return;
7386 }
7387
7388 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7389 // steps.
7390 if (is_negotiation_needed_)
7391 return;
7392
7393 // Set connection's [[NegotiationNeeded]] slot to true.
7394 is_negotiation_needed_ = true;
7395
7396 // Queue a task that runs the following steps:
7397 // If connection's [[IsClosed]] slot is true, abort these steps.
7398 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7399 // Fire an event named negotiationneeded at connection.
7400 Observer()->OnRenegotiationNeeded();
7401}
7402
7403bool PeerConnection::CheckIfNegotiationIsNeeded() {
7404 RTC_DCHECK_RUN_ON(signaling_thread());
7405 // 1. If any implementation-specific negotiation is required, as described at
7406 // the start of this section, return true.
7407
Henrik Boström79b69802019-07-18 11:16:56 +02007408 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7409 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7410 return true;
7411 }
7412
7413 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007414 const SessionDescriptionInterface* description = current_local_description();
7415 if (!description)
7416 return true;
7417
Henrik Boström79b69802019-07-18 11:16:56 +02007418 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007419 // description has been negotiated yet for data, return true.
7420 if (!sctp_data_channels_.empty()) {
7421 if (!cricket::GetFirstDataContent(description->description()->contents()))
7422 return true;
7423 }
7424
Henrik Boström79b69802019-07-18 11:16:56 +02007425 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007426 // following checks:
7427 for (const auto& transceiver : transceivers_) {
7428 const ContentInfo* current_local_msection =
7429 FindTransceiverMSection(transceiver.get(), description);
7430
7431 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7432 transceiver.get(), current_remote_description());
7433
Henrik Boström79b69802019-07-18 11:16:56 +02007434 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007435 // but the associated m= section is not yet rejected in
7436 // connection.[[CurrentLocalDescription]] or
7437 // connection.[[CurrentRemoteDescription]], return true.
7438 if (transceiver->stopped()) {
7439 if (current_local_msection && !current_local_msection->rejected &&
7440 ((current_remote_msection && !current_remote_msection->rejected) ||
7441 !current_remote_msection)) {
7442 return true;
7443 }
7444 continue;
7445 }
7446
Henrik Boström79b69802019-07-18 11:16:56 +02007447 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007448 // section in description, return true.
7449 if (!current_local_msection)
7450 return true;
7451
7452 const MediaContentDescription* current_local_media_description =
7453 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007454 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007455 // in description then perform the following checks:
7456
Henrik Boström79b69802019-07-18 11:16:56 +02007457 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007458 // associated m= section in description either doesn't contain a single
7459 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7460 // m= section, or the MSID values themselves, differ from what is in
7461 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7462 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7463 if (current_local_media_description->streams().size() == 0)
7464 return true;
7465
7466 std::vector<std::string> msection_msids;
7467 for (const auto& stream : current_local_media_description->streams()) {
7468 for (const std::string& msid : stream.stream_ids())
7469 msection_msids.push_back(msid);
7470 }
7471
7472 std::vector<std::string> transceiver_msids =
7473 transceiver->sender()->stream_ids();
7474 if (msection_msids.size() != transceiver_msids.size())
7475 return true;
7476
7477 absl::c_sort(transceiver_msids);
7478 absl::c_sort(msection_msids);
7479 if (transceiver_msids != msection_msids)
7480 return true;
7481 }
7482
Henrik Boström79b69802019-07-18 11:16:56 +02007483 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007484 // associated m= section in neither connection.[[CurrentLocalDescription]]
7485 // nor connection.[[CurrentRemoteDescription]] matches
7486 // transceiver.[[Direction]], return true.
7487 if (description->GetType() == SdpType::kOffer) {
7488 if (!current_remote_description())
7489 return true;
7490
7491 if (!current_remote_msection)
7492 return true;
7493
7494 RtpTransceiverDirection current_local_direction =
7495 current_local_media_description->direction();
7496 RtpTransceiverDirection current_remote_direction =
7497 current_remote_msection->media_description()->direction();
7498 if (transceiver->direction() != current_local_direction &&
7499 transceiver->direction() !=
7500 RtpTransceiverDirectionReversed(current_remote_direction)) {
7501 return true;
7502 }
7503 }
7504
Henrik Boström79b69802019-07-18 11:16:56 +02007505 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007506 // associated m= section in the description does not match
7507 // transceiver.[[Direction]] intersected with the offered direction (as
7508 // described in [JSEP] (section 5.3.1.)), return true.
7509 if (description->GetType() == SdpType::kAnswer) {
7510 if (!remote_description())
7511 return true;
7512
7513 const ContentInfo* offered_remote_msection =
7514 FindTransceiverMSection(transceiver.get(), remote_description());
7515
7516 RtpTransceiverDirection offered_direction =
7517 offered_remote_msection
7518 ? offered_remote_msection->media_description()->direction()
7519 : RtpTransceiverDirection::kInactive;
7520
7521 if (current_local_media_description->direction() !=
7522 (RtpTransceiverDirectionIntersection(
7523 transceiver->direction(),
7524 RtpTransceiverDirectionReversed(offered_direction)))) {
7525 return true;
7526 }
7527 }
7528 }
7529
7530 // If all the preceding checks were performed and true was not returned,
7531 // nothing remains to be negotiated; return false.
7532 return false;
7533}
7534
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007535} // namespace webrtc