blob: 44617dd822fe293c73da314cdc636feed9749e09 [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"
27#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020030#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "logging/rtc_event_log/rtc_event_log.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010033#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080035#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "pc/channel_manager.h"
37#include "pc/dtmf_sender.h"
38#include "pc/media_stream.h"
39#include "pc/media_stream_observer.h"
40#include "pc/remote_audio_source.h"
41#include "pc/rtp_media_utils.h"
42#include "pc/rtp_receiver.h"
43#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010044#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "pc/sctp_utils.h"
46#include "pc/sdp_utils.h"
47#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010048#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/bind.h"
51#include "rtc_base/checks.h"
52#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010053#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080054#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020055#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020056#include "rtc_base/trace_event.h"
57#include "system_wrappers/include/clock.h"
58#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070059#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::ContentInfo;
62using cricket::ContentInfos;
63using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080064using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080065using cricket::RidDescription;
66using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080067using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::SimulcastDescription;
69using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080072using cricket::TransportInfo;
73
74using cricket::LOCAL_PORT_TYPE;
75using cricket::STUN_PORT_TYPE;
76using cricket::RELAY_PORT_TYPE;
77using cricket::PRFLX_PORT_TYPE;
78
Steve Antonba818672017-11-06 10:21:57 -080079namespace webrtc {
80
Steve Anton75737c02017-11-06 10:37:17 -080081// Error messages
82const char kBundleWithoutRtcpMux[] =
83 "rtcp-mux must be enabled when BUNDLE "
84 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080085const char kInvalidCandidates[] = "Description contains invalid candidates.";
86const char kInvalidSdp[] = "Invalid session description.";
87const char kMlineMismatchInAnswer[] =
88 "The order of m-lines in answer doesn't match order in offer. Rejecting "
89 "answer.";
90const char kMlineMismatchInSubsequentOffer[] =
91 "The order of m-lines in subsequent offer doesn't match order from "
92 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080093const char kSdpWithoutDtlsFingerprint[] =
94 "Called with SDP without DTLS fingerprint.";
95const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
96const char kSdpWithoutIceUfragPwd[] =
97 "Called with SDP without ice-ufrag and ice-pwd.";
98const char kSessionError[] = "Session error code: ";
99const char kSessionErrorDesc[] = "Session error description: ";
100const char kDtlsSrtpSetupFailureRtp[] =
101 "Couldn't set up DTLS-SRTP on RTP channel.";
102const char kDtlsSrtpSetupFailureRtcp[] =
103 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104
Steve Anton75737c02017-11-06 10:37:17 -0800105namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106
Seth Hampson845e8782018-03-02 11:34:10 -0800107static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800108static const char kDefaultAudioSenderId[] = "defaulta0";
109static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700110
zhihuang8f65cdf2016-05-06 18:40:30 -0700111// The length of RTCP CNAMEs.
112static const int kRtcpCnameLength = 16;
113
Steve Antonad182762018-09-05 20:22:40 +0000114enum {
115 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
116 MSG_SET_SESSIONDESCRIPTION_FAILED,
117 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
118 MSG_GETSTATS,
119 MSG_FREE_DATACHANNELS,
120 MSG_REPORT_USAGE_PATTERN,
121};
122
Harald Alvestrand19793842018-06-25 12:03:50 +0200123static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
124
Steve Antonad182762018-09-05 20:22:40 +0000125struct SetSessionDescriptionMsg : public rtc::MessageData {
126 explicit SetSessionDescriptionMsg(
127 webrtc::SetSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct CreateSessionDescriptionMsg : public rtc::MessageData {
135 explicit CreateSessionDescriptionMsg(
136 webrtc::CreateSessionDescriptionObserver* observer)
137 : observer(observer) {}
138
139 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
140 RTCError error;
141};
142
143struct GetStatsMsg : public rtc::MessageData {
144 GetStatsMsg(webrtc::StatsObserver* observer,
145 webrtc::MediaStreamTrackInterface* track)
146 : observer(observer), track(track) {}
147 rtc::scoped_refptr<webrtc::StatsObserver> observer;
148 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
149};
150
deadbeefab9b2d12015-10-14 11:33:11 -0700151// Check if we can send |new_stream| on a PeerConnection.
152bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
153 webrtc::MediaStreamInterface* new_stream) {
154 if (!new_stream || !current_streams) {
155 return false;
156 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700157 if (current_streams->find(new_stream->id()) != nullptr) {
158 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100159 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700160 return false;
161 }
162 return true;
163}
164
deadbeef5e97fb52015-10-15 12:49:08 -0700165// If the direction is "recvonly" or "inactive", treat the description
166// as containing no streams.
167// See: https://code.google.com/p/webrtc/issues/detail?id=5054
168std::vector<cricket::StreamParams> GetActiveStreams(
169 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800170 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700171 ? desc->streams()
172 : std::vector<cricket::StreamParams>();
173}
174
deadbeefab9b2d12015-10-14 11:33:11 -0700175bool IsValidOfferToReceiveMedia(int value) {
176 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
177 return (value >= Options::kUndefined) &&
178 (value <= Options::kMaxOfferToReceiveMedia);
179}
180
zhihuang1c378ed2017-08-17 14:10:50 -0700181// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800182void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700183 const std::vector<rtc::scoped_refptr<
184 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700185 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200186 cricket::MediaDescriptionOptions* video_media_description_options,
187 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700188 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700189 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
190 if (audio_media_description_options) {
191 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700192 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700193 }
194 } else {
195 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
196 if (video_media_description_options) {
197 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800198 sender->id(), sender->internal()->stream_ids(), {},
199 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700200 }
201 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700202 }
zhihuang1c378ed2017-08-17 14:10:50 -0700203}
olka3c747662017-08-17 06:50:32 -0700204
zhihuang1c378ed2017-08-17 14:10:50 -0700205// Add options to |session_options| from |rtp_data_channels|.
206void AddRtpDataChannelOptions(
207 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
208 rtp_data_channels,
209 cricket::MediaDescriptionOptions* data_media_description_options) {
210 if (!data_media_description_options) {
211 return;
212 }
deadbeefab9b2d12015-10-14 11:33:11 -0700213 // Check for data channels.
214 for (const auto& kv : rtp_data_channels) {
215 const DataChannel* channel = kv.second;
216 if (channel->state() == DataChannel::kConnecting ||
217 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700218 // Legacy RTP data channels are signaled with the track/stream ID set to
219 // the data channel's label.
220 data_media_description_options->AddRtpDataChannel(channel->label(),
221 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700222 }
223 }
224}
225
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700226uint32_t ConvertIceTransportTypeToCandidateFilter(
227 PeerConnectionInterface::IceTransportsType type) {
228 switch (type) {
229 case PeerConnectionInterface::kNone:
230 return cricket::CF_NONE;
231 case PeerConnectionInterface::kRelay:
232 return cricket::CF_RELAY;
233 case PeerConnectionInterface::kNoHost:
234 return (cricket::CF_ALL & ~cricket::CF_HOST);
235 case PeerConnectionInterface::kAll:
236 return cricket::CF_ALL;
237 default:
nissec80e7412017-01-11 05:56:46 -0800238 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700239 }
240 return cricket::CF_NONE;
241}
242
deadbeef293e9262017-01-11 12:28:30 -0800243// Helper to set an error and return from a method.
244bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
245 if (error) {
246 error->set_type(type);
247 }
248 return type == webrtc::RTCErrorType::NONE;
249}
250
Steve Anton038834f2017-07-14 15:59:59 -0700251bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700252 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700253 if (error_out) {
254 *error_out = std::move(error);
255 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700256 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700257}
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// Get the SCTP port out of a SessionDescription.
547// Return -1 if not found.
548int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 const cricket::DataContentDescription* data_desc =
550 GetFirstDataContentDescription(session_description);
551 RTC_DCHECK(data_desc);
552 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800553 return -1;
554 }
Steve Anton75737c02017-11-06 10:37:17 -0800555 std::string value;
556 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
557 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800558 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800559 if (!codec.Matches(match_pattern)) {
560 continue;
561 }
562 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
563 return rtc::FromString<int>(value);
564 }
565 }
566 return -1;
567}
568
Steve Anton75737c02017-11-06 10:37:17 -0800569// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
570bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
571 const SessionDescriptionInterface* new_desc,
572 const std::string& content_name) {
573 if (!old_desc) {
574 return false;
575 }
576 const SessionDescription* new_sd = new_desc->description();
577 const SessionDescription* old_sd = old_desc->description();
578 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
579 if (!cinfo || cinfo->rejected) {
580 return false;
581 }
582 // If the content isn't rejected, check if ufrag and password has changed.
583 const cricket::TransportDescription* new_transport_desc =
584 new_sd->GetTransportDescriptionByName(content_name);
585 const cricket::TransportDescription* old_transport_desc =
586 old_sd->GetTransportDescriptionByName(content_name);
587 if (!new_transport_desc || !old_transport_desc) {
588 // No transport description exists. This is not an ICE restart.
589 return false;
590 }
591 if (cricket::IceCredentialsChanged(
592 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
593 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100594 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
595 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800596 return true;
597 }
598 return false;
599}
600
Steve Anton80dd7b52018-02-16 17:08:42 -0800601// Generates a string error message for SetLocalDescription/SetRemoteDescription
602// from an RTCError.
603std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
604 SdpType type,
605 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200606 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800607 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
608 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200609 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800610}
611
Seth Hampson5b4f0752018-04-02 16:31:36 -0700612std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
613 std::string output = "streams=[";
614 const char* separator = "";
615 for (const auto& stream_id : stream_ids) {
616 output.append(separator).append(stream_id);
617 separator = ", ";
618 }
619 output.append("]");
620 return output;
621}
622
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200623absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700624 int rtc_configuration_parameter) {
625 if (rtc_configuration_parameter ==
626 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200627 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700628 }
629 return rtc_configuration_parameter;
630}
631
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800632cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
633 switch (type) {
634 case DataMessageType::kText:
635 return cricket::DMT_TEXT;
636 case DataMessageType::kBinary:
637 return cricket::DMT_BINARY;
638 case DataMessageType::kControl:
639 return cricket::DMT_CONTROL;
640 default:
641 return cricket::DMT_NONE;
642 }
643 return cricket::DMT_NONE;
644}
645
646DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
647 switch (type) {
648 case cricket::DMT_TEXT:
649 return DataMessageType::kText;
650 case cricket::DMT_BINARY:
651 return DataMessageType::kBinary;
652 case cricket::DMT_CONTROL:
653 return DataMessageType::kControl;
654 case cricket::DMT_NONE:
655 default:
656 RTC_NOTREACHED();
657 }
658 return DataMessageType::kControl;
659}
660
Steve Anton75737c02017-11-06 10:37:17 -0800661} // namespace
662
Henrik Boström31638672017-11-23 17:48:32 +0100663// Upon completion, posts a task to execute the callback of the
664// SetSessionDescriptionObserver asynchronously on the same thread. At this
665// point, the state of the peer connection might no longer reflect the effects
666// of the SetRemoteDescription operation, as the peer connection could have been
667// modified during the post.
668// TODO(hbos): Remove this class once we remove the version of
669// PeerConnectionInterface::SetRemoteDescription() that takes a
670// SetSessionDescriptionObserver as an argument.
671class PeerConnection::SetRemoteDescriptionObserverAdapter
672 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
673 public:
674 SetRemoteDescriptionObserverAdapter(
675 rtc::scoped_refptr<PeerConnection> pc,
676 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
677 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
678
679 // SetRemoteDescriptionObserverInterface implementation.
680 void OnSetRemoteDescriptionComplete(RTCError error) override {
681 if (error.ok())
682 pc_->PostSetSessionDescriptionSuccess(wrapper_);
683 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100684 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100685 }
686
687 private:
688 rtc::scoped_refptr<PeerConnection> pc_;
689 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
690};
691
deadbeef293e9262017-01-11 12:28:30 -0800692bool PeerConnectionInterface::RTCConfiguration::operator==(
693 const PeerConnectionInterface::RTCConfiguration& o) const {
694 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700695 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800696 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000697 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700698 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800699 BundlePolicy bundle_policy;
700 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700701 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
702 int ice_candidate_pool_size;
703 bool disable_ipv6;
704 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700705 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100706 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700707 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200708 absl::optional<int> screencast_min_bitrate;
709 absl::optional<bool> combined_audio_video_bwe;
710 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800711 TcpCandidatePolicy tcp_candidate_policy;
712 CandidateNetworkPolicy candidate_network_policy;
713 int audio_jitter_buffer_max_packets;
714 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100715 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100716 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800717 int ice_connection_receiving_timeout;
718 int ice_backup_candidate_pair_ping_interval;
719 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800720 bool prioritize_most_likely_ice_candidate_pairs;
721 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800722 bool prune_turn_ports;
723 bool presume_writable_when_fully_relayed;
724 bool enable_ice_renomination;
725 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200726 absl::optional<int> ice_check_interval_strong_connectivity;
727 absl::optional<int> ice_check_interval_weak_connectivity;
728 absl::optional<int> ice_check_min_interval;
729 absl::optional<int> ice_unwritable_timeout;
730 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800731 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200732 absl::optional<int> stun_candidate_keepalive_interval;
733 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200734 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800735 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200736 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700737 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700738 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700739 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700740 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100741 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800742 };
743 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
744 "Did you add something to RTCConfiguration and forget to "
745 "update operator==?");
746 return type == o.type && servers == o.servers &&
747 bundle_policy == o.bundle_policy &&
748 rtcp_mux_policy == o.rtcp_mux_policy &&
749 tcp_candidate_policy == o.tcp_candidate_policy &&
750 candidate_network_policy == o.candidate_network_policy &&
751 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
752 audio_jitter_buffer_fast_accelerate ==
753 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100754 audio_jitter_buffer_min_delay_ms ==
755 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100756 audio_jitter_buffer_enable_rtx_handling ==
757 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800758 ice_connection_receiving_timeout ==
759 o.ice_connection_receiving_timeout &&
760 ice_backup_candidate_pair_ping_interval ==
761 o.ice_backup_candidate_pair_ping_interval &&
762 continual_gathering_policy == o.continual_gathering_policy &&
763 certificates == o.certificates &&
764 prioritize_most_likely_ice_candidate_pairs ==
765 o.prioritize_most_likely_ice_candidate_pairs &&
766 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800767 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700768 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100769 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800770 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800771 screencast_min_bitrate == o.screencast_min_bitrate &&
772 combined_audio_video_bwe == o.combined_audio_video_bwe &&
773 enable_dtls_srtp == o.enable_dtls_srtp &&
774 ice_candidate_pool_size == o.ice_candidate_pool_size &&
775 prune_turn_ports == o.prune_turn_ports &&
776 presume_writable_when_fully_relayed ==
777 o.presume_writable_when_fully_relayed &&
778 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800779 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800780 ice_check_interval_strong_connectivity ==
781 o.ice_check_interval_strong_connectivity &&
782 ice_check_interval_weak_connectivity ==
783 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700784 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700785 ice_unwritable_timeout == o.ice_unwritable_timeout &&
786 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800787 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800788 stun_candidate_keepalive_interval ==
789 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200790 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800791 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800792 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700793 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700794 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700795 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700796 use_media_transport_for_data_channels ==
797 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100798 crypto_options == o.crypto_options &&
799 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800800}
801
802bool PeerConnectionInterface::RTCConfiguration::operator!=(
803 const PeerConnectionInterface::RTCConfiguration& o) const {
804 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800805}
806
zhihuang8f65cdf2016-05-06 18:40:30 -0700807// Generate a RTCP CNAME when a PeerConnection is created.
808std::string GenerateRtcpCname() {
809 std::string cname;
810 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100811 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800812 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700813 }
814 return cname;
815}
816
zhihuang1c378ed2017-08-17 14:10:50 -0700817bool ValidateOfferAnswerOptions(
818 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
819 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
820 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700821}
822
zhihuang1c378ed2017-08-17 14:10:50 -0700823// From |rtc_options|, fill parts of |session_options| shared by all generated
824// m= sections (in other words, nothing that involves a map/array).
825void ExtractSharedMediaSessionOptions(
826 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
827 cricket::MediaSessionOptions* session_options) {
828 session_options->vad_enabled = rtc_options.voice_activity_detection;
829 session_options->bundle_enabled = rtc_options.use_rtp_mux;
830}
zhihuanga77e6bb2017-08-14 18:17:48 -0700831
zhihuang38ede132017-06-15 12:52:32 -0700832PeerConnection::PeerConnection(PeerConnectionFactory* factory,
833 std::unique_ptr<RtcEventLog> event_log,
834 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700836 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100837 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700838 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700839 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700840 remote_streams_(StreamCollection::Create()),
841 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842
843PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100844 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800845 RTC_DCHECK_RUN_ON(signaling_thread());
846
Steve Anton8af21862017-12-15 11:20:13 -0800847 // Need to stop transceivers before destroying the stats collector because
848 // AudioRtpSender has a reference to the StatsCollector it will update when
849 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100850 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800851 transceiver->Stop();
852 }
Steve Anton4171afb2017-11-20 10:20:22 -0800853
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700854 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800855 if (stats_collector_) {
856 stats_collector_->WaitForPendingRequest();
857 stats_collector_ = nullptr;
858 }
Steve Anton75737c02017-11-06 10:37:17 -0800859
Steve Anton8af21862017-12-15 11:20:13 -0800860 // Don't destroy BaseChannels until after stats has been cleaned up so that
861 // the last stats request can still read from the channels.
862 DestroyAllChannels();
863
Mirko Bonadei675513b2017-11-09 11:09:25 +0100864 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800865
866 webrtc_session_desc_factory_.reset();
867 sctp_invoker_.reset();
868 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800869 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800870 transport_controller_.reset();
871
deadbeef91dd5672016-05-18 16:55:30 -0700872 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700873 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700874 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700875 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700876 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100877 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700878 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800879 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700880 event_log_.reset();
881 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882}
883
Steve Anton8af21862017-12-15 11:20:13 -0800884void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800885 // Destroy video channels first since they may have a pointer to a voice
886 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100887 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800888 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800889 DestroyTransceiverChannel(transceiver);
890 }
891 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100892 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800893 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800894 DestroyTransceiverChannel(transceiver);
895 }
896 }
897 DestroyDataChannel();
898}
899
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000901 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700902 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100903 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100904 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100905 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700906
907 RTCError config_error = ValidateConfiguration(configuration);
908 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100909 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700910 return false;
911 }
912
Benjamin Wrightcab58882018-05-02 15:12:47 -0700913 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100914 RTC_LOG(LS_ERROR)
915 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100916 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800917 return false;
918 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200919
Benjamin Wrightcab58882018-05-02 15:12:47 -0700920 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800921 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100922 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100923 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800924 return false;
925 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700926
Benjamin Wrightcab58882018-05-02 15:12:47 -0700927 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700928 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700929 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700930 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800931
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200932 cricket::ServerAddresses stun_servers;
933 std::vector<cricket::RelayServerConfig> turn_servers;
934
935 RTCErrorType parse_error =
936 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
937 if (parse_error != RTCErrorType::NONE) {
938 return false;
939 }
940
deadbeef91dd5672016-05-18 16:55:30 -0700941 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700942 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700943 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200944 RTC_FROM_HERE,
945 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
946 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 return false;
948 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200949 // If initialization was successful, note if STUN or TURN servers
950 // were supplied.
951 if (!stun_servers.empty()) {
952 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
953 }
954 if (!turn_servers.empty()) {
955 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
956 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700958 // Send information about IPv4/IPv6 status.
959 PeerConnectionAddressFamilyCounter address_family;
960 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
961 address_family = kPeerConnection_IPv6;
962 } else {
963 address_family = kPeerConnection_IPv4;
964 }
965 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
966 kPeerConnectionAddressFamilyCounter_Max);
967
Zhi Huange830e682018-03-30 10:48:35 -0700968 const PeerConnectionFactoryInterface::Options& options = factory_->options();
969
Steve Anton75737c02017-11-06 10:37:17 -0800970 // RFC 3264: The numeric value of the session id and version in the
971 // o line MUST be representable with a "64 bit signed integer".
972 // Due to this constraint session id |session_id_| is max limited to
973 // LLONG_MAX.
974 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700975 JsepTransportController::Config config;
976 config.redetermine_role_on_ice_restart =
977 configuration.redetermine_role_on_ice_restart;
978 config.ssl_max_version = factory_->options().ssl_max_version;
979 config.disable_encryption = options.disable_encryption;
980 config.bundle_policy = configuration.bundle_policy;
981 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700982 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
983 // stub.
984 config.crypto_options = configuration.crypto_options.has_value()
985 ? *configuration.crypto_options
986 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700987 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +0100988 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -0700989#if defined(ENABLE_EXTERNAL_AUTH)
990 config.enable_external_auth = true;
991#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700992 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700993
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700994 if (configuration.use_media_transport ||
995 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700996 if (!factory_->media_transport_factory()) {
997 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700998 << "PeerConnecton is initialized with use_media_transport = true or "
999 << "use_media_transport_for_data_channels = true "
1000 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001001 return false;
1002 }
1003
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001004 config.use_media_transport_for_media = configuration.use_media_transport;
1005 config.use_media_transport_for_data_channels =
1006 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001007 config.media_transport_factory = factory_->media_transport_factory();
1008 }
1009
Zhi Huange830e682018-03-30 10:48:35 -07001010 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001011 signaling_thread(), network_thread(), port_allocator_.get(),
1012 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001013 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001014 this, &PeerConnection::OnTransportControllerConnectionState);
1015 transport_controller_->SignalStandardizedIceConnectionState.connect(
1016 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001017 transport_controller_->SignalConnectionState.connect(
1018 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001019 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001020 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001021 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001022 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001023 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001024 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1025 transport_controller_->SignalDtlsHandshakeError.connect(
1026 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1027
1028 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001029
deadbeefab9b2d12015-10-14 11:33:11 -07001030 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001031 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032
Steve Antonba818672017-11-06 10:21:57 -08001033 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001034 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001035
Steve Anton75737c02017-11-06 10:37:17 -08001036 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1037 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1038 if (!configuration.certificates.empty()) {
1039 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1040 // just picking the first one. The decision should be made based on the DTLS
1041 // handshake. The DTLS negotiations need to know about all certificates.
1042 certificate = configuration.certificates[0];
1043 }
1044
Steve Antond25da372017-11-06 14:50:29 -08001045 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001046
1047 if (options.disable_encryption) {
1048 dtls_enabled_ = false;
1049 } else {
1050 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001051 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001052 // |configuration| can override the default |dtls_enabled_| value.
1053 if (configuration.enable_dtls_srtp) {
1054 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1055 }
1056 }
1057
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001058 if (configuration.use_media_transport_for_data_channels) {
1059 if (configuration.enable_rtp_data_channel) {
1060 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1061 "use_media_transport_for_data_channels are "
1062 "incompatible and cannot both be set to true";
1063 return false;
1064 }
1065 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1066 } else if (configuration.enable_rtp_data_channel) {
1067 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1068 // set. It takes precendence over the disable_sctp_data_channels
1069 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001070 data_channel_type_ = cricket::DCT_RTP;
1071 } else {
1072 // DTLS has to be enabled to use SCTP.
1073 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1074 data_channel_type_ = cricket::DCT_SCTP;
1075 }
1076 }
1077
1078 video_options_.screencast_min_bitrate_kbps =
1079 configuration.screencast_min_bitrate;
1080 audio_options_.combined_audio_video_bwe =
1081 configuration.combined_audio_video_bwe;
1082
1083 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001084 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001085
1086 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001087 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001088
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001089 audio_options_.audio_jitter_buffer_min_delay_ms =
1090 configuration.audio_jitter_buffer_min_delay_ms;
1091
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001092 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1093 configuration.audio_jitter_buffer_enable_rtx_handling;
1094
Steve Anton75737c02017-11-06 10:37:17 -08001095 // Whether the certificate generator/certificate is null or not determines
1096 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1097 // the right instructions by clearing the variables if needed.
1098 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001099 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001100 certificate = nullptr;
1101 } else if (certificate) {
1102 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001103 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001104 }
1105
1106 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1107 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001108 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001109 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1110 this, &PeerConnection::OnCertificateReady);
1111
1112 if (options.disable_encryption) {
1113 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1114 }
1115
1116 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001117 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001118 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119
Steve Anton4171afb2017-11-20 10:20:22 -08001120 // Add default audio/video transceivers for Plan B SDP.
1121 if (!IsUnifiedPlan()) {
1122 transceivers_.push_back(
1123 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1124 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1125 transceivers_.push_back(
1126 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1127 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1128 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001129 int delay_ms =
1130 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001131 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1132 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133 return true;
1134}
1135
Steve Anton038834f2017-07-14 15:59:59 -07001136RTCError PeerConnection::ValidateConfiguration(
1137 const RTCConfiguration& config) const {
1138 if (config.ice_regather_interval_range &&
1139 config.continual_gathering_policy == GATHER_ONCE) {
1140 return RTCError(RTCErrorType::INVALID_PARAMETER,
1141 "ice_regather_interval_range specified but continual "
1142 "gathering policy is GATHER_ONCE");
1143 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001144 auto result =
1145 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1146 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001147}
1148
Yves Gerey665174f2018-06-19 15:03:05 +02001149rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001150 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001151 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1152 "Plan SdpSemantics. Please use GetSenders "
1153 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001154 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001155}
1156
Yves Gerey665174f2018-06-19 15:03:05 +02001157rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001158 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001159 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1160 "Plan SdpSemantics. Please use GetReceivers "
1161 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001162 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163}
1164
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001165bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001166 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001167 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1168 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001169 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170 if (IsClosed()) {
1171 return false;
1172 }
deadbeefab9b2d12015-10-14 11:33:11 -07001173 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174 return false;
1175 }
deadbeefab9b2d12015-10-14 11:33:11 -07001176
1177 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001178 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1179 observer->SignalAudioTrackAdded.connect(this,
1180 &PeerConnection::OnAudioTrackAdded);
1181 observer->SignalAudioTrackRemoved.connect(
1182 this, &PeerConnection::OnAudioTrackRemoved);
1183 observer->SignalVideoTrackAdded.connect(this,
1184 &PeerConnection::OnVideoTrackAdded);
1185 observer->SignalVideoTrackRemoved.connect(
1186 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001187 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001188
deadbeefab9b2d12015-10-14 11:33:11 -07001189 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001190 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001191 }
1192 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001193 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001194 }
1195
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001196 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001197 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001198 return true;
1199}
1200
1201void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001202 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001203 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1204 "Plan SdpSemantics. Please use RemoveTrack "
1205 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001206 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001207 if (!IsClosed()) {
1208 for (const auto& track : local_stream->GetAudioTracks()) {
1209 RemoveAudioTrack(track.get(), local_stream);
1210 }
1211 for (const auto& track : local_stream->GetVideoTracks()) {
1212 RemoveVideoTrack(track.get(), local_stream);
1213 }
deadbeefab9b2d12015-10-14 11:33:11 -07001214 }
deadbeefab9b2d12015-10-14 11:33:11 -07001215 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001216 stream_observers_.erase(
1217 std::remove_if(
1218 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001219 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001220 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001221 }),
1222 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001223
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001224 if (IsClosed()) {
1225 return;
1226 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001227 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228}
1229
Steve Anton2d6c76a2018-01-05 17:10:52 -08001230RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001231 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001232 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001233 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001234 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001235 if (!track) {
1236 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1237 }
1238 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1239 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1240 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1241 "Track has invalid kind: " + track->kind());
1242 }
Steve Antonf9381f02017-12-14 10:23:57 -08001243 if (IsClosed()) {
1244 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1245 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001246 }
Steve Anton4171afb2017-11-20 10:20:22 -08001247 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001248 LOG_AND_RETURN_ERROR(
1249 RTCErrorType::INVALID_PARAMETER,
1250 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001251 }
Steve Antonf9381f02017-12-14 10:23:57 -08001252 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001253 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1254 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001255 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001256 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001257 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001258 }
1259 return sender_or_error;
1260}
deadbeefe1f9d832016-01-14 15:35:42 -08001261
Steve Antonf9381f02017-12-14 10:23:57 -08001262RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1263PeerConnection::AddTrackPlanB(
1264 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001265 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001266 if (stream_ids.size() > 1u) {
1267 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1268 "AddTrack with more than one stream is not "
1269 "supported with Plan B semantics.");
1270 }
1271 std::vector<std::string> adjusted_stream_ids = stream_ids;
1272 if (adjusted_stream_ids.empty()) {
1273 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1274 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001275 cricket::MediaType media_type =
1276 (track->kind() == MediaStreamTrackInterface::kAudioKind
1277 ? cricket::MEDIA_TYPE_AUDIO
1278 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001279 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001280 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001281 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001282 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001283 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001284 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001285 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001286 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001287 if (sender_info) {
1288 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001289 }
Steve Antonf9381f02017-12-14 10:23:57 -08001290 } else {
1291 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001292 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001293 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001294 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001295 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001296 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001297 if (sender_info) {
1298 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001299 }
deadbeefe1f9d832016-01-14 15:35:42 -08001300 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001301 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001302}
deadbeefe1f9d832016-01-14 15:35:42 -08001303
Steve Antonf9381f02017-12-14 10:23:57 -08001304RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1305PeerConnection::AddTrackUnifiedPlan(
1306 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001307 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001308 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1309 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001310 RTC_LOG(LS_INFO) << "Reusing an existing "
1311 << cricket::MediaTypeToString(transceiver->media_type())
1312 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001313 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001314 transceiver->internal()->set_direction(
1315 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001316 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001317 transceiver->internal()->set_direction(
1318 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001319 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001320 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001321 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001322 } else {
1323 cricket::MediaType media_type =
1324 (track->kind() == MediaStreamTrackInterface::kAudioKind
1325 ? cricket::MEDIA_TYPE_AUDIO
1326 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001327 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1328 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001329 std::string sender_id = track->id();
1330 // Avoid creating a sender with an existing ID by generating a random ID.
1331 // This can happen if this is the second time AddTrack has created a sender
1332 // for this track.
1333 if (FindSenderById(sender_id)) {
1334 sender_id = rtc::CreateRandomUuid();
1335 }
Florent Castelli892acf02018-10-01 22:47:20 +02001336 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001337 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1338 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001339 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001340 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001341 }
Steve Antonf9381f02017-12-14 10:23:57 -08001342 return transceiver->sender();
1343}
1344
1345rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1346PeerConnection::FindFirstTransceiverForAddedTrack(
1347 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1348 RTC_DCHECK(track);
1349 for (auto transceiver : transceivers_) {
1350 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001351 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001352 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001353 !transceiver->internal()->has_ever_been_used_to_send() &&
1354 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001355 return transceiver;
1356 }
1357 }
1358 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001359}
1360
1361bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1362 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001363 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001364}
1365
Steve Anton24db5732018-07-23 10:27:33 -07001366RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001367 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001368 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001369 if (!sender) {
1370 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1371 }
deadbeefe1f9d832016-01-14 15:35:42 -08001372 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001373 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1374 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001375 }
Steve Antonf9381f02017-12-14 10:23:57 -08001376 if (IsUnifiedPlan()) {
1377 auto transceiver = FindTransceiverBySender(sender);
1378 if (!transceiver || !sender->track()) {
1379 return RTCError::OK();
1380 }
1381 sender->SetTrack(nullptr);
1382 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001383 transceiver->internal()->set_direction(
1384 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001385 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001386 transceiver->internal()->set_direction(
1387 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001388 }
Steve Anton4171afb2017-11-20 10:20:22 -08001389 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001390 bool removed;
1391 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1392 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1393 } else {
1394 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1395 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1396 }
1397 if (!removed) {
1398 LOG_AND_RETURN_ERROR(
1399 RTCErrorType::INVALID_PARAMETER,
1400 "Couldn't find sender " + sender->id() + " to remove.");
1401 }
Steve Anton4171afb2017-11-20 10:20:22 -08001402 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001403 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001404 return RTCError::OK();
1405}
1406
1407rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1408PeerConnection::FindTransceiverBySender(
1409 rtc::scoped_refptr<RtpSenderInterface> sender) {
1410 for (auto transceiver : transceivers_) {
1411 if (transceiver->sender() == sender) {
1412 return transceiver;
1413 }
1414 }
1415 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001416}
1417
Steve Anton9158ef62017-11-27 13:01:52 -08001418RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1419PeerConnection::AddTransceiver(
1420 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1421 return AddTransceiver(track, RtpTransceiverInit());
1422}
1423
1424RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1425PeerConnection::AddTransceiver(
1426 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1427 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001428 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001429 RTC_CHECK(IsUnifiedPlan())
1430 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001431 if (!track) {
1432 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1433 }
1434 cricket::MediaType media_type;
1435 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1436 media_type = cricket::MEDIA_TYPE_AUDIO;
1437 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1438 media_type = cricket::MEDIA_TYPE_VIDEO;
1439 } else {
1440 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1441 "Track kind is not audio or video");
1442 }
1443 return AddTransceiver(media_type, track, init);
1444}
1445
1446RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1447PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1448 return AddTransceiver(media_type, RtpTransceiverInit());
1449}
1450
1451RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1452PeerConnection::AddTransceiver(cricket::MediaType media_type,
1453 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001454 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001455 RTC_CHECK(IsUnifiedPlan())
1456 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001457 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1458 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1459 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1460 "media type is not audio or video");
1461 }
1462 return AddTransceiver(media_type, nullptr, init);
1463}
1464
1465RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1466PeerConnection::AddTransceiver(
1467 cricket::MediaType media_type,
1468 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001469 const RtpTransceiverInit& init,
1470 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001471 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1472 media_type == cricket::MEDIA_TYPE_VIDEO));
1473 if (track) {
1474 RTC_DCHECK_EQ(media_type,
1475 (track->kind() == MediaStreamTrackInterface::kAudioKind
1476 ? cricket::MEDIA_TYPE_AUDIO
1477 : cricket::MEDIA_TYPE_VIDEO));
1478 }
1479
Amit Hilbuchaa584152019-02-06 17:09:52 -08001480 size_t num_rids = absl::c_count_if(init.send_encodings,
1481 [](const RtpEncodingParameters& encoding) {
1482 return !encoding.rid.empty();
1483 });
1484 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001485 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001486 RTCErrorType::INVALID_PARAMETER,
1487 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001488 }
1489
Amit Hilbuchaa584152019-02-06 17:09:52 -08001490 if (absl::c_any_of(init.send_encodings,
1491 [](const RtpEncodingParameters& encoding) {
1492 return encoding.ssrc.has_value();
1493 })) {
1494 LOG_AND_RETURN_ERROR(
1495 RTCErrorType::UNSUPPORTED_PARAMETER,
1496 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001497 }
1498
1499 RtpParameters parameters;
1500 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001501
1502 // Encodings are dropped from the tail if too many are provided.
1503 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1504 parameters.encodings.erase(
1505 parameters.encodings.begin() + kMaxSimulcastStreams,
1506 parameters.encodings.end());
1507 }
1508
1509 // Single RID should be removed.
1510 if (parameters.encodings.size() == 1 &&
1511 !parameters.encodings[0].rid.empty()) {
1512 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1513 parameters.encodings[0].rid.clear();
1514 }
1515
1516 // If RIDs were not provided, they are generated for simulcast scenario.
1517 if (parameters.encodings.size() > 1 && num_rids == 0) {
1518 rtc::UniqueStringGenerator rid_generator;
1519 for (RtpEncodingParameters& encoding : parameters.encodings) {
1520 encoding.rid = rid_generator();
1521 }
1522 }
1523
Florent Castelli892acf02018-10-01 22:47:20 +02001524 if (UnimplementedRtpParameterHasValue(parameters)) {
1525 LOG_AND_RETURN_ERROR(
1526 RTCErrorType::UNSUPPORTED_PARAMETER,
1527 "Attempted to set an unimplemented parameter of RtpParameters.");
1528 }
Steve Anton9158ef62017-11-27 13:01:52 -08001529
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001530 auto result = cricket::CheckRtpParametersValues(parameters);
1531 if (!result.ok()) {
1532 LOG_AND_RETURN_ERROR(result.type(), result.message());
1533 }
1534
Steve Anton3d954a62018-04-02 11:27:23 -07001535 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1536 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001537 // Set the sender ID equal to the track ID if the track is specified unless
1538 // that sender ID is already in use.
1539 std::string sender_id =
1540 (track && !FindSenderById(track->id()) ? track->id()
1541 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001542 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001543 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001544 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1545 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1546 transceiver->internal()->set_direction(init.direction);
1547
Steve Anton22da89f2018-01-25 13:58:07 -08001548 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001549 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001550 }
Steve Antonf9381f02017-12-14 10:23:57 -08001551
1552 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1553}
1554
Steve Anton02ee47c2018-01-10 16:26:06 -08001555rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1556PeerConnection::CreateSender(
1557 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001558 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001559 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001560 const std::vector<std::string>& stream_ids,
1561 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001562 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001563 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1564 RTC_DCHECK(!track ||
1565 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1566 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1567 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001568 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001569 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001570 } else {
1571 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1572 RTC_DCHECK(!track ||
1573 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1574 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001575 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001576 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001577 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001578 bool set_track_succeeded = sender->SetTrack(track);
1579 RTC_DCHECK(set_track_succeeded);
1580 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001581 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001582 return sender;
1583}
1584
1585rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1586PeerConnection::CreateReceiver(cricket::MediaType media_type,
1587 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001588 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1589 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001590 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001591 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001592 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1593 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001594 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001595 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001596 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001597 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001598 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1599 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001600 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001601 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001602 return receiver;
1603}
1604
1605rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1606PeerConnection::CreateAndAddTransceiver(
1607 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1608 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1609 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001610 // Ensure that the new sender does not have an ID that is already in use by
1611 // another sender.
1612 // Allow receiver IDs to conflict since those come from remote SDP (which
1613 // could be invalid, but should not cause a crash).
1614 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001615 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1616 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001617 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001618 transceiver->internal()->SignalNegotiationNeeded.connect(
1619 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001620 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001621}
1622
Steve Anton52d86772018-02-20 15:48:12 -08001623void PeerConnection::OnNegotiationNeeded() {
1624 RTC_DCHECK_RUN_ON(signaling_thread());
1625 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001626 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001627}
1628
deadbeeffac06552015-11-25 11:26:01 -08001629rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001630 const std::string& kind,
1631 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001632 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001633 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1634 "Plan SdpSemantics. Please use AddTransceiver "
1635 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001636 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001637 if (IsClosed()) {
1638 return nullptr;
1639 }
Steve Anton4171afb2017-11-20 10:20:22 -08001640
Seth Hampson5b4f0752018-04-02 16:31:36 -07001641 // Internally we need to have one stream with Plan B semantics, so we
1642 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001643 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001644 if (stream_id.empty()) {
1645 stream_ids.push_back(rtc::CreateRandomUuid());
1646 RTC_LOG(LS_INFO)
1647 << "No stream_id specified for sender. Generated stream ID: "
1648 << stream_ids[0];
1649 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001650 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001651 }
1652
Steve Anton4171afb2017-11-20 10:20:22 -08001653 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001654 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001655 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001656 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001657 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001658 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001659 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001660 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001661 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001662 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001663 auto video_sender =
1664 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001665 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001666 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001667 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001668 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001669 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001670 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001671 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001672 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001673 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001674
deadbeefe1f9d832016-01-14 15:35:42 -08001675 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001676}
1677
deadbeef70ab1a12015-09-28 16:53:55 -07001678std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1679 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001680 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001681 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001682 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001683 }
1684 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001685}
1686
Steve Anton4171afb2017-11-20 10:20:22 -08001687std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1688PeerConnection::GetSendersInternal() const {
1689 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1690 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001691 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001692 auto senders = transceiver->internal()->senders();
1693 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1694 }
1695 return all_senders;
1696}
1697
deadbeef70ab1a12015-09-28 16:53:55 -07001698std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1699PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001700 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001701 for (const auto& receiver : GetReceiversInternal()) {
1702 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001703 }
1704 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001705}
1706
Steve Anton4171afb2017-11-20 10:20:22 -08001707std::vector<
1708 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1709PeerConnection::GetReceiversInternal() const {
1710 std::vector<
1711 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1712 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001713 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001714 auto receivers = transceiver->internal()->receivers();
1715 all_receivers.insert(all_receivers.end(), receivers.begin(),
1716 receivers.end());
1717 }
1718 return all_receivers;
1719}
1720
Steve Anton9158ef62017-11-27 13:01:52 -08001721std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1722PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001723 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001724 RTC_CHECK(IsUnifiedPlan())
1725 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001726 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001727 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001728 all_transceivers.push_back(transceiver);
1729 }
1730 return all_transceivers;
1731}
1732
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001734 MediaStreamTrackInterface* track,
1735 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001736 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001737 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001738 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001739 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001740 return false;
1741 }
1742
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001743 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001744 // The StatsCollector is used to tell if a track is valid because it may
1745 // remember tracks that the PeerConnection previously removed.
1746 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001747 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1748 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001749 return false;
1750 }
Steve Antonad182762018-09-05 20:22:40 +00001751 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1752 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001753 return true;
1754}
1755
hbos74e1a4f2016-09-15 23:33:01 -07001756void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001757 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001758 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001759 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001760 stats_collector_->GetStatsReport(callback);
1761}
1762
Henrik Boström1df1bf82018-03-20 13:24:20 +01001763void PeerConnection::GetStats(
1764 rtc::scoped_refptr<RtpSenderInterface> selector,
1765 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1766 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1767 RTC_DCHECK(callback);
1768 RTC_DCHECK(stats_collector_);
1769 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1770 if (selector) {
1771 for (const auto& proxy_transceiver : transceivers_) {
1772 for (const auto& proxy_sender :
1773 proxy_transceiver->internal()->senders()) {
1774 if (proxy_sender == selector) {
1775 internal_sender = proxy_sender->internal();
1776 break;
1777 }
1778 }
1779 if (internal_sender)
1780 break;
1781 }
1782 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001783 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001784 // belong to the PeerConnection (in Plan B, senders can be removed from the
1785 // PeerConnection). This means that "all the stats objects representing the
1786 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1787 // produces an empty stats report.
1788 stats_collector_->GetStatsReport(internal_sender, callback);
1789}
1790
1791void PeerConnection::GetStats(
1792 rtc::scoped_refptr<RtpReceiverInterface> selector,
1793 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1794 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1795 RTC_DCHECK(callback);
1796 RTC_DCHECK(stats_collector_);
1797 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1798 if (selector) {
1799 for (const auto& proxy_transceiver : transceivers_) {
1800 for (const auto& proxy_receiver :
1801 proxy_transceiver->internal()->receivers()) {
1802 if (proxy_receiver == selector) {
1803 internal_receiver = proxy_receiver->internal();
1804 break;
1805 }
1806 }
1807 if (internal_receiver)
1808 break;
1809 }
1810 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001811 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001812 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1813 // the PeerConnection). This means that "all the stats objects representing
1814 // the selector" is an empty set. Invoking GetStatsReport() with a null
1815 // selector produces an empty stats report.
1816 stats_collector_->GetStatsReport(internal_receiver, callback);
1817}
1818
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001819PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001820 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821 return signaling_state_;
1822}
1823
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001824PeerConnectionInterface::IceConnectionState
1825PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001826 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 return ice_connection_state_;
1828}
1829
Alex Loiko9289eda2018-11-23 16:18:59 +00001830PeerConnectionInterface::IceConnectionState
1831PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001832 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001833 return standardized_ice_connection_state_;
1834}
1835
Jonas Olsson635474e2018-10-18 15:58:17 +02001836PeerConnectionInterface::PeerConnectionState
1837PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001838 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001839 return connection_state_;
1840}
1841
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001842PeerConnectionInterface::IceGatheringState
1843PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001844 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001845 return ice_gathering_state_;
1846}
1847
Yves Gerey665174f2018-06-19 15:03:05 +02001848rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001849 const std::string& label,
1850 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001851 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001852 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001853
deadbeefab9b2d12015-10-14 11:33:11 -07001854 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001855
kwibergd1fe2812016-04-27 06:47:29 -07001856 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001857 if (config) {
1858 internal_config.reset(new InternalDataChannelInit(*config));
1859 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001860 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001861 InternalCreateDataChannel(label, internal_config.get()));
1862 if (!channel.get()) {
1863 return nullptr;
1864 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001866 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1867 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001868 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001869 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001870 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001871 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001872 return DataChannelProxy::Create(signaling_thread(), channel.get());
1873}
1874
1875void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001876 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001877 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001878 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001879
nisse7ce109a2017-01-31 00:57:56 -08001880 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001881 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001882 return;
1883 }
deadbeefab9b2d12015-10-14 11:33:11 -07001884
Steve Anton8d3444d2017-10-20 15:30:51 -07001885 if (IsClosed()) {
1886 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001887 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001888 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001889 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001890 return;
1891 }
1892
zhihuang1c378ed2017-08-17 14:10:50 -07001893 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001894 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001895 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001896 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001897 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001898 return;
1899 }
1900
Steve Anton22da89f2018-01-25 13:58:07 -08001901 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1902 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1903 if (IsUnifiedPlan()) {
1904 RTCError error = HandleLegacyOfferOptions(options);
1905 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001906 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001907 return;
1908 }
1909 }
1910
zhihuang1c378ed2017-08-17 14:10:50 -07001911 cricket::MediaSessionOptions session_options;
1912 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001913 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914}
1915
Steve Anton22da89f2018-01-25 13:58:07 -08001916RTCError PeerConnection::HandleLegacyOfferOptions(
1917 const RTCOfferAnswerOptions& options) {
1918 RTC_DCHECK(IsUnifiedPlan());
1919
1920 if (options.offer_to_receive_audio == 0) {
1921 RemoveRecvDirectionFromReceivingTransceiversOfType(
1922 cricket::MEDIA_TYPE_AUDIO);
1923 } else if (options.offer_to_receive_audio == 1) {
1924 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1925 } else if (options.offer_to_receive_audio > 1) {
1926 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1927 "offer_to_receive_audio > 1 is not supported.");
1928 }
1929
1930 if (options.offer_to_receive_video == 0) {
1931 RemoveRecvDirectionFromReceivingTransceiversOfType(
1932 cricket::MEDIA_TYPE_VIDEO);
1933 } else if (options.offer_to_receive_video == 1) {
1934 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1935 } else if (options.offer_to_receive_video > 1) {
1936 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1937 "offer_to_receive_video > 1 is not supported.");
1938 }
1939
1940 return RTCError::OK();
1941}
1942
1943void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1944 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001945 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001946 RtpTransceiverDirection new_direction =
1947 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1948 if (new_direction != transceiver->direction()) {
1949 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1950 << " transceiver (MID="
1951 << transceiver->mid().value_or("<not set>") << ") from "
1952 << RtpTransceiverDirectionToString(
1953 transceiver->direction())
1954 << " to "
1955 << RtpTransceiverDirectionToString(new_direction)
1956 << " since CreateOffer specified offer_to_receive=0";
1957 transceiver->internal()->set_direction(new_direction);
1958 }
Steve Anton22da89f2018-01-25 13:58:07 -08001959 }
1960}
1961
1962void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1963 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001964 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08001965 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001966 RTC_LOG(LS_INFO)
1967 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1968 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001969 RtpTransceiverInit init;
1970 init.direction = RtpTransceiverDirection::kRecvOnly;
1971 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1972 }
1973}
1974
1975std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1976PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1977 std::vector<
1978 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1979 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001980 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001981 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001982 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1983 receiving_transceivers.push_back(transceiver);
1984 }
1985 }
1986 return receiving_transceivers;
1987}
1988
htaa2a49d92016-03-04 02:51:39 -08001989void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1990 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001991 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08001992 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001993 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001994 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001995 return;
1996 }
1997
Steve Antondffead82018-02-06 10:31:29 -08001998 if (!(signaling_state_ == kHaveRemoteOffer ||
1999 signaling_state_ == kHaveLocalPrAnswer)) {
2000 std::string error =
2001 "PeerConnection cannot create an answer in a state other than "
2002 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002003 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002004 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002005 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002006 return;
2007 }
2008
Steve Antondffead82018-02-06 10:31:29 -08002009 // The remote description should be set if we're in the right state.
2010 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002011
Steve Anton22da89f2018-01-25 13:58:07 -08002012 if (IsUnifiedPlan()) {
2013 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2014 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2015 "supported with Unified Plan semantics. Use the "
2016 "RtpTransceiver API instead.";
2017 }
2018 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2019 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2020 "supported with Unified Plan semantics. Use the "
2021 "RtpTransceiver API instead.";
2022 }
2023 }
2024
htaa2a49d92016-03-04 02:51:39 -08002025 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002026 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002027
Steve Antond25da372017-11-06 14:50:29 -08002028 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029}
2030
2031void PeerConnection::SetLocalDescription(
2032 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002033 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002034 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002035 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002036
Steve Anton80dd7b52018-02-16 17:08:42 -08002037 // The SetLocalDescription contract is that we take ownership of the session
2038 // description regardless of the outcome, so wrap it in a unique_ptr right
2039 // away. Ideally, SetLocalDescription's signature will be changed to take the
2040 // description as a unique_ptr argument to formalize this agreement.
2041 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2042
nisse7ce109a2017-01-31 00:57:56 -08002043 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002044 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045 return;
2046 }
Steve Anton8a006912017-12-04 15:25:56 -08002047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002049 PostSetSessionDescriptionFailure(
2050 observer,
2051 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002052 return;
2053 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002054
Steve Anton80dd7b52018-02-16 17:08:42 -08002055 // If a session error has occurred the PeerConnection is in a possibly
2056 // inconsistent state so fail right away.
2057 if (session_error() != SessionError::kNone) {
2058 std::string error_message = GetSessionErrorMsg();
2059 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002060 PostSetSessionDescriptionFailure(
2061 observer,
2062 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002063 return;
2064 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002065
Steve Anton80dd7b52018-02-16 17:08:42 -08002066 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2067 if (!error.ok()) {
2068 std::string error_message = GetSetDescriptionErrorMessage(
2069 cricket::CS_LOCAL, desc->GetType(), error);
2070 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002071 PostSetSessionDescriptionFailure(
2072 observer,
2073 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002074 return;
2075 }
2076
2077 // Grab the description type before moving ownership to ApplyLocalDescription,
2078 // which may destroy it before returning.
2079 const SdpType type = desc->GetType();
2080
2081 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002082 // |desc| may be destroyed at this point.
2083
2084 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002085 // If ApplyLocalDescription fails, the PeerConnection could be in an
2086 // inconsistent state, so act conservatively here and set the session error
2087 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2088 SetSessionError(SessionError::kContent, error.message());
2089 std::string error_message =
2090 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2091 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002092 PostSetSessionDescriptionFailure(
2093 observer,
2094 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002095 return;
2096 }
Steve Anton8a006912017-12-04 15:25:56 -08002097 RTC_DCHECK(local_description());
2098
2099 PostSetSessionDescriptionSuccess(observer);
2100
Steve Antonad182762018-09-05 20:22:40 +00002101 // MaybeStartGathering needs to be called after posting
2102 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2103 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002104 transport_controller_->MaybeStartGathering();
2105
Steve Antona3a92c22017-12-07 10:27:41 -08002106 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002107 // TODO(deadbeef): We already had to hop to the network thread for
2108 // MaybeStartGathering...
2109 network_thread()->Invoke<void>(
2110 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2111 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002112 // Make UMA notes about what was agreed to.
2113 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002114 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002115 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002116}
2117
2118RTCError PeerConnection::ApplyLocalDescription(
2119 std::unique_ptr<SessionDescriptionInterface> desc) {
2120 RTC_DCHECK_RUN_ON(signaling_thread());
2121 RTC_DCHECK(desc);
2122
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123 // Update stats here so that we have the most recent stats for tracks and
2124 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002125 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002126
Steve Antondcc3c022017-12-22 16:02:54 -08002127 // Take a reference to the old local description since it's used below to
2128 // compare against the new local description. When setting the new local
2129 // description, grab ownership of the replaced session description in case it
2130 // is the same as |old_local_description|, to keep it alive for the duration
2131 // of the method.
2132 const SessionDescriptionInterface* old_local_description =
2133 local_description();
2134 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002135 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002136 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002137 replaced_local_description = pending_local_description_
2138 ? std::move(pending_local_description_)
2139 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002140 current_local_description_ = std::move(desc);
2141 pending_local_description_ = nullptr;
2142 current_remote_description_ = std::move(pending_remote_description_);
2143 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002144 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002145 pending_local_description_ = std::move(desc);
2146 }
2147 // The session description to apply now must be accessed by
2148 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002149 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002150
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002151 if (!is_caller_) {
2152 if (remote_description()) {
2153 // Remote description was applied first, so this PC is the callee.
2154 is_caller_ = false;
2155 } else {
2156 // Local description is applied first, so this PC is the caller.
2157 is_caller_ = true;
2158 }
2159 }
2160
Zhi Huange830e682018-03-30 10:48:35 -07002161 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2162 if (!error.ok()) {
2163 return error;
2164 }
2165
Steve Antondcc3c022017-12-22 16:02:54 -08002166 if (IsUnifiedPlan()) {
2167 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002168 cricket::CS_LOCAL, *local_description(), old_local_description,
2169 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002170 if (!error.ok()) {
2171 return error;
2172 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002173 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2174 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002175 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002176 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2177 // Note that code paths that don't set MID won't be able to use
2178 // information about DTLS transports.
2179 if (transceiver->mid()) {
2180 auto dtls_transport =
2181 LookupDtlsTransportByMidInternal(*transceiver->mid());
2182 transceiver->internal()->sender_internal()->set_transport(
2183 dtls_transport);
2184 transceiver->internal()->receiver_internal()->set_transport(
2185 dtls_transport);
2186 }
2187
Steve Antondcc3c022017-12-22 16:02:54 -08002188 const ContentInfo* content =
2189 FindMediaSectionForTransceiver(transceiver, local_description());
2190 if (!content) {
2191 continue;
2192 }
2193 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002194 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2195 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002196 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002197 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2198 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2199 // "recvonly", process the removal of a remote track for the media
2200 // description, given transceiver, removeList, and muteTracks.
2201 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2202 (transceiver->internal()->fired_direction() &&
2203 RtpTransceiverDirectionHasRecv(
2204 *transceiver->internal()->fired_direction()))) {
2205 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2206 &removed_streams);
2207 }
2208 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2209 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002210 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002211 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002212 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002213 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002214 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002215 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002216 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002217 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002218 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002219 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002220 }
2221 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002222 // Media channels will be created only when offer is set. These may use new
2223 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002224 if (type == SdpType::kOffer) {
2225 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2226 // description is applied. Restore back to old description.
2227 RTCError error = CreateChannels(*local_description()->description());
2228 if (!error.ok()) {
2229 return error;
2230 }
2231 }
Steve Antondcc3c022017-12-22 16:02:54 -08002232 // Remove unused channels if MediaContentDescription is rejected.
2233 RemoveUnusedChannels(local_description()->description());
2234 }
Steve Anton8a006912017-12-04 15:25:56 -08002235
Zhi Huange830e682018-03-30 10:48:35 -07002236 error = UpdateSessionState(type, cricket::CS_LOCAL,
2237 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002238 if (!error.ok()) {
2239 return error;
2240 }
Steve Antondcc3c022017-12-22 16:02:54 -08002241
Steve Anton8a006912017-12-04 15:25:56 -08002242 if (remote_description()) {
2243 // Now that we have a local description, we can push down remote candidates.
2244 UseCandidatesInSessionDescription(remote_description());
2245 }
2246
2247 pending_ice_restarts_.clear();
2248 if (session_error() != SessionError::kNone) {
2249 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2250 }
2251
deadbeefab9b2d12015-10-14 11:33:11 -07002252 // If setting the description decided our SSL role, allocate any necessary
2253 // SCTP sids.
2254 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002255 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002256 AllocateSctpSids(role);
2257 }
2258
Steve Antond3679212018-01-17 17:41:02 -08002259 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002260 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002261 const ContentInfo* content =
2262 FindMediaSectionForTransceiver(transceiver, local_description());
2263 if (!content) {
2264 continue;
2265 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002266 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2267 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002268 // 0 is a special value meaning "this sender has no associated send
2269 // stream". Need to call this so the sender won't attempt to configure
2270 // a no longer existing stream and run into DCHECKs in the lower
2271 // layers.
2272 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002273 } else {
2274 // Get the StreamParams from the channel which could generate SSRCs.
2275 const std::vector<StreamParams>& streams = channel->local_streams();
2276 transceiver->internal()->sender_internal()->set_stream_ids(
2277 streams[0].stream_ids());
2278 transceiver->internal()->sender_internal()->SetSsrc(
2279 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002280 }
2281 }
2282 } else {
2283 // Plan B semantics.
2284
Steve Antondcc3c022017-12-22 16:02:54 -08002285 // Update state and SSRC of local MediaStreams and DataChannels based on the
2286 // local session description.
2287 const cricket::ContentInfo* audio_content =
2288 GetFirstAudioContent(local_description()->description());
2289 if (audio_content) {
2290 if (audio_content->rejected) {
2291 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2292 } else {
2293 const cricket::AudioContentDescription* audio_desc =
2294 audio_content->media_description()->as_audio();
2295 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2296 }
deadbeeffaac4972015-11-12 15:33:07 -08002297 }
deadbeefab9b2d12015-10-14 11:33:11 -07002298
Steve Antondcc3c022017-12-22 16:02:54 -08002299 const cricket::ContentInfo* video_content =
2300 GetFirstVideoContent(local_description()->description());
2301 if (video_content) {
2302 if (video_content->rejected) {
2303 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2304 } else {
2305 const cricket::VideoContentDescription* video_desc =
2306 video_content->media_description()->as_video();
2307 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2308 }
deadbeeffaac4972015-11-12 15:33:07 -08002309 }
deadbeefab9b2d12015-10-14 11:33:11 -07002310 }
2311
2312 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002313 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002314 if (data_content) {
2315 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002316 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002317 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002318 cricket::kMediaProtocolRtpPrefix)) {
2319 UpdateLocalRtpDataChannels(data_desc->streams());
2320 }
2321 }
2322
Steve Anton8a006912017-12-04 15:25:56 -08002323 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002324}
2325
Steve Anton06817cd2018-12-18 15:55:30 -08002326// The SDP parser used to populate these values by default for the 'content
2327// name' if an a=mid line was absent.
2328static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2329 switch (media_type) {
2330 case cricket::MEDIA_TYPE_AUDIO:
2331 return cricket::CN_AUDIO;
2332 case cricket::MEDIA_TYPE_VIDEO:
2333 return cricket::CN_VIDEO;
2334 case cricket::MEDIA_TYPE_DATA:
2335 return cricket::CN_DATA;
2336 }
2337 RTC_NOTREACHED();
2338 return "";
2339}
2340
2341void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002342 cricket::SessionDescription* new_remote_description) {
2343 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002344 const cricket::ContentInfos& local_contents =
2345 (local_description() ? local_description()->description()->contents()
2346 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002347 const cricket::ContentInfos& remote_contents =
2348 (remote_description() ? remote_description()->description()->contents()
2349 : cricket::ContentInfos());
2350 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2351 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002352 if (!content.name.empty()) {
2353 continue;
2354 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002355 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002356 absl::string_view source_explanation;
2357 if (IsUnifiedPlan()) {
2358 if (i < local_contents.size()) {
2359 new_mid = local_contents[i].name;
2360 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002361 } else if (i < remote_contents.size()) {
2362 new_mid = remote_contents[i].name;
2363 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002364 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002365 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002366 source_explanation = "generated just now";
2367 }
2368 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002369 new_mid = std::string(
2370 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002371 source_explanation = "to match pre-existing behavior";
2372 }
Steve Antond7180cc2019-02-07 10:44:53 -08002373 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002374 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002375 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002376 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2377 << " is missing an a=mid line. Filling in the value '"
2378 << new_mid << "' " << source_explanation << ".";
2379 }
2380}
2381
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002382void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002383 SetSessionDescriptionObserver* observer,
2384 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002385 SetRemoteDescription(
2386 std::unique_ptr<SessionDescriptionInterface>(desc),
2387 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2388 new SetRemoteDescriptionObserverAdapter(this, observer)));
2389}
2390
2391void PeerConnection::SetRemoteDescription(
2392 std::unique_ptr<SessionDescriptionInterface> desc,
2393 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002394 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002395 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002396
nisse7ce109a2017-01-31 00:57:56 -08002397 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002398 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 return;
2400 }
Steve Anton8a006912017-12-04 15:25:56 -08002401
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002403 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002404 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002405 return;
2406 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002407
Steve Anton80dd7b52018-02-16 17:08:42 -08002408 // If a session error has occurred the PeerConnection is in a possibly
2409 // inconsistent state so fail right away.
2410 if (session_error() != SessionError::kNone) {
2411 std::string error_message = GetSessionErrorMsg();
2412 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2413 observer->OnSetRemoteDescriptionComplete(
2414 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2415 return;
2416 }
Steve Anton71439a62018-02-15 11:53:06 -08002417
Steve Antonba42e992018-04-09 14:10:01 -07002418 if (desc->GetType() == SdpType::kOffer) {
2419 // Report to UMA the format of the received offer.
2420 ReportSdpFormatReceived(*desc);
2421 }
2422
Steve Anton06817cd2018-12-18 15:55:30 -08002423 // Handle remote descriptions missing a=mid lines for interop with legacy end
2424 // points.
2425 FillInMissingRemoteMids(desc->description());
2426
Steve Anton80dd7b52018-02-16 17:08:42 -08002427 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002428 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002429 std::string error_message = GetSetDescriptionErrorMessage(
2430 cricket::CS_REMOTE, desc->GetType(), error);
2431 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002432 observer->OnSetRemoteDescriptionComplete(
2433 RTCError(error.type(), std::move(error_message)));
2434 return;
2435 }
Steve Anton71439a62018-02-15 11:53:06 -08002436
Steve Anton80dd7b52018-02-16 17:08:42 -08002437 // Grab the description type before moving ownership to
2438 // ApplyRemoteDescription, which may destroy it before returning.
2439 const SdpType type = desc->GetType();
2440
2441 error = ApplyRemoteDescription(std::move(desc));
2442 // |desc| may be destroyed at this point.
2443
2444 if (!error.ok()) {
2445 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2446 // inconsistent state, so act conservatively here and set the session error
2447 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2448 SetSessionError(SessionError::kContent, error.message());
2449 std::string error_message =
2450 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2451 RTC_LOG(LS_ERROR) << error_message;
2452 observer->OnSetRemoteDescriptionComplete(
2453 RTCError(error.type(), std::move(error_message)));
2454 return;
2455 }
2456 RTC_DCHECK(remote_description());
2457
2458 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002459 // TODO(deadbeef): We already had to hop to the network thread for
2460 // MaybeStartGathering...
2461 network_thread()->Invoke<void>(
2462 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2463 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002464 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002465 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002466 }
2467
2468 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002469 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002470}
2471
2472RTCError PeerConnection::ApplyRemoteDescription(
2473 std::unique_ptr<SessionDescriptionInterface> desc) {
2474 RTC_DCHECK_RUN_ON(signaling_thread());
2475 RTC_DCHECK(desc);
2476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002477 // Update stats here so that we have the most recent stats for tracks and
2478 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002479 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002480
Steve Antondcc3c022017-12-22 16:02:54 -08002481 // Take a reference to the old remote description since it's used below to
2482 // compare against the new remote description. When setting the new remote
2483 // description, grab ownership of the replaced session description in case it
2484 // is the same as |old_remote_description|, to keep it alive for the duration
2485 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002486 const SessionDescriptionInterface* old_remote_description =
2487 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002488 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002489 SdpType type = desc->GetType();
2490 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002491 replaced_remote_description = pending_remote_description_
2492 ? std::move(pending_remote_description_)
2493 : std::move(current_remote_description_);
2494 current_remote_description_ = std::move(desc);
2495 pending_remote_description_ = nullptr;
2496 current_local_description_ = std::move(pending_local_description_);
2497 } else {
2498 replaced_remote_description = std::move(pending_remote_description_);
2499 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002500 }
Steve Anton8a006912017-12-04 15:25:56 -08002501 // The session description to apply now must be accessed by
2502 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002503 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002504
Zhi Huange830e682018-03-30 10:48:35 -07002505 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2506 if (!error.ok()) {
2507 return error;
2508 }
Steve Anton8a006912017-12-04 15:25:56 -08002509 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002510 if (IsUnifiedPlan()) {
2511 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002512 cricket::CS_REMOTE, *remote_description(), local_description(),
2513 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002514 if (!error.ok()) {
2515 return error;
2516 }
Steve Antondcc3c022017-12-22 16:02:54 -08002517 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002518 // Media channels will be created only when offer is set. These may use new
2519 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002520 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002521 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002522 // description is applied. Restore back to old description.
2523 RTCError error = CreateChannels(*remote_description()->description());
2524 if (!error.ok()) {
2525 return error;
2526 }
2527 }
Steve Antondcc3c022017-12-22 16:02:54 -08002528 // Remove unused channels if MediaContentDescription is rejected.
2529 RemoveUnusedChannels(remote_description()->description());
2530 }
Steve Anton8a006912017-12-04 15:25:56 -08002531
Zhi Huange830e682018-03-30 10:48:35 -07002532 // NOTE: Candidates allocation will be initiated only when
2533 // SetLocalDescription is called.
2534 error = UpdateSessionState(type, cricket::CS_REMOTE,
2535 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002536 if (!error.ok()) {
2537 return error;
2538 }
2539
2540 if (local_description() &&
2541 !UseCandidatesInSessionDescription(remote_description())) {
2542 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2543 }
2544
2545 if (old_remote_description) {
2546 for (const cricket::ContentInfo& content :
2547 old_remote_description->description()->contents()) {
2548 // Check if this new SessionDescription contains new ICE ufrag and
2549 // password that indicates the remote peer requests an ICE restart.
2550 // TODO(deadbeef): When we start storing both the current and pending
2551 // remote description, this should reset pending_ice_restarts and compare
2552 // against the current description.
2553 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2554 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002555 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002556 pending_ice_restarts_.insert(content.name);
2557 }
2558 } else {
2559 // We retain all received candidates only if ICE is not restarted.
2560 // When ICE is restarted, all previous candidates belong to an old
2561 // generation and should not be kept.
2562 // TODO(deadbeef): This goes against the W3C spec which says the remote
2563 // description should only contain candidates from the last set remote
2564 // description plus any candidates added since then. We should remove
2565 // this once we're sure it won't break anything.
2566 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2567 old_remote_description, content.name, mutable_remote_description());
2568 }
2569 }
2570 }
2571
2572 if (session_error() != SessionError::kNone) {
2573 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2574 }
2575
2576 // Set the the ICE connection state to connecting since the connection may
2577 // become writable with peer reflexive candidates before any remote candidate
2578 // is signaled.
2579 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2580 // is to have a new signal the indicates a change in checking state from the
2581 // transport and expose a new checking() member from transport that can be
2582 // read to determine the current checking state. The existing SignalConnecting
2583 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002584 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002585 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002586 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2587 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2588 }
2589
deadbeefab9b2d12015-10-14 11:33:11 -07002590 // If setting the description decided our SSL role, allocate any necessary
2591 // SCTP sids.
2592 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002593 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002594 AllocateSctpSids(role);
2595 }
2596
Steve Antondcc3c022017-12-22 16:02:54 -08002597 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002598 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002599 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002600 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002601 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002602 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002603 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002604 const ContentInfo* content =
2605 FindMediaSectionForTransceiver(transceiver, remote_description());
2606 if (!content) {
2607 continue;
2608 }
2609 const MediaContentDescription* media_desc = content->media_description();
2610 RtpTransceiverDirection local_direction =
2611 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002612 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2613 // RTCSessionDescription: Set the associated remote streams given
2614 // transceiver.[[Receiver]], msids, addList, and removeList".
2615 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2616 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2617 std::vector<std::string> stream_ids;
2618 if (!media_desc->streams().empty()) {
2619 // The remote description has signaled the stream IDs.
2620 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002621 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002622 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2623 << " (" << GetStreamIdsString(stream_ids) << ").";
2624 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2625 stream_ids, &added_streams,
2626 &removed_streams);
2627 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2628 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2629 // and transceiver's current direction is neither sendrecv nor recvonly,
2630 // process the addition of a remote track for the media description.
2631 if (!transceiver->fired_direction() ||
2632 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2633 RTC_LOG(LS_INFO)
2634 << "Processing the addition of a remote track for MID="
2635 << content->name << ".";
2636 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002637 }
Steve Antondcc3c022017-12-22 16:02:54 -08002638 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002639 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002640 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2641 // removal of a remote track for the media description, given transceiver,
2642 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002643 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002644 (transceiver->fired_direction() &&
2645 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2646 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2647 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002648 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002649 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002650 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002651 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002652 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002653 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002654 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002655 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002656 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002657 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2658 if (transceiver->mid()) {
2659 auto dtls_transport =
2660 LookupDtlsTransportByMidInternal(*transceiver->mid());
2661 transceiver->internal()->sender_internal()->set_transport(
2662 dtls_transport);
2663 transceiver->internal()->receiver_internal()->set_transport(
2664 dtls_transport);
2665 }
Steve Antondcc3c022017-12-22 16:02:54 -08002666 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002667 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002668 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002669 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002670 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2671 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002672 transceiver->Stop();
2673 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002674 if (!content->rejected &&
2675 RtpTransceiverDirectionHasRecv(local_direction)) {
2676 // Set ssrc to 0 in the case of an unsignalled ssrc.
2677 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002678 if (!media_desc->streams().empty() &&
2679 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002680 ssrc = media_desc->streams()[0].first_ssrc();
2681 }
2682 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002683 }
Steve Antondcc3c022017-12-22 16:02:54 -08002684 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002685 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002686 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002687 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002688 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002689 observer->OnTrack(transceiver);
2690 observer->OnAddTrack(transceiver->receiver(),
2691 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002692 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002693 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002694 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002695 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002696 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002697 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002698 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002699 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002700 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002701 }
Steve Antondcc3c022017-12-22 16:02:54 -08002702 }
2703
Henrik Boströmfdb92012017-11-09 19:55:44 +01002704 const cricket::ContentInfo* audio_content =
2705 GetFirstAudioContent(remote_description()->description());
2706 const cricket::ContentInfo* video_content =
2707 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002708 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002709 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002710 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002711 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002712 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002713 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002714
2715 // Check if the descriptions include streams, just in case the peer supports
2716 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002717 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002718 (audio_desc && !audio_desc->streams().empty()) ||
2719 (video_desc && !video_desc->streams().empty())) {
2720 remote_peer_supports_msid_ = true;
2721 }
deadbeefab9b2d12015-10-14 11:33:11 -07002722
2723 // We wait to signal new streams until we finish processing the description,
2724 // since only at that point will new streams have all their tracks.
2725 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2726
Steve Antondcc3c022017-12-22 16:02:54 -08002727 if (!IsUnifiedPlan()) {
2728 // TODO(steveanton): When removing RTP senders/receivers in response to a
2729 // rejected media section, there is some cleanup logic that expects the
2730 // voice/ video channel to still be set. But in this method the voice/video
2731 // channel would have been destroyed by the SetRemoteDescription caller
2732 // above so the cleanup that relies on them fails to run. The RemoveSenders
2733 // calls should be moved to right before the DestroyChannel calls to fix
2734 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002735
Steve Antondcc3c022017-12-22 16:02:54 -08002736 // Find all audio rtp streams and create corresponding remote AudioTracks
2737 // and MediaStreams.
2738 if (audio_content) {
2739 if (audio_content->rejected) {
2740 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2741 } else {
2742 bool default_audio_track_needed =
2743 !remote_peer_supports_msid_ &&
2744 RtpTransceiverDirectionHasSend(audio_desc->direction());
2745 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2746 default_audio_track_needed, audio_desc->type(),
2747 new_streams);
2748 }
deadbeeffaac4972015-11-12 15:33:07 -08002749 }
deadbeefab9b2d12015-10-14 11:33:11 -07002750
Steve Antondcc3c022017-12-22 16:02:54 -08002751 // Find all video rtp streams and create corresponding remote VideoTracks
2752 // and MediaStreams.
2753 if (video_content) {
2754 if (video_content->rejected) {
2755 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2756 } else {
2757 bool default_video_track_needed =
2758 !remote_peer_supports_msid_ &&
2759 RtpTransceiverDirectionHasSend(video_desc->direction());
2760 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2761 default_video_track_needed, video_desc->type(),
2762 new_streams);
2763 }
deadbeeffaac4972015-11-12 15:33:07 -08002764 }
deadbeefab9b2d12015-10-14 11:33:11 -07002765
Steve Antondcc3c022017-12-22 16:02:54 -08002766 // Update the DataChannels with the information from the remote peer.
2767 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002768 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002769 cricket::kMediaProtocolRtpPrefix)) {
2770 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2771 }
deadbeefab9b2d12015-10-14 11:33:11 -07002772 }
deadbeefab9b2d12015-10-14 11:33:11 -07002773
Steve Antondcc3c022017-12-22 16:02:54 -08002774 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002775 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002776 for (size_t i = 0; i < new_streams->count(); ++i) {
2777 MediaStreamInterface* new_stream = new_streams->at(i);
2778 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002779 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002780 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2781 }
deadbeefab9b2d12015-10-14 11:33:11 -07002782
Steve Antondcc3c022017-12-22 16:02:54 -08002783 UpdateEndedRemoteMediaStreams();
2784 }
deadbeefab9b2d12015-10-14 11:33:11 -07002785
Steve Anton8a006912017-12-04 15:25:56 -08002786 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002787}
2788
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002789void PeerConnection::SetAssociatedRemoteStreams(
2790 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2791 const std::vector<std::string>& stream_ids,
2792 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2793 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2794 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2795 for (const std::string& stream_id : stream_ids) {
2796 rtc::scoped_refptr<MediaStreamInterface> stream =
2797 remote_streams_->find(stream_id);
2798 if (!stream) {
2799 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2800 MediaStream::Create(stream_id));
2801 remote_streams_->AddStream(stream);
2802 added_streams->push_back(stream);
2803 }
2804 media_streams.push_back(stream);
2805 }
2806 // Special case: "a=msid" missing, use random stream ID.
2807 if (media_streams.empty() &&
2808 !(remote_description()->description()->msid_signaling() &
2809 cricket::kMsidSignalingMediaSection)) {
2810 if (!missing_msid_default_stream_) {
2811 missing_msid_default_stream_ = MediaStreamProxy::Create(
2812 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2813 added_streams->push_back(missing_msid_default_stream_);
2814 }
2815 media_streams.push_back(missing_msid_default_stream_);
2816 }
2817 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2818 receiver->streams();
2819 // SetStreams() will add/remove the receiver's track to/from the streams. This
2820 // differs from the spec - the spec uses an "addList" and "removeList" to
2821 // update the stream-track relationships in a later step. We do this earlier,
2822 // changing the order of things, but the end-result is the same.
2823 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2824 // instead. https://crbug.com/webrtc/9480
2825 receiver->SetStreams(media_streams);
2826 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2827}
2828
Steve Anton0f5400a2018-07-17 14:25:36 -07002829void PeerConnection::ProcessRemovalOfRemoteTrack(
2830 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2831 transceiver,
2832 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2833 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2834 RTC_DCHECK(transceiver->mid());
2835 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2836 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002837 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002838 transceiver->internal()->receiver_internal()->streams();
2839 // This will remove the remote track from the streams.
2840 transceiver->internal()->receiver_internal()->set_stream_ids({});
2841 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002842 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2843}
2844
2845void PeerConnection::RemoveRemoteStreamsIfEmpty(
2846 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2847 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2848 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2849 // streams, see if the stream was removed by checking if this was the last
2850 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002851 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002852 if (remote_stream->GetAudioTracks().empty() &&
2853 remote_stream->GetVideoTracks().empty()) {
2854 remote_streams_->RemoveStream(remote_stream);
2855 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002856 }
2857 }
2858}
2859
Steve Antondcc3c022017-12-22 16:02:54 -08002860RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2861 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002862 const SessionDescriptionInterface& new_session,
2863 const SessionDescriptionInterface* old_local_description,
2864 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002865 RTC_DCHECK(IsUnifiedPlan());
2866
Steve Anton7464fca2018-01-19 11:10:37 -08002867 const cricket::ContentGroup* bundle_group = nullptr;
2868 if (new_session.GetType() == SdpType::kOffer) {
2869 auto bundle_group_or_error =
2870 GetEarlyBundleGroup(*new_session.description());
2871 if (!bundle_group_or_error.ok()) {
2872 return bundle_group_or_error.MoveError();
2873 }
2874 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002875 }
Steve Antondcc3c022017-12-22 16:02:54 -08002876
Steve Antondcc3c022017-12-22 16:02:54 -08002877 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002878 for (size_t i = 0; i < new_contents.size(); ++i) {
2879 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002880 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002881 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002882 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2883 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002884 const cricket::ContentInfo* old_local_content = nullptr;
2885 if (old_local_description &&
2886 i < old_local_description->description()->contents().size()) {
2887 old_local_content =
2888 &old_local_description->description()->contents()[i];
2889 }
2890 const cricket::ContentInfo* old_remote_content = nullptr;
2891 if (old_remote_description &&
2892 i < old_remote_description->description()->contents().size()) {
2893 old_remote_content =
2894 &old_remote_description->description()->contents()[i];
2895 }
Steve Antondcc3c022017-12-22 16:02:54 -08002896 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002897 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2898 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002899 if (!transceiver_or_error.ok()) {
2900 return transceiver_or_error.MoveError();
2901 }
2902 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002903 RTCError error =
2904 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2905 if (!error.ok()) {
2906 return error;
2907 }
2908 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002909 if (GetDataMid() && new_content.name != *GetDataMid()) {
2910 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002911 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2912 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002913 continue;
2914 }
2915 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2916 if (!error.ok()) {
2917 return error;
2918 }
Steve Antondcc3c022017-12-22 16:02:54 -08002919 } else {
2920 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2921 "Unknown section type.");
2922 }
2923 }
2924
2925 return RTCError::OK();
2926}
2927
2928RTCError PeerConnection::UpdateTransceiverChannel(
2929 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2930 transceiver,
2931 const cricket::ContentInfo& content,
2932 const cricket::ContentGroup* bundle_group) {
2933 RTC_DCHECK(IsUnifiedPlan());
2934 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002935 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002936 if (content.rejected) {
2937 if (channel) {
2938 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002939 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002940 }
2941 } else {
2942 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002943 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002944 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002945 } else {
Steve Anton69470252018-02-09 11:43:08 -08002946 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002947 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002948 }
2949 if (!channel) {
2950 LOG_AND_RETURN_ERROR(
2951 RTCErrorType::INTERNAL_ERROR,
2952 "Failed to create channel for mid=" + content.name);
2953 }
2954 transceiver->internal()->SetChannel(channel);
2955 }
2956 }
2957 return RTCError::OK();
2958}
2959
Steve Antonfa2260d2017-12-28 16:38:23 -08002960RTCError PeerConnection::UpdateDataChannel(
2961 cricket::ContentSource source,
2962 const cricket::ContentInfo& content,
2963 const cricket::ContentGroup* bundle_group) {
2964 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002965 // If data channels are disabled, ignore this media section. CreateAnswer
2966 // will take care of rejecting it.
2967 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002968 }
2969 if (content.rejected) {
2970 DestroyDataChannel();
2971 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002972 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002973 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002974 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2975 "Failed to create data channel.");
2976 }
2977 }
2978 if (source == cricket::CS_REMOTE) {
2979 const MediaContentDescription* data_desc = content.media_description();
2980 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2981 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2982 }
2983 }
2984 }
2985 return RTCError::OK();
2986}
2987
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002988// This method will extract any send encodings that were sent by the remote
2989// connection. This is currently only relevant for Simulcast scenario (where
2990// the number of layers may be communicated by the server).
2991static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2992 const MediaContentDescription& desc) {
2993 if (!desc.HasSimulcast()) {
2994 return {};
2995 }
2996 std::vector<RtpEncodingParameters> result;
2997 const SimulcastDescription& simulcast = desc.simulcast_description();
2998
2999 // This is a remote description, the parameters we are after should appear
3000 // as receive streams.
3001 for (const auto& alternatives : simulcast.receive_layers()) {
3002 RTC_DCHECK(!alternatives.empty());
3003 // There is currently no way to specify or choose from alternatives.
3004 // We will always use the first alternative, which is the most preferred.
3005 const SimulcastLayer& layer = alternatives[0];
3006 RtpEncodingParameters parameters;
3007 parameters.rid = layer.rid;
3008 parameters.active = !layer.is_paused;
3009 result.push_back(parameters);
3010 }
3011
3012 return result;
3013}
3014
3015static RTCError UpdateSimulcastLayerStatusInSender(
3016 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003017 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003018 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003019 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003020 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003021
3022 // The simulcast envelope cannot be changed, only the status of the streams.
3023 // So we will iterate over the send encodings rather than the layers.
3024 for (RtpEncodingParameters& encoding : parameters.encodings) {
3025 auto iter = std::find_if(layers.begin(), layers.end(),
3026 [&encoding](const SimulcastLayer& layer) {
3027 return layer.rid == encoding.rid;
3028 });
3029 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003030 if (iter == layers.end()) {
3031 disabled_layers.push_back(encoding.rid);
3032 continue;
3033 }
3034
3035 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003036 }
3037
Amit Hilbuch619b2942019-02-26 15:55:19 -08003038 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003039 if (result.ok()) {
3040 result = sender->DisableEncodingLayers(disabled_layers);
3041 }
3042
3043 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003044}
3045
Amit Hilbuch2297d332019-02-19 12:49:22 -08003046static RTCError DisableSimulcastInSender(
3047 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003048 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003049 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003050 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003051 return RTCError::OK();
3052 }
3053
Amit Hilbuch2297d332019-02-19 12:49:22 -08003054 std::vector<std::string> disabled_layers;
3055 std::transform(
3056 parameters.encodings.begin() + 1, parameters.encodings.end(),
3057 std::back_inserter(disabled_layers),
3058 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3059 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003060}
3061
Steve Antondcc3c022017-12-22 16:02:54 -08003062RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3063PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003064 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003065 size_t mline_index,
3066 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003067 const ContentInfo* old_local_content,
3068 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003069 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003070 // If this is an offer then the m= section might be recycled. If the m=
3071 // section is being recycled (defined as: rejected in the current local or
3072 // remote description and not rejected in new description), dissociate the
3073 // currently associated RtpTransceiver by setting its mid property to null,
3074 // and discard the mapping between the transceiver and its m= section index.
3075 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3076 old_remote_content)) {
3077 // We want to dissociate the transceiver that has the rejected mid.
3078 const std::string& old_mid =
3079 (old_local_content && old_local_content->rejected)
3080 ? old_local_content->name
3081 : old_remote_content->name;
3082 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003083 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003084 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3085 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003086 old_transceiver->internal()->set_mid(absl::nullopt);
3087 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003088 }
3089 }
3090 const MediaContentDescription* media_desc = content.media_description();
3091 auto transceiver = GetAssociatedTransceiver(content.name);
3092 if (source == cricket::CS_LOCAL) {
3093 // Find the RtpTransceiver that corresponds to this m= section, using the
3094 // mapping between transceivers and m= section indices established when
3095 // creating the offer.
3096 if (!transceiver) {
3097 transceiver = GetTransceiverByMLineIndex(mline_index);
3098 }
3099 if (!transceiver) {
3100 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3101 "Unknown transceiver");
3102 }
3103 } else {
3104 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3105 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3106 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003107 // When simulcast is requested, a transceiver cannot be associated because
3108 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003109 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003110 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3111 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003112 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3113 }
3114 // If no RtpTransceiver was found in the previous step, create one with a
3115 // recvonly direction.
3116 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003117 RTC_LOG(LS_INFO) << "Adding "
3118 << cricket::MediaTypeToString(media_desc->type())
3119 << " transceiver for MID=" << content.name
3120 << " at i=" << mline_index
3121 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003122 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003123 std::vector<RtpEncodingParameters> send_encodings =
3124 GetSendEncodingsFromRemoteDescription(*media_desc);
3125 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3126 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003127 std::string receiver_id;
3128 if (!media_desc->streams().empty()) {
3129 receiver_id = media_desc->streams()[0].id;
3130 } else {
3131 receiver_id = rtc::CreateRandomUuid();
3132 }
3133 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003134 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003135 transceiver->internal()->set_direction(
3136 RtpTransceiverDirection::kRecvOnly);
3137 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003138
3139 // Check if the offer indicated simulcast but the answer rejected it.
3140 // This can happen when simulcast is not supported on the remote party.
3141 // This check can be simplified to comparing the number of send encodings,
3142 // but that might break legacy implementation in which simulcast is not
3143 // signaled in the remote description.
3144 if (old_local_content && old_local_content->media_description() &&
3145 old_local_content->media_description()->HasSimulcast() &&
3146 !media_desc->HasSimulcast()) {
3147 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003148 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003149 if (!error.ok()) {
3150 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3151 return std::move(error);
3152 }
3153 }
Steve Antondcc3c022017-12-22 16:02:54 -08003154 }
3155 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003156 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003157 LOG_AND_RETURN_ERROR(
3158 RTCErrorType::INVALID_PARAMETER,
3159 "Transceiver type does not match media description type.");
3160 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003161 if (media_desc->HasSimulcast()) {
3162 std::vector<SimulcastLayer> layers =
3163 source == cricket::CS_LOCAL
3164 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3165 : media_desc->simulcast_description()
3166 .receive_layers()
3167 .GetAllLayers();
3168 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003169 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003170 if (!error.ok()) {
3171 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3172 return std::move(error);
3173 }
3174 }
Steve Antondcc3c022017-12-22 16:02:54 -08003175 // Associate the found or created RtpTransceiver with the m= section by
3176 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3177 // section, and establish a mapping between the transceiver and the index of
3178 // the m= section.
3179 transceiver->internal()->set_mid(content.name);
3180 transceiver->internal()->set_mline_index(mline_index);
3181 return std::move(transceiver);
3182}
3183
3184rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3185PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3186 RTC_DCHECK(IsUnifiedPlan());
3187 for (auto transceiver : transceivers_) {
3188 if (transceiver->mid() == mid) {
3189 return transceiver;
3190 }
3191 }
3192 return nullptr;
3193}
3194
3195rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3196PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3197 RTC_DCHECK(IsUnifiedPlan());
3198 for (auto transceiver : transceivers_) {
3199 if (transceiver->internal()->mline_index() == mline_index) {
3200 return transceiver;
3201 }
3202 }
3203 return nullptr;
3204}
3205
3206rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3207PeerConnection::FindAvailableTransceiverToReceive(
3208 cricket::MediaType media_type) const {
3209 RTC_DCHECK(IsUnifiedPlan());
3210 // From JSEP section 5.10 (Applying a Remote Description):
3211 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3212 // the same type that were added to the PeerConnection by addTrack and are not
3213 // associated with any m= section and are not stopped, find the first such
3214 // RtpTransceiver.
3215 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003216 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003217 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3218 !transceiver->stopped()) {
3219 return transceiver;
3220 }
3221 }
3222 return nullptr;
3223}
3224
Steve Antoned10bd92017-12-05 10:52:59 -08003225const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3226 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3227 transceiver,
3228 const SessionDescriptionInterface* sdesc) const {
3229 RTC_DCHECK(transceiver);
3230 RTC_DCHECK(sdesc);
3231 if (IsUnifiedPlan()) {
3232 if (!transceiver->internal()->mid()) {
3233 // This transceiver is not associated with a media section yet.
3234 return nullptr;
3235 }
3236 return sdesc->description()->GetContentByName(
3237 *transceiver->internal()->mid());
3238 } else {
3239 // Plan B only allows at most one audio and one video section, so use the
3240 // first media section of that type.
3241 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003242 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003243 }
3244}
3245
deadbeef46c73892016-11-16 19:42:04 -08003246PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003247 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003248 return configuration_;
3249}
3250
deadbeef293e9262017-01-11 12:28:30 -08003251bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3252 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003253 RTC_DCHECK_RUN_ON(signaling_thread());
3254 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003255 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003256 if (IsClosed()) {
3257 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3258 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3259 }
3260
Qingsi Wanga2d60672018-04-11 16:57:45 -07003261 // According to JSEP, after setLocalDescription, changing the candidate pool
3262 // size is not allowed, and changing the set of ICE servers will not result
3263 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003264 if (local_description() && configuration.ice_candidate_pool_size !=
3265 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003266 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3267 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003268 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003269 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003270
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003271 if (local_description() &&
3272 configuration.use_media_transport != configuration_.use_media_transport) {
3273 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3274 "SetLocalDescription.";
3275 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3276 }
3277
3278 if (remote_description() &&
3279 configuration.use_media_transport != configuration_.use_media_transport) {
3280 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3281 "SetRemoteDescription.";
3282 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3283 }
3284
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003285 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003286 configuration.use_media_transport_for_data_channels !=
3287 configuration_.use_media_transport_for_data_channels) {
3288 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3289 "after calling SetLocalDescription.";
3290 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3291 }
3292
3293 if (remote_description() &&
3294 configuration.use_media_transport_for_data_channels !=
3295 configuration_.use_media_transport_for_data_channels) {
3296 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3297 "after calling SetRemoteDescription.";
3298 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3299 }
3300
3301 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003302 configuration.crypto_options != configuration_.crypto_options) {
3303 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3304 "SetLocalDescription.";
3305 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3306 }
3307
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003308 if (configuration.use_media_transport_for_data_channels ||
3309 configuration.use_media_transport) {
3310 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3311 << "Media transport requires MaxBundle policy.";
3312 }
3313
deadbeef293e9262017-01-11 12:28:30 -08003314 // The simplest (and most future-compatible) way to tell if the config was
3315 // modified in an invalid way is to copy each property we do support
3316 // modifying, then use operator==. There are far more properties we don't
3317 // support modifying than those we do, and more could be added.
3318 RTCConfiguration modified_config = configuration_;
3319 modified_config.servers = configuration.servers;
3320 modified_config.type = configuration.type;
3321 modified_config.ice_candidate_pool_size =
3322 configuration.ice_candidate_pool_size;
3323 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003324 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003325 modified_config.ice_check_interval_strong_connectivity =
3326 configuration.ice_check_interval_strong_connectivity;
3327 modified_config.ice_check_interval_weak_connectivity =
3328 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003329 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3330 modified_config.ice_unwritable_min_checks =
3331 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003332 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003333 modified_config.stun_candidate_keepalive_interval =
3334 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003335 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003336 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003337 modified_config.active_reset_srtp_params =
3338 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003339 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003340 modified_config.use_media_transport_for_data_channels =
3341 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003342 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003343 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003344 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3345 }
3346
Steve Anton038834f2017-07-14 15:59:59 -07003347 // Validate the modified configuration.
3348 RTCError validate_error = ValidateConfiguration(modified_config);
3349 if (!validate_error.ok()) {
3350 return SafeSetError(std::move(validate_error), error);
3351 }
3352
deadbeef293e9262017-01-11 12:28:30 -08003353 // Note that this isn't possible through chromium, since it's an unsigned
3354 // short in WebIDL.
3355 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003356 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003357 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3358 }
3359
3360 // Parse ICE servers before hopping to network thread.
3361 cricket::ServerAddresses stun_servers;
3362 std::vector<cricket::RelayServerConfig> turn_servers;
3363 RTCErrorType parse_error =
3364 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3365 if (parse_error != RTCErrorType::NONE) {
3366 return SafeSetError(parse_error, error);
3367 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003368 // Note if STUN or TURN servers were supplied.
3369 if (!stun_servers.empty()) {
3370 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3371 }
3372 if (!turn_servers.empty()) {
3373 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3374 }
deadbeef293e9262017-01-11 12:28:30 -08003375
3376 // In theory this shouldn't fail.
3377 if (!network_thread()->Invoke<bool>(
3378 RTC_FROM_HERE,
3379 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3380 stun_servers, turn_servers, modified_config.type,
3381 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003382 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003383 modified_config.turn_customizer,
3384 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003385 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003386 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3387 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003388
deadbeefd1a38b52016-12-10 13:15:33 -08003389 // As described in JSEP, calling setConfiguration with new ICE servers or
3390 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3391 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003392 if (modified_config.servers != configuration_.servers ||
3393 modified_config.type != configuration_.type ||
3394 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003395 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003396 }
skvladd1f5fda2017-02-03 16:54:05 -08003397
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003398 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003399 transport_controller_->SetMediaTransportSettings(
3400 modified_config.use_media_transport,
3401 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003402
Zhi Huangb57e1692018-06-12 11:41:11 -07003403 if (configuration_.active_reset_srtp_params !=
3404 modified_config.active_reset_srtp_params) {
3405 transport_controller_->SetActiveResetSrtpParams(
3406 modified_config.active_reset_srtp_params);
3407 }
3408
deadbeef293e9262017-01-11 12:28:30 -08003409 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003410 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003411 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003412}
3413
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003414bool PeerConnection::AddIceCandidate(
3415 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003416 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003417 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003418 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003419 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003420 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003421 return false;
3422 }
Steve Antond25da372017-11-06 14:50:29 -08003423
3424 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003425 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003426 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003427 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003428 return false;
3429 }
3430
3431 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003432 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003433 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003434 return false;
3435 }
3436
3437 bool valid = false;
3438 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3439 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003440 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003441 return false;
3442 }
3443
3444 // Add this candidate to the remote session description.
3445 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003446 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003447 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003448 return false;
3449 }
3450
3451 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003452 bool result = UseCandidate(ice_candidate);
3453 if (result) {
3454 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3455 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3456 } else {
3457 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3458 }
3459 return result;
Steve Antond25da372017-11-06 14:50:29 -08003460 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003461 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003462 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003463 return true;
3464 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003465}
3466
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003467bool PeerConnection::RemoveIceCandidates(
3468 const std::vector<cricket::Candidate>& candidates) {
3469 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003470 if (IsClosed()) {
3471 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3472 return false;
3473 }
3474
Steve Antond25da372017-11-06 14:50:29 -08003475 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003476 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3477 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003478 return false;
3479 }
3480
3481 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003482 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003483 return false;
3484 }
3485
3486 size_t number_removed =
3487 mutable_remote_description()->RemoveCandidates(candidates);
3488 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003489 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003490 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003491 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003492 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003493 }
3494
3495 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003496 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3497 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003498 RTC_LOG(LS_ERROR)
3499 << "RemoveIceCandidates: Error when removing remote candidates: "
3500 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003501 }
3502 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003503}
3504
Niels Möller0c4f7be2018-05-07 14:01:37 +02003505RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003506 if (!worker_thread()->IsCurrent()) {
3507 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003508 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003509 }
3510
Niels Möller0c4f7be2018-05-07 14:01:37 +02003511 const bool has_min = bitrate.min_bitrate_bps.has_value();
3512 const bool has_start = bitrate.start_bitrate_bps.has_value();
3513 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003514 if (has_min && *bitrate.min_bitrate_bps < 0) {
3515 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3516 "min_bitrate_bps <= 0");
3517 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003518 if (has_start) {
3519 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003520 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003521 "start_bitrate_bps < min_bitrate_bps");
3522 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003523 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3524 "curent_bitrate_bps < 0");
3525 }
3526 }
3527 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003528 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003529 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003530 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003531 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3533 "max_bitrate_bps < min_bitrate_bps");
3534 } else if (*bitrate.max_bitrate_bps < 0) {
3535 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3536 "max_bitrate_bps < 0");
3537 }
3538 }
3539
zstein4b979802017-06-02 14:37:37 -07003540 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003541 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003542
3543 return RTCError::OK();
3544}
3545
Alex Narest78609d52017-10-20 10:37:47 +02003546void PeerConnection::SetBitrateAllocationStrategy(
3547 std::unique_ptr<rtc::BitrateAllocationStrategy>
3548 bitrate_allocation_strategy) {
3549 rtc::Thread* worker_thread = factory_->worker_thread();
3550 if (!worker_thread->IsCurrent()) {
3551 rtc::BitrateAllocationStrategy* strategy_raw =
3552 bitrate_allocation_strategy.release();
3553 auto functor = [this, strategy_raw]() {
3554 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003555 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003556 };
3557 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3558 return;
3559 }
3560 RTC_DCHECK(call_.get());
3561 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3562}
3563
henrika5f6bf242017-11-01 11:06:56 +01003564void PeerConnection::SetAudioPlayout(bool playout) {
3565 if (!worker_thread()->IsCurrent()) {
3566 worker_thread()->Invoke<void>(
3567 RTC_FROM_HERE,
3568 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3569 return;
3570 }
3571 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003572 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003573 audio_state->SetPlayout(playout);
3574}
3575
3576void PeerConnection::SetAudioRecording(bool recording) {
3577 if (!worker_thread()->IsCurrent()) {
3578 worker_thread()->Invoke<void>(
3579 RTC_FROM_HERE,
3580 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3581 return;
3582 }
3583 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003584 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003585 audio_state->SetRecording(recording);
3586}
3587
Steve Anton8c0f7a72017-10-03 10:03:10 -07003588std::unique_ptr<rtc::SSLCertificate>
3589PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003590 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3591 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003592 return nullptr;
3593 }
Steve Antonf25303e2018-10-16 15:23:31 -07003594 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003595}
3596
Zhi Huang70b820f2018-01-27 14:16:15 -08003597std::unique_ptr<rtc::SSLCertChain>
3598PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003599 auto audio_transceiver = GetFirstAudioTransceiver();
3600 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003601 return nullptr;
3602 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003603 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003604 audio_transceiver->internal()->channel()->transport_name());
3605}
3606
3607rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3608PeerConnection::GetFirstAudioTransceiver() const {
3609 for (auto transceiver : transceivers_) {
3610 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3611 return transceiver;
3612 }
3613 }
3614 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003615}
3616
ivoc14d5dbe2016-07-04 07:06:55 -07003617bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3618 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003619 // TODO(eladalon): It would be better to not allow negative values into PC.
3620 const size_t max_size = (max_size_bytes < 0)
3621 ? RtcEventLog::kUnlimitedOutput
3622 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003623 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3624 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3625 output_period_ms = 5000;
3626 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003627 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003628 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003629 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003630}
3631
Bjorn Tereliusde939432017-11-20 17:38:14 +01003632bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3633 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003634 // TODO(eladalon): In C++14, this can be done with a lambda.
3635 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003636 bool operator()() {
3637 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3638 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003639 PeerConnection* const pc;
3640 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003641 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003642 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003643 return worker_thread()->Invoke<bool>(
3644 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003645}
3646
3647void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003648 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003649 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3650}
3651
Harald Alvestrandad88c882018-11-28 16:47:46 +01003652rtc::scoped_refptr<DtlsTransportInterface>
3653PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3654 return transport_controller_->LookupDtlsTransportByMid(mid);
3655}
3656
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003657rtc::scoped_refptr<DtlsTransport>
3658PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3659 return transport_controller_->LookupDtlsTransportByMid(mid);
3660}
3661
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003662rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3663 const {
3664 return sctp_transport_;
3665}
3666
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003667const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003668 return pending_local_description_ ? pending_local_description_.get()
3669 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003670}
3671
3672const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003673 return pending_remote_description_ ? pending_remote_description_.get()
3674 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003675}
3676
deadbeeffe4a8a42016-12-20 17:56:17 -08003677const SessionDescriptionInterface* PeerConnection::current_local_description()
3678 const {
Steve Anton75737c02017-11-06 10:37:17 -08003679 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003680}
3681
3682const SessionDescriptionInterface* PeerConnection::current_remote_description()
3683 const {
Steve Anton75737c02017-11-06 10:37:17 -08003684 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003685}
3686
3687const SessionDescriptionInterface* PeerConnection::pending_local_description()
3688 const {
Steve Anton75737c02017-11-06 10:37:17 -08003689 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003690}
3691
3692const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3693 const {
Steve Anton75737c02017-11-06 10:37:17 -08003694 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003695}
3696
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003697void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003698 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003699 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003700 // Update stats here so that we have the most recent stats for tracks and
3701 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003702 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003703
Steve Anton75737c02017-11-06 10:37:17 -08003704 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003705 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003706
Mirko Bonadei739baf02019-01-27 17:29:42 +01003707 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003708 transceiver->Stop();
3709 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003710
3711 // Ensure that all asynchronous stats requests are completed before destroying
3712 // the transport controller below.
3713 if (stats_collector_) {
3714 stats_collector_->WaitForPendingRequest();
3715 }
3716
3717 // Don't destroy BaseChannels until after stats has been cleaned up so that
3718 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003719 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003720
Qingsi Wang93a84392018-01-30 17:13:09 -08003721 // The event log is used in the transport controller, which must be outlived
3722 // by the former. CreateOffer by the peer connection is implemented
3723 // asynchronously and if the peer connection is closed without resetting the
3724 // WebRTC session description factory, the session description factory would
3725 // call the transport controller.
3726 webrtc_session_desc_factory_.reset();
3727 transport_controller_.reset();
3728
deadbeef42a42632017-03-10 15:18:00 -08003729 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003730 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3731 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003732
Steve Anton978b8762017-09-29 12:15:02 -07003733 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003734 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003735 call_.reset();
3736 // The event log must outlive call (and any other object that uses it).
3737 event_log_.reset();
3738 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003739 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003740 // The .h file says that observer can be discarded after close() returns.
3741 // Make sure this is true.
3742 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003743}
3744
Steve Antonad182762018-09-05 20:22:40 +00003745void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003746 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003747 switch (msg->message_id) {
3748 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3749 SetSessionDescriptionMsg* param =
3750 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3751 param->observer->OnSuccess();
3752 delete param;
3753 break;
3754 }
3755 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3756 SetSessionDescriptionMsg* param =
3757 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3758 param->observer->OnFailure(std::move(param->error));
3759 delete param;
3760 break;
3761 }
3762 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3763 CreateSessionDescriptionMsg* param =
3764 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3765 param->observer->OnFailure(std::move(param->error));
3766 delete param;
3767 break;
3768 }
3769 case MSG_GETSTATS: {
3770 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3771 StatsReports reports;
3772 stats_->GetStats(param->track, &reports);
3773 param->observer->OnComplete(reports);
3774 delete param;
3775 break;
3776 }
3777 case MSG_FREE_DATACHANNELS: {
3778 sctp_data_channels_to_free_.clear();
3779 break;
3780 }
3781 case MSG_REPORT_USAGE_PATTERN: {
3782 ReportUsagePattern();
3783 break;
3784 }
3785 default:
3786 RTC_NOTREACHED() << "Not implemented";
3787 break;
3788 }
3789}
3790
Steve Antonafb0bb72018-02-20 11:35:37 -08003791cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3792 RTC_DCHECK(!IsUnifiedPlan());
3793 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3794 GetAudioTransceiver()->internal()->channel());
3795 if (voice_channel) {
3796 return voice_channel->media_channel();
3797 } else {
3798 return nullptr;
3799 }
3800}
3801
3802cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3803 RTC_DCHECK(!IsUnifiedPlan());
3804 auto* video_channel = static_cast<cricket::VideoChannel*>(
3805 GetVideoTransceiver()->internal()->channel());
3806 if (video_channel) {
3807 return video_channel->media_channel();
3808 } else {
3809 return nullptr;
3810 }
3811}
3812
Steve Anton4171afb2017-11-20 10:20:22 -08003813void PeerConnection::CreateAudioReceiver(
3814 MediaStreamInterface* stream,
3815 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003816 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3817 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003818 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3819 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003820 auto* audio_receiver = new AudioRtpReceiver(
3821 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003822 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003823 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3824 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3825 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003826 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003827 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003828 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003829}
3830
Steve Anton4171afb2017-11-20 10:20:22 -08003831void PeerConnection::CreateVideoReceiver(
3832 MediaStreamInterface* stream,
3833 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003834 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3835 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003836 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3837 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003838 auto* video_receiver = new VideoRtpReceiver(
3839 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003840 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003841 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3842 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3843 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003844 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003845 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003846 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003847}
3848
deadbeef70ab1a12015-09-28 16:53:55 -07003849// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3850// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003851rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003852 const RtpSenderInfo& remote_sender_info) {
3853 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3854 if (!receiver) {
3855 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3856 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003857 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003858 }
Steve Anton4171afb2017-11-20 10:20:22 -08003859 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3860 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3861 } else {
3862 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3863 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003864 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003865}
3866
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003867void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3868 MediaStreamInterface* stream) {
3869 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003870 RTC_DCHECK(track);
3871 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003872 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003873 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003874 // We already have a sender for this track, so just change the stream_id
3875 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003876 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003877 return;
3878 }
3879
3880 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003881 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003882 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003883 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003884 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003885 // If the sender has already been configured in SDP, we call SetSsrc,
3886 // which will connect the sender to the underlying transport. This can
3887 // occur if a local session description that contains the ID of the sender
3888 // is set before AddStream is called. It can also occur if the local
3889 // session description is not changed and RemoveStream is called, and
3890 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003891 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003892 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003893 if (sender_info) {
3894 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003895 }
3896}
3897
3898// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3899// indefinitely, when we have unified plan SDP.
3900void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3901 MediaStreamInterface* stream) {
3902 RTC_DCHECK(!IsClosed());
3903 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003904 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003905 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3906 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003907 return;
3908 }
Steve Anton4171afb2017-11-20 10:20:22 -08003909 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003910}
3911
3912void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3913 MediaStreamInterface* stream) {
3914 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003915 RTC_DCHECK(track);
3916 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003917 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003918 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003919 // We already have a sender for this track, so just change the stream_id
3920 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003921 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003922 return;
3923 }
3924
3925 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003926 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003927 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003928 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003929 GetVideoTransceiver()->internal()->AddSender(new_sender);
3930 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003931 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003932 if (sender_info) {
3933 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003934 }
3935}
3936
3937void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3938 MediaStreamInterface* stream) {
3939 RTC_DCHECK(!IsClosed());
3940 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003941 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003942 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3943 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003944 return;
3945 }
Steve Anton4171afb2017-11-20 10:20:22 -08003946 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003947}
3948
Steve Antonba818672017-11-06 10:21:57 -08003949void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08003950 if (ice_connection_state_ == new_state) {
3951 return;
3952 }
3953
deadbeefcbecd352015-09-23 11:50:27 -07003954 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003955 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003956 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003957 return;
3958 }
Steve Antonba818672017-11-06 10:21:57 -08003959
Mirko Bonadei675513b2017-11-09 11:09:25 +01003960 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3961 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003962 RTC_DCHECK(ice_connection_state_ !=
3963 PeerConnectionInterface::kIceConnectionClosed);
3964
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003965 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003966 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003967}
3968
Alex Loiko9289eda2018-11-23 16:18:59 +00003969void PeerConnection::SetStandardizedIceConnectionState(
3970 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00003971 if (standardized_ice_connection_state_ == new_state)
3972 return;
3973 if (IsClosed())
3974 return;
3975 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003976 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003977}
3978
Jonas Olsson635474e2018-10-18 15:58:17 +02003979void PeerConnection::SetConnectionState(
3980 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02003981 if (connection_state_ == new_state)
3982 return;
3983 if (IsClosed())
3984 return;
3985 connection_state_ = new_state;
3986 Observer()->OnConnectionChange(new_state);
3987}
3988
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003989void PeerConnection::OnIceGatheringChange(
3990 PeerConnectionInterface::IceGatheringState new_state) {
3991 if (IsClosed()) {
3992 return;
3993 }
3994 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003995 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003996}
3997
jbauch81bf7b02017-03-25 08:31:12 -07003998void PeerConnection::OnIceCandidate(
3999 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004000 if (IsClosed()) {
4001 return;
4002 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004003 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004004 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4005 candidate->candidate().address().IsPrivateIP()) {
4006 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4007 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004008 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004009}
4010
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004011void PeerConnection::OnIceCandidatesRemoved(
4012 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004013 if (IsClosed()) {
4014 return;
4015 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004016 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004017}
4018
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004019void PeerConnection::ChangeSignalingState(
4020 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004021 if (signaling_state_ == signaling_state) {
4022 return;
4023 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004024 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4025 << GetSignalingStateString(signaling_state_)
4026 << " New state: "
4027 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004028 signaling_state_ = signaling_state;
4029 if (signaling_state == kClosed) {
4030 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004031 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004032 standardized_ice_connection_state_ =
4033 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004034 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4035 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004036 if (ice_gathering_state_ != kIceGatheringComplete) {
4037 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004038 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004039 }
4040 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004041 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004042}
4043
deadbeefeb459812015-12-15 19:24:43 -08004044void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4045 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004046 if (IsClosed()) {
4047 return;
4048 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004049 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004050 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004051}
4052
deadbeefeb459812015-12-15 19:24:43 -08004053void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4054 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004055 if (IsClosed()) {
4056 return;
4057 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004058 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004059 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004060}
4061
4062void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4063 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004064 if (IsClosed()) {
4065 return;
4066 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004067 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004068 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004069}
4070
4071void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4072 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004073 if (IsClosed()) {
4074 return;
4075 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004076 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004077 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004078}
4079
Henrik Boström31638672017-11-23 17:48:32 +01004080void PeerConnection::PostSetSessionDescriptionSuccess(
4081 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004082 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4083 signaling_thread()->Post(RTC_FROM_HERE, this,
4084 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004085}
4086
deadbeefab9b2d12015-10-14 11:33:11 -07004087void PeerConnection::PostSetSessionDescriptionFailure(
4088 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004089 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004090 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004091 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4092 msg->error = std::move(error);
4093 signaling_thread()->Post(RTC_FROM_HERE, this,
4094 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004095}
4096
4097void PeerConnection::PostCreateSessionDescriptionFailure(
4098 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004099 RTCError error) {
4100 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004101 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4102 msg->error = std::move(error);
4103 signaling_thread()->Post(RTC_FROM_HERE, this,
4104 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004105}
4106
zhihuang1c378ed2017-08-17 14:10:50 -07004107void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004108 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004109 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004110 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004111
Steve Antondcc3c022017-12-22 16:02:54 -08004112 if (IsUnifiedPlan()) {
4113 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4114 } else {
4115 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4116 }
4117
Steve Antonfa2260d2017-12-28 16:38:23 -08004118 // Intentionally unset the data channel type for RTP data channel with the
4119 // second condition. Otherwise the RTP data channels would be successfully
4120 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4121 // when building with chromium. We want to leave RTP data channels broken, so
4122 // people won't try to use them.
4123 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4124 session_options->data_channel_type = data_channel_type();
4125 }
4126
Steve Antondcc3c022017-12-22 16:02:54 -08004127 // Apply ICE restart flag and renomination flag.
4128 for (auto& options : session_options->media_description_options) {
4129 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4130 options.transport_options.enable_ice_renomination =
4131 configuration_.enable_ice_renomination;
4132 }
4133
4134 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004135 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004136 session_options->pooled_ice_credentials =
4137 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4138 RTC_FROM_HERE,
4139 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4140 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004141 session_options->offer_extmap_allow_mixed =
4142 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004143}
4144
4145void PeerConnection::GetOptionsForPlanBOffer(
4146 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4147 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004148 // Figure out transceiver directional preferences.
4149 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4150 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4151
4152 // By default, generate sendrecv/recvonly m= sections.
4153 bool recv_audio = true;
4154 bool recv_video = true;
4155
4156 // By default, only offer a new m= section if we have media to send with it.
4157 bool offer_new_audio_description = send_audio;
4158 bool offer_new_video_description = send_video;
4159 bool offer_new_data_description = HasDataChannels();
4160
4161 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004162 if (offer_answer_options.offer_to_receive_audio !=
4163 RTCOfferAnswerOptions::kUndefined) {
4164 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004165 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004166 offer_new_audio_description ||
4167 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004168 }
Steve Antondcc3c022017-12-22 16:02:54 -08004169 if (offer_answer_options.offer_to_receive_video !=
4170 RTCOfferAnswerOptions::kUndefined) {
4171 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004172 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004173 offer_new_video_description ||
4174 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004175 }
4176
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004177 absl::optional<size_t> audio_index;
4178 absl::optional<size_t> video_index;
4179 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004180 // If a current description exists, generate m= sections in the same order,
4181 // using the first audio/video/data section that appears and rejecting
4182 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004183 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004184 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004185 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004186 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4187 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4188 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004189 }
4190
zhihuang1c378ed2017-08-17 14:10:50 -07004191 // Add audio/video/data m= sections to the end if needed.
4192 if (!audio_index && offer_new_audio_description) {
4193 session_options->media_description_options.push_back(
4194 cricket::MediaDescriptionOptions(
4195 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004196 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4197 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004198 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004199 }
zhihuang1c378ed2017-08-17 14:10:50 -07004200 if (!video_index && offer_new_video_description) {
4201 session_options->media_description_options.push_back(
4202 cricket::MediaDescriptionOptions(
4203 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004204 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4205 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004206 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004207 }
zhihuang1c378ed2017-08-17 14:10:50 -07004208 if (!data_index && offer_new_data_description) {
4209 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004210 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004211 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004212 }
4213
4214 cricket::MediaDescriptionOptions* audio_media_description_options =
4215 !audio_index ? nullptr
4216 : &session_options->media_description_options[*audio_index];
4217 cricket::MediaDescriptionOptions* video_media_description_options =
4218 !video_index ? nullptr
4219 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004220
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004221 AddPlanBRtpSenderOptions(GetSendersInternal(),
4222 audio_media_description_options,
4223 video_media_description_options,
4224 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004225}
4226
Steve Antondcc3c022017-12-22 16:02:54 -08004227static cricket::MediaDescriptionOptions
4228GetMediaDescriptionOptionsForTransceiver(
4229 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4230 transceiver,
4231 const std::string& mid) {
4232 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004233 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004234 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004235 // This behavior is specified in JSEP. The gist is that:
4236 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4237 // sendrecv.
4238 // 2. If the MSID is included, then it must be included in any subsequent
4239 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004240 if (transceiver->stopped() ||
4241 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4242 !transceiver->internal()->has_ever_been_used_to_send())) {
4243 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004244 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004245
4246 cricket::SenderOptions sender_options;
4247 sender_options.track_id = transceiver->sender()->id();
4248 sender_options.stream_ids = transceiver->sender()->stream_ids();
4249
4250 // The following sets up RIDs and Simulcast.
4251 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004252 RtpParameters send_parameters =
4253 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004254 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4255 send_parameters.encodings.end(),
4256 [](const RtpEncodingParameters& encoding) {
4257 return !encoding.rid.empty();
4258 });
4259
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004260 std::vector<RidDescription> send_rids;
4261 SimulcastLayerList send_layers;
4262 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4263 if (encoding.rid.empty()) {
4264 continue;
4265 }
4266 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4267 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4268 }
4269
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004270 if (has_rids) {
4271 sender_options.rids = send_rids;
4272 }
4273
4274 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004275 // When RIDs are configured, we must set num_sim_layers to 0 to.
4276 // Otherwise, num_sim_layers must be 1 because either there is no
4277 // simulcast, or simulcast is acheived by munging the SDP.
4278 sender_options.num_sim_layers = has_rids ? 0 : 1;
4279 media_description_options.sender_options.push_back(sender_options);
4280
Steve Antondcc3c022017-12-22 16:02:54 -08004281 return media_description_options;
4282}
4283
Steve Anton5c72e712018-12-10 14:25:30 -08004284// Returns the ContentInfo at mline index |i|, or null if none exists.
4285static const ContentInfo* GetContentByIndex(
4286 const SessionDescriptionInterface* sdesc,
4287 size_t i) {
4288 if (!sdesc) {
4289 return nullptr;
4290 }
4291 const ContentInfos& contents = sdesc->description()->contents();
4292 return (i < contents.size() ? &contents[i] : nullptr);
4293}
4294
Steve Antondcc3c022017-12-22 16:02:54 -08004295void PeerConnection::GetOptionsForUnifiedPlanOffer(
4296 const RTCOfferAnswerOptions& offer_answer_options,
4297 cricket::MediaSessionOptions* session_options) {
4298 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4299 // Offers) and 5.2.2 (Subsequent Offers).
4300 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4301 const ContentInfos& local_contents =
4302 (local_description() ? local_description()->description()->contents()
4303 : ContentInfos());
4304 const ContentInfos& remote_contents =
4305 (remote_description() ? remote_description()->description()->contents()
4306 : ContentInfos());
4307 // The mline indices that can be recycled. New transceivers should reuse these
4308 // slots first.
4309 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004310 // First, go through each media section that exists in either the local or
4311 // remote description and generate a media section in this offer for the
4312 // associated transceiver. If a media section can be recycled, generate a
4313 // default, rejected media section here that can be later overwritten.
4314 for (size_t i = 0;
4315 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4316 // Either |local_content| or |remote_content| is non-null.
4317 const ContentInfo* local_content =
4318 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004319 const ContentInfo* current_local_content =
4320 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004321 const ContentInfo* remote_content =
4322 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004323 const ContentInfo* current_remote_content =
4324 GetContentByIndex(current_remote_description(), i);
4325 bool had_been_rejected =
4326 (current_local_content && current_local_content->rejected) ||
4327 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004328 const std::string& mid =
4329 (local_content ? local_content->name : remote_content->name);
4330 cricket::MediaType media_type =
4331 (local_content ? local_content->media_description()->type()
4332 : remote_content->media_description()->type());
4333 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4334 media_type == cricket::MEDIA_TYPE_VIDEO) {
4335 auto transceiver = GetAssociatedTransceiver(mid);
4336 RTC_CHECK(transceiver);
4337 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004338 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004339 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004340 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004341 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4342 RtpTransceiverDirection::kInactive,
4343 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004344 recycleable_mline_indices.push(i);
4345 } else {
4346 session_options->media_description_options.push_back(
4347 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4348 // CreateOffer shouldn't really cause any state changes in
4349 // PeerConnection, but we need a way to match new transceivers to new
4350 // media sections in SetLocalDescription and JSEP specifies this is done
4351 // by recording the index of the media section generated for the
4352 // transceiver in the offer.
4353 transceiver->internal()->set_mline_index(i);
4354 }
4355 } else {
4356 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004357 RTC_CHECK(GetDataMid());
4358 if (had_been_rejected || mid != *GetDataMid()) {
4359 session_options->media_description_options.push_back(
4360 GetMediaDescriptionOptionsForRejectedData(mid));
4361 } else {
4362 session_options->media_description_options.push_back(
4363 GetMediaDescriptionOptionsForActiveData(mid));
4364 }
Steve Antondcc3c022017-12-22 16:02:54 -08004365 }
4366 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004367
Steve Antondcc3c022017-12-22 16:02:54 -08004368 // Next, look for transceivers that are newly added (that is, are not stopped
4369 // and not associated). Reuse media sections marked as recyclable first,
4370 // otherwise append to the end of the offer. New media sections should be
4371 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004372 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004373 if (transceiver->mid() || transceiver->stopped()) {
4374 continue;
4375 }
4376 size_t mline_index;
4377 if (!recycleable_mline_indices.empty()) {
4378 mline_index = recycleable_mline_indices.front();
4379 recycleable_mline_indices.pop();
4380 session_options->media_description_options[mline_index] =
4381 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004382 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004383 } else {
4384 mline_index = session_options->media_description_options.size();
4385 session_options->media_description_options.push_back(
4386 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004387 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004388 }
4389 // See comment above for why CreateOffer changes the transceiver's state.
4390 transceiver->internal()->set_mline_index(mline_index);
4391 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004392 // Lastly, add a m-section if we have local data channels and an m section
4393 // does not already exist.
4394 if (!GetDataMid() && HasDataChannels()) {
4395 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004396 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004397 }
Steve Antondcc3c022017-12-22 16:02:54 -08004398}
4399
4400void PeerConnection::GetOptionsForAnswer(
4401 const RTCOfferAnswerOptions& offer_answer_options,
4402 cricket::MediaSessionOptions* session_options) {
4403 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4404
4405 if (IsUnifiedPlan()) {
4406 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4407 } else {
4408 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4409 }
4410
Steve Antonfa2260d2017-12-28 16:38:23 -08004411 // Intentionally unset the data channel type for RTP data channel. Otherwise
4412 // the RTP data channels would be successfully negotiated by default and the
4413 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4414 // We want to leave RTP data channels broken, so people won't try to use them.
4415 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4416 session_options->data_channel_type = data_channel_type();
4417 }
4418
Steve Antondcc3c022017-12-22 16:02:54 -08004419 // Apply ICE renomination flag.
4420 for (auto& options : session_options->media_description_options) {
4421 options.transport_options.enable_ice_renomination =
4422 configuration_.enable_ice_renomination;
4423 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004424
4425 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004426 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004427 session_options->pooled_ice_credentials =
4428 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4429 RTC_FROM_HERE,
4430 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4431 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004432}
4433
Steve Antondcc3c022017-12-22 16:02:54 -08004434void PeerConnection::GetOptionsForPlanBAnswer(
4435 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004436 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004437 // Figure out transceiver directional preferences.
4438 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4439 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4440
4441 // By default, generate sendrecv/recvonly m= sections. The direction is also
4442 // restricted by the direction in the offer.
4443 bool recv_audio = true;
4444 bool recv_video = true;
4445
4446 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004447 if (offer_answer_options.offer_to_receive_audio !=
4448 RTCOfferAnswerOptions::kUndefined) {
4449 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004450 }
Steve Antondcc3c022017-12-22 16:02:54 -08004451 if (offer_answer_options.offer_to_receive_video !=
4452 RTCOfferAnswerOptions::kUndefined) {
4453 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004454 }
4455
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004456 absl::optional<size_t> audio_index;
4457 absl::optional<size_t> video_index;
4458 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004459
4460 // Generate m= sections that match those in the offer.
4461 // Note that mediasession.cc will handle intersection our preferred
4462 // direction with the offered direction.
4463 GenerateMediaDescriptionOptions(
4464 remote_description(),
4465 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4466 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4467 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004468
4469 cricket::MediaDescriptionOptions* audio_media_description_options =
4470 !audio_index ? nullptr
4471 : &session_options->media_description_options[*audio_index];
4472 cricket::MediaDescriptionOptions* video_media_description_options =
4473 !video_index ? nullptr
4474 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004475
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004476 AddPlanBRtpSenderOptions(GetSendersInternal(),
4477 audio_media_description_options,
4478 video_media_description_options,
4479 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004480}
zhihuangaf388472016-11-02 16:49:48 -07004481
Steve Antondcc3c022017-12-22 16:02:54 -08004482void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4483 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4484 cricket::MediaSessionOptions* session_options) {
4485 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4486 // Answers) and 5.3.2 (Subsequent Answers).
4487 RTC_DCHECK(remote_description());
4488 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4489 for (const ContentInfo& content :
4490 remote_description()->description()->contents()) {
4491 cricket::MediaType media_type = content.media_description()->type();
4492 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4493 media_type == cricket::MEDIA_TYPE_VIDEO) {
4494 auto transceiver = GetAssociatedTransceiver(content.name);
4495 RTC_CHECK(transceiver);
4496 session_options->media_description_options.push_back(
4497 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4498 } else {
4499 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004500 // Reject all data sections if data channels are disabled.
4501 // Reject a data section if it has already been rejected.
4502 // Reject all data sections except for the first one.
4503 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4504 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004505 session_options->media_description_options.push_back(
4506 GetMediaDescriptionOptionsForRejectedData(content.name));
4507 } else {
4508 session_options->media_description_options.push_back(
4509 GetMediaDescriptionOptionsForActiveData(content.name));
4510 }
Steve Antondcc3c022017-12-22 16:02:54 -08004511 }
4512 }
htaa2a49d92016-03-04 02:51:39 -08004513}
4514
zhihuang1c378ed2017-08-17 14:10:50 -07004515void PeerConnection::GenerateMediaDescriptionOptions(
4516 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004517 RtpTransceiverDirection audio_direction,
4518 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004519 absl::optional<size_t>* audio_index,
4520 absl::optional<size_t>* video_index,
4521 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004522 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004523 for (const cricket::ContentInfo& content :
4524 session_desc->description()->contents()) {
4525 if (IsAudioContent(&content)) {
4526 // If we already have an audio m= section, reject this extra one.
4527 if (*audio_index) {
4528 session_options->media_description_options.push_back(
4529 cricket::MediaDescriptionOptions(
4530 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004531 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004532 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004533 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004534 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004535 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4536 content.name, audio_direction,
4537 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004538 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004539 }
4540 } else if (IsVideoContent(&content)) {
4541 // If we already have an video m= section, reject this extra one.
4542 if (*video_index) {
4543 session_options->media_description_options.push_back(
4544 cricket::MediaDescriptionOptions(
4545 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004546 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004547 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004548 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004549 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004550 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4551 content.name, video_direction,
4552 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004553 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004554 }
4555 } else {
4556 RTC_DCHECK(IsDataContent(&content));
4557 // If we already have an data m= section, reject this extra one.
4558 if (*data_index) {
4559 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004560 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004561 } else {
4562 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004563 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004564 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004565 }
4566 }
htaa2a49d92016-03-04 02:51:39 -08004567 }
deadbeefab9b2d12015-10-14 11:33:11 -07004568}
4569
Steve Antonfa2260d2017-12-28 16:38:23 -08004570cricket::MediaDescriptionOptions
4571PeerConnection::GetMediaDescriptionOptionsForActiveData(
4572 const std::string& mid) const {
4573 // Direction for data sections is meaningless, but legacy endpoints might
4574 // expect sendrecv.
4575 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4576 RtpTransceiverDirection::kSendRecv,
4577 /*stopped=*/false);
4578 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4579 return options;
4580}
4581
4582cricket::MediaDescriptionOptions
4583PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4584 const std::string& mid) const {
4585 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4586 RtpTransceiverDirection::kInactive,
4587 /*stopped=*/true);
4588 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4589 return options;
4590}
4591
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004592absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004593 switch (data_channel_type_) {
4594 case cricket::DCT_RTP:
4595 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004596 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004597 }
4598 return rtp_data_channel_->content_name();
4599 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004600 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004601 case cricket::DCT_MEDIA_TRANSPORT:
4602 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004603 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004604 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004605 }
4606}
4607
Steve Anton4171afb2017-11-20 10:20:22 -08004608void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4609 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4610 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004611 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004612}
4613
Steve Anton4171afb2017-11-20 10:20:22 -08004614void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004615 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004616 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004617 cricket::MediaType media_type,
4618 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004619 RTC_DCHECK(!IsUnifiedPlan());
4620
Steve Anton4171afb2017-11-20 10:20:22 -08004621 std::vector<RtpSenderInfo>* current_senders =
4622 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004623
Steve Anton4171afb2017-11-20 10:20:22 -08004624 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004625 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004626 for (auto sender_it = current_senders->begin();
4627 sender_it != current_senders->end();
4628 /* incremented manually */) {
4629 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004630 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004631 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004632 std::string params_stream_id;
4633 if (params) {
4634 params_stream_id =
4635 (!params->first_stream_id().empty() ? params->first_stream_id()
4636 : kDefaultStreamId);
4637 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004638 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004639 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004640 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004641 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004642 sender_exists) {
4643 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004644 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004645 OnRemoteSenderRemoved(info, media_type);
4646 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004647 }
4648 }
4649
Steve Anton4171afb2017-11-20 10:20:22 -08004650 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004651 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004652 if (!params.has_ssrcs()) {
4653 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4654 // sender, this means it is coming from a Unified Plan endpoint,so we just
4655 // create a default.
4656 default_sender_needed = true;
4657 break;
4658 }
4659
Seth Hampson845e8782018-03-02 11:34:10 -08004660 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004661 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004662 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4663 // not supported in Plan B, we just take the first here and create the
4664 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004665 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004666 (!params.first_stream_id().empty() ? params.first_stream_id()
4667 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004668 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004669 uint32_t ssrc = params.first_ssrc();
4670
4671 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004672 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004673 if (!stream) {
4674 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004675 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004676 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004677 remote_streams_->AddStream(stream);
4678 new_streams->AddStream(stream);
4679 }
4680
Steve Anton4171afb2017-11-20 10:20:22 -08004681 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004682 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004683 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004684 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004685 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004686 }
4687 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004688
Steve Anton4171afb2017-11-20 10:20:22 -08004689 // Add default sender if necessary.
4690 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004691 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004692 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004693 if (!default_stream) {
4694 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004695 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004696 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004697 remote_streams_->AddStream(default_stream);
4698 new_streams->AddStream(default_stream);
4699 }
Steve Anton4171afb2017-11-20 10:20:22 -08004700 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4701 ? kDefaultAudioSenderId
4702 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004703 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004704 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004705 if (!default_sender_info) {
4706 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004707 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004708 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004709 }
4710 }
deadbeefab9b2d12015-10-14 11:33:11 -07004711}
4712
Steve Anton4171afb2017-11-20 10:20:22 -08004713void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4714 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004715 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4716 << " receiver for track_id=" << sender_info.sender_id
4717 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004718
Steve Anton3d954a62018-04-02 11:27:23 -07004719 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004720 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004721 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004722 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004723 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004724 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004725 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004726 }
4727}
4728
Steve Anton4171afb2017-11-20 10:20:22 -08004729void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4730 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004731 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4732 << " receiver for track_id=" << sender_info.sender_id
4733 << " and stream_id=" << sender_info.stream_id;
4734
Seth Hampson845e8782018-03-02 11:34:10 -08004735 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004736
Henrik Boström933d8b02017-10-10 10:05:16 -07004737 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004738 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004739 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4740 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004741 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004742 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004743 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004744 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004745 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004746 }
4747 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004748 // Stopping or destroying a VideoRtpReceiver will end the
4749 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004750 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004751 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004752 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004753 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004754 // There's no guarantee the track is still available, e.g. the track may
4755 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004756 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004757 }
4758 } else {
nisseede5da42017-01-12 05:15:36 -08004759 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004760 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004761 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004762 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004763 }
deadbeefab9b2d12015-10-14 11:33:11 -07004764}
4765
4766void PeerConnection::UpdateEndedRemoteMediaStreams() {
4767 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4768 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4769 MediaStreamInterface* stream = remote_streams_->at(i);
4770 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4771 streams_to_remove.push_back(stream);
4772 }
4773 }
4774
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004775 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004776 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004777 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004778 }
4779}
4780
Steve Anton4171afb2017-11-20 10:20:22 -08004781void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004782 const std::vector<cricket::StreamParams>& streams,
4783 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004784 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004785
Seth Hampson845e8782018-03-02 11:34:10 -08004786 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004787 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004788 for (auto sender_it = current_senders->begin();
4789 sender_it != current_senders->end();
4790 /* incremented manually */) {
4791 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004792 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004793 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4794 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004795 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004796 OnLocalSenderRemoved(info, media_type);
4797 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004798 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004799 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004800 }
4801 }
4802
Steve Anton4171afb2017-11-20 10:20:22 -08004803 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004804 for (const cricket::StreamParams& params : streams) {
4805 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004806 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004807 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004808 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004809 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004810 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004811 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004812 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004813 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004814 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004815 }
4816 }
4817}
4818
Steve Anton4171afb2017-11-20 10:20:22 -08004819void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4820 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004821 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004822 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004823 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004824 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4825 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004826 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004827 return;
4828 }
4829
deadbeeffac06552015-11-25 11:26:01 -08004830 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004831 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004832 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004833 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004834 }
deadbeeffac06552015-11-25 11:26:01 -08004835
Seth Hampson5b4f0752018-04-02 16:31:36 -07004836 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004837 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004838}
4839
Steve Anton4171afb2017-11-20 10:20:22 -08004840void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4841 cricket::MediaType media_type) {
4842 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004843 if (!sender) {
4844 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004845 // SessionDescriptions has been renegotiated.
4846 return;
4847 }
deadbeeffac06552015-11-25 11:26:01 -08004848
4849 // A sender has been removed from the SessionDescription but it's still
4850 // associated with the PeerConnection. This only occurs if the SDP doesn't
4851 // match with the calls to CreateSender, AddStream and RemoveStream.
4852 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004853 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004854 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004855 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004856 }
deadbeeffac06552015-11-25 11:26:01 -08004857
Steve Anton4171afb2017-11-20 10:20:22 -08004858 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004859}
4860
4861void PeerConnection::UpdateLocalRtpDataChannels(
4862 const cricket::StreamParamsVec& streams) {
4863 std::vector<std::string> existing_channels;
4864
4865 // Find new and active data channels.
4866 for (const cricket::StreamParams& params : streams) {
4867 // |it->sync_label| is actually the data channel label. The reason is that
4868 // we use the same naming of data channels as we do for
4869 // MediaStreams and Tracks.
4870 // For MediaStreams, the sync_label is the MediaStream label and the
4871 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004872 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004873 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004874 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004875 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004876 continue;
4877 }
4878 // Set the SSRC the data channel should use for sending.
4879 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4880 existing_channels.push_back(data_channel_it->first);
4881 }
4882
4883 UpdateClosingRtpDataChannels(existing_channels, true);
4884}
4885
4886void PeerConnection::UpdateRemoteRtpDataChannels(
4887 const cricket::StreamParamsVec& streams) {
4888 std::vector<std::string> existing_channels;
4889
4890 // Find new and active data channels.
4891 for (const cricket::StreamParams& params : streams) {
4892 // The data channel label is either the mslabel or the SSRC if the mslabel
4893 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004894 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004895 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004896 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004897 auto data_channel_it = rtp_data_channels_.find(label);
4898 if (data_channel_it == rtp_data_channels_.end()) {
4899 // This is a new data channel.
4900 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4901 } else {
4902 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4903 }
4904 existing_channels.push_back(label);
4905 }
4906
4907 UpdateClosingRtpDataChannels(existing_channels, false);
4908}
4909
4910void PeerConnection::UpdateClosingRtpDataChannels(
4911 const std::vector<std::string>& active_channels,
4912 bool is_local_update) {
4913 auto it = rtp_data_channels_.begin();
4914 while (it != rtp_data_channels_.end()) {
4915 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004916 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004917 ++it;
4918 continue;
4919 }
4920
4921 if (is_local_update) {
4922 data_channel->SetSendSsrc(0);
4923 } else {
4924 data_channel->RemotePeerRequestClose();
4925 }
4926
4927 if (data_channel->state() == DataChannel::kClosed) {
4928 rtp_data_channels_.erase(it);
4929 it = rtp_data_channels_.begin();
4930 } else {
4931 ++it;
4932 }
4933 }
4934}
4935
4936void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4937 uint32_t remote_ssrc) {
4938 rtc::scoped_refptr<DataChannel> channel(
4939 InternalCreateDataChannel(label, nullptr));
4940 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004941 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004942 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004943 return;
4944 }
4945 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004946 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4947 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004948 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004949}
4950
4951rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4952 const std::string& label,
4953 const InternalDataChannelInit* config) {
4954 if (IsClosed()) {
4955 return nullptr;
4956 }
Steve Anton75737c02017-11-06 10:37:17 -08004957 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004958 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004959 << "InternalCreateDataChannel: Data is not supported in this call.";
4960 return nullptr;
4961 }
4962 InternalDataChannelInit new_config =
4963 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004964 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004965 if (new_config.id < 0) {
4966 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004967 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004968 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004969 RTC_LOG(LS_ERROR)
4970 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004971 return nullptr;
4972 }
4973 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004974 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004975 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004976 return nullptr;
4977 }
4978 }
4979
Steve Anton75737c02017-11-06 10:37:17 -08004980 rtc::scoped_refptr<DataChannel> channel(
4981 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004982 if (!channel) {
4983 sid_allocator_.ReleaseSid(new_config.id);
4984 return nullptr;
4985 }
4986
4987 if (channel->data_channel_type() == cricket::DCT_RTP) {
4988 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004989 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4990 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004991 return nullptr;
4992 }
4993 rtp_data_channels_[channel->label()] = channel;
4994 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004995 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004996 sctp_data_channels_.push_back(channel);
4997 channel->SignalClosed.connect(this,
4998 &PeerConnection::OnSctpDataChannelClosed);
4999 }
5000
Steve Anton2d8609c2018-01-23 16:38:46 -08005001 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005002 return channel;
5003}
5004
5005bool PeerConnection::HasDataChannels() const {
5006 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5007}
5008
5009void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
5010 for (const auto& channel : sctp_data_channels_) {
5011 if (channel->id() < 0) {
5012 int sid;
5013 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005014 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07005015 continue;
5016 }
5017 channel->SetSctpSid(sid);
5018 }
5019 }
5020}
5021
5022void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005023 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005024 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5025 ++it) {
5026 if (it->get() == channel) {
5027 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005028 // After the closing procedure is done, it's safe to use this ID for
5029 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005030 sid_allocator_.ReleaseSid(channel->id());
5031 }
deadbeefbd292462015-12-14 18:15:29 -08005032 // Since this method is triggered by a signal from the DataChannel,
5033 // we can't free it directly here; we need to free it asynchronously.
5034 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005035 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005036 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5037 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005038 return;
5039 }
5040 }
5041}
5042
deadbeefab9b2d12015-10-14 11:33:11 -07005043void PeerConnection::OnDataChannelDestroyed() {
5044 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5045 // DataChannel may callback to us and try to modify the list.
5046 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5047 temp_rtp_dcs.swap(rtp_data_channels_);
5048 for (const auto& kv : temp_rtp_dcs) {
5049 kv.second->OnTransportChannelDestroyed();
5050 }
5051
5052 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5053 temp_sctp_dcs.swap(sctp_data_channels_);
5054 for (const auto& channel : temp_sctp_dcs) {
5055 channel->OnTransportChannelDestroyed();
5056 }
5057}
5058
5059void PeerConnection::OnDataChannelOpenMessage(
5060 const std::string& label,
5061 const InternalDataChannelInit& config) {
5062 rtc::scoped_refptr<DataChannel> channel(
5063 InternalCreateDataChannel(label, &config));
5064 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005065 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005066 return;
5067 }
5068
deadbeefa601f5c2016-06-06 14:27:39 -07005069 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5070 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005071 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005072 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005073}
5074
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005075bool PeerConnection::HandleOpenMessage_s(
5076 const cricket::ReceiveDataParams& params,
5077 const rtc::CopyOnWriteBuffer& buffer) {
5078 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5079 // Received OPEN message; parse and signal that a new data channel should
5080 // be created.
5081 std::string label;
5082 InternalDataChannelInit config;
5083 config.id = params.ssrc;
5084 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5085 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5086 << params.ssrc;
5087 return true;
5088 }
5089 config.open_handshake_role = InternalDataChannelInit::kAcker;
5090 OnDataChannelOpenMessage(label, config);
5091 return true;
5092 }
5093 return false;
5094}
5095
Steve Anton4171afb2017-11-20 10:20:22 -08005096rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5097PeerConnection::GetAudioTransceiver() const {
5098 // This method only works with Plan B SDP, where there is a single
5099 // audio/video transceiver.
5100 RTC_DCHECK(!IsUnifiedPlan());
5101 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005102 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005103 return transceiver;
5104 }
5105 }
5106 RTC_NOTREACHED();
5107 return nullptr;
5108}
5109
5110rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5111PeerConnection::GetVideoTransceiver() const {
5112 // This method only works with Plan B SDP, where there is a single
5113 // audio/video transceiver.
5114 RTC_DCHECK(!IsUnifiedPlan());
5115 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005116 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005117 return transceiver;
5118 }
5119 }
5120 RTC_NOTREACHED();
5121 return nullptr;
5122}
5123
5124// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5125// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005126bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005127 switch (type) {
5128 case cricket::MEDIA_TYPE_AUDIO:
5129 return !GetAudioTransceiver()->internal()->senders().empty();
5130 case cricket::MEDIA_TYPE_VIDEO:
5131 return !GetVideoTransceiver()->internal()->senders().empty();
5132 case cricket::MEDIA_TYPE_DATA:
5133 return false;
5134 }
5135 RTC_NOTREACHED();
5136 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005137}
5138
Steve Anton4171afb2017-11-20 10:20:22 -08005139rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5140PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005141 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005142 for (auto sender : transceiver->internal()->senders()) {
5143 if (sender->track() == track) {
5144 return sender;
5145 }
5146 }
5147 }
5148 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005149}
5150
Steve Anton4171afb2017-11-20 10:20:22 -08005151rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5152PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005153 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005154 for (auto sender : transceiver->internal()->senders()) {
5155 if (sender->id() == sender_id) {
5156 return sender;
5157 }
5158 }
5159 }
5160 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005161}
5162
Steve Anton4171afb2017-11-20 10:20:22 -08005163rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5164PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005165 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005166 for (auto receiver : transceiver->internal()->receivers()) {
5167 if (receiver->id() == receiver_id) {
5168 return receiver;
5169 }
5170 }
5171 }
5172 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005173}
5174
Steve Anton4171afb2017-11-20 10:20:22 -08005175std::vector<PeerConnection::RtpSenderInfo>*
5176PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5177 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5178 media_type == cricket::MEDIA_TYPE_VIDEO);
5179 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5180 ? &remote_audio_sender_infos_
5181 : &remote_video_sender_infos_;
5182}
5183
5184std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005185 cricket::MediaType media_type) {
5186 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5187 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005188 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5189 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005190}
5191
Steve Anton4171afb2017-11-20 10:20:22 -08005192const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5193 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005194 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005195 const std::string sender_id) const {
5196 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005197 if (sender_info.stream_id == stream_id &&
5198 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005199 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005200 }
5201 }
5202 return nullptr;
5203}
5204
5205DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5206 for (const auto& channel : sctp_data_channels_) {
5207 if (channel->id() == sid) {
5208 return channel;
5209 }
5210 }
5211 return nullptr;
5212}
5213
deadbeef91dd5672016-05-18 16:55:30 -07005214bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005215 const cricket::ServerAddresses& stun_servers,
5216 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005217 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005218 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005219 // To handle both internal and externally created port allocator, we will
5220 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005221 port_allocator_flags_ = port_allocator_->flags();
5222 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5223 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5224 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005225 // If the disable-IPv6 flag was specified, we'll not override it
5226 // by experiment.
5227 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005228 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005229 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5230 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005231 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005232 }
5233
zhihuangb09b3f92017-03-07 14:40:51 -08005234 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005235 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005236 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005237 }
5238
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005239 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005240 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005241 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005242 }
5243
honghaiz60347052016-05-31 18:29:12 -07005244 if (configuration.candidate_network_policy ==
5245 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005246 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005247 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005248 }
5249
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005250 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005251 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005252 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5253 }
5254
Qingsi Wanga2d60672018-04-11 16:57:45 -07005255 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005256 // No step delay is used while allocating ports.
5257 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5258 port_allocator_->set_candidate_filter(
5259 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005260 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005261
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005262 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005263 for (auto& turn_server : turn_servers_copy) {
5264 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005265 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005266 // Call this last since it may create pooled allocator sessions using the
5267 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005268 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005269 stun_servers, std::move(turn_servers_copy),
5270 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5271 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005272 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005273 return true;
5274}
5275
deadbeef91dd5672016-05-18 16:55:30 -07005276bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005277 const cricket::ServerAddresses& stun_servers,
5278 const std::vector<cricket::RelayServerConfig>& turn_servers,
5279 IceTransportsType type,
5280 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005281 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005282 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005283 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005284 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005285 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005286 // According to JSEP, after setLocalDescription, changing the candidate pool
5287 // size is not allowed, and changing the set of ICE servers will not result
5288 // in new candidates being gathered.
5289 if (local_description()) {
5290 port_allocator_->FreezeCandidatePool();
5291 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005292 // Add the custom tls turn servers if they exist.
5293 auto turn_servers_copy = turn_servers;
5294 for (auto& turn_server : turn_servers_copy) {
5295 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5296 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005297 // Call this last since it may create pooled allocator sessions using the
5298 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005299 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005300 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5301 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005302}
5303
Steve Antonba818672017-11-06 10:21:57 -08005304cricket::ChannelManager* PeerConnection::channel_manager() const {
5305 return factory_->channel_manager();
5306}
5307
Elad Alon99c3fe52017-10-13 16:29:40 +02005308bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005309 std::unique_ptr<RtcEventLogOutput> output,
5310 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005311 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005312 if (!event_log_) {
5313 return false;
5314 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005315 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005316}
5317
5318void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005319 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005320 if (event_log_) {
5321 event_log_->StopLogging();
5322 }
ivoc14d5dbe2016-07-04 07:06:55 -07005323}
nisseeaabdf62017-05-05 02:23:02 -07005324
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005325cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005326 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005327 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005328 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005329 if (channel && channel->content_name() == content_name) {
5330 return channel;
5331 }
Steve Anton75737c02017-11-06 10:37:17 -08005332 }
5333 if (rtp_data_channel() &&
5334 rtp_data_channel()->content_name() == content_name) {
5335 return rtp_data_channel();
5336 }
5337 return nullptr;
5338}
5339
5340bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005341 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005342 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005343 RTC_LOG(LS_INFO)
5344 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005345 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005346 return false;
5347 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005348 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005349 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005350 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005351 return false;
5352 }
5353
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005354 absl::optional<rtc::SSLRole> dtls_role;
5355 if (sctp_mid_) {
5356 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5357 } else if (is_caller_) {
5358 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5359 }
Zhi Huange830e682018-03-30 10:48:35 -07005360 if (dtls_role) {
5361 *role = *dtls_role;
5362 return true;
5363 }
5364 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005365}
5366
5367bool PeerConnection::GetSslRole(const std::string& content_name,
5368 rtc::SSLRole* role) {
5369 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005370 RTC_LOG(LS_INFO)
5371 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005372 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005373 return false;
5374 }
5375
Zhi Huange830e682018-03-30 10:48:35 -07005376 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5377 if (dtls_role) {
5378 *role = *dtls_role;
5379 return true;
5380 }
5381 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005382}
5383
Steve Antonf8470812017-12-04 10:46:21 -08005384void PeerConnection::SetSessionError(SessionError error,
5385 const std::string& error_desc) {
5386 RTC_DCHECK_RUN_ON(signaling_thread());
5387 if (error != session_error_) {
5388 session_error_ = error;
5389 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005390 }
5391}
5392
Zhi Huange830e682018-03-30 10:48:35 -07005393RTCError PeerConnection::UpdateSessionState(
5394 SdpType type,
5395 cricket::ContentSource source,
5396 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005397 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005398
5399 // If there's already a pending error then no state transition should happen.
5400 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005401 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005402
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005403 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005404 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005405 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005406 }
5407
5408 // Update the signaling state according to the specified state machine (see
5409 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005410 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005411 ChangeSignalingState(source == cricket::CS_LOCAL
5412 ? PeerConnectionInterface::kHaveLocalOffer
5413 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005414 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005415 ChangeSignalingState(source == cricket::CS_LOCAL
5416 ? PeerConnectionInterface::kHaveLocalPrAnswer
5417 : PeerConnectionInterface::kHaveRemotePrAnswer);
5418 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005419 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005420 ChangeSignalingState(PeerConnectionInterface::kStable);
5421 }
5422
5423 // Update internal objects according to the session description's media
5424 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005425 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005426 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005427 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005428 }
5429
Steve Anton8a006912017-12-04 15:25:56 -08005430 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005431}
5432
Steve Anton8a006912017-12-04 15:25:56 -08005433RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005434 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005435 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005436 const SessionDescriptionInterface* sdesc =
5437 (source == cricket::CS_LOCAL ? local_description()
5438 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005439 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005440
5441 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005442 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005443 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005444 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005445 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005446 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005447 continue;
5448 }
5449 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005450 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005451 if (!content_desc) {
5452 continue;
5453 }
5454 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005455 bool success = (source == cricket::CS_LOCAL)
5456 ? channel->SetLocalContent(content_desc, type, &error)
5457 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005458 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005459 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005460 }
5461 }
5462
5463 // If using the RtpDataChannel, push down the new SDP section for it too.
5464 if (rtp_data_channel_) {
5465 const ContentInfo* data_content =
5466 cricket::GetFirstDataContent(sdesc->description());
5467 if (data_content && !data_content->rejected) {
5468 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005469 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005470 if (data_desc) {
5471 std::string error;
5472 bool success =
5473 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005474 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005475 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005476 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005477 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005478 }
Steve Anton75737c02017-11-06 10:37:17 -08005479 }
5480 }
5481 }
Steve Antoned10bd92017-12-05 10:52:59 -08005482
Steve Anton75737c02017-11-06 10:37:17 -08005483 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5484 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5485 if (sctp_transport_ && local_description() && remote_description() &&
5486 cricket::GetFirstDataContent(local_description()->description()) &&
5487 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005488 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005489 RTC_FROM_HERE,
5490 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005491 if (!success) {
5492 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5493 "Failed to push down SCTP parameters.");
5494 }
Steve Anton75737c02017-11-06 10:37:17 -08005495 }
Steve Antoned10bd92017-12-05 10:52:59 -08005496
Steve Anton8a006912017-12-04 15:25:56 -08005497 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005498}
5499
5500bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5501 RTC_DCHECK(network_thread()->IsCurrent());
5502 RTC_DCHECK(local_description());
5503 RTC_DCHECK(remote_description());
5504 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5505 // When we support "max-message-size", that would also be pushed down here.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005506 return cricket_sctp_transport()->Start(
Steve Anton75737c02017-11-06 10:37:17 -08005507 GetSctpPort(local_description()->description()),
5508 GetSctpPort(remote_description()->description()));
5509}
5510
Steve Anton8a006912017-12-04 15:25:56 -08005511RTCError PeerConnection::PushdownTransportDescription(
5512 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005513 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005514 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005515
Zhi Huange830e682018-03-30 10:48:35 -07005516 if (source == cricket::CS_LOCAL) {
5517 const SessionDescriptionInterface* sdesc = local_description();
5518 RTC_DCHECK(sdesc);
5519 return transport_controller_->SetLocalDescription(type,
5520 sdesc->description());
5521 } else {
5522 const SessionDescriptionInterface* sdesc = remote_description();
5523 RTC_DCHECK(sdesc);
5524 return transport_controller_->SetRemoteDescription(type,
5525 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005526 }
Steve Anton75737c02017-11-06 10:37:17 -08005527}
5528
5529bool PeerConnection::GetTransportDescription(
5530 const SessionDescription* description,
5531 const std::string& content_name,
5532 cricket::TransportDescription* tdesc) {
5533 if (!description || !tdesc) {
5534 return false;
5535 }
5536 const TransportInfo* transport_info =
5537 description->GetTransportInfoByName(content_name);
5538 if (!transport_info) {
5539 return false;
5540 }
5541 *tdesc = transport_info->description;
5542 return true;
5543}
5544
Steve Anton75737c02017-11-06 10:37:17 -08005545cricket::IceConfig PeerConnection::ParseIceConfig(
5546 const PeerConnectionInterface::RTCConfiguration& config) const {
5547 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005548 switch (config.continual_gathering_policy) {
5549 case PeerConnectionInterface::GATHER_ONCE:
5550 gathering_policy = cricket::GATHER_ONCE;
5551 break;
5552 case PeerConnectionInterface::GATHER_CONTINUALLY:
5553 gathering_policy = cricket::GATHER_CONTINUALLY;
5554 break;
5555 default:
5556 RTC_NOTREACHED();
5557 gathering_policy = cricket::GATHER_ONCE;
5558 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005559
Steve Anton75737c02017-11-06 10:37:17 -08005560 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005561 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5562 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005563 ice_config.prioritize_most_likely_candidate_pairs =
5564 config.prioritize_most_likely_ice_candidate_pairs;
5565 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005566 RTCConfigurationToIceConfigOptionalInt(
5567 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005568 ice_config.continual_gathering_policy = gathering_policy;
5569 ice_config.presume_writable_when_fully_relayed =
5570 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005571 ice_config.ice_check_interval_strong_connectivity =
5572 config.ice_check_interval_strong_connectivity;
5573 ice_config.ice_check_interval_weak_connectivity =
5574 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005575 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005576 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5577 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005578 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005579 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005580 ice_config.regather_all_networks_interval_range =
5581 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005582 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005583 return ice_config;
5584}
5585
Steve Antona41959e2018-11-28 11:15:33 -08005586static absl::string_view GetTrackIdBySsrc(
5587 const SessionDescriptionInterface* session_description,
5588 uint32_t ssrc) {
5589 if (!session_description) {
5590 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005591 }
Steve Antona41959e2018-11-28 11:15:33 -08005592 for (const cricket::ContentInfo& content :
5593 session_description->description()->contents()) {
5594 const cricket::MediaContentDescription& media =
5595 *content.media_description();
5596 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5597 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5598 const cricket::StreamParams* stream_params =
5599 cricket::GetStreamBySsrc(media.streams(), ssrc);
5600 if (stream_params) {
5601 return stream_params->id;
5602 }
5603 }
5604 }
5605 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005606}
5607
Steve Antona41959e2018-11-28 11:15:33 -08005608absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5609 return GetTrackIdBySsrc(local_description(), ssrc);
5610}
5611
5612absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5613 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005614}
5615
5616bool PeerConnection::SendData(const cricket::SendDataParams& params,
5617 const rtc::CopyOnWriteBuffer& payload,
5618 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005619 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5620 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5621 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005622 return false;
5623 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005624 if (media_transport_) {
5625 SendDataParams send_params;
5626 send_params.type = ToWebrtcDataMessageType(params.type);
5627 send_params.ordered = params.ordered;
5628 if (params.max_rtx_count >= 0) {
5629 send_params.max_rtx_count = params.max_rtx_count;
5630 } else if (params.max_rtx_ms >= 0) {
5631 send_params.max_rtx_ms = params.max_rtx_ms;
5632 }
5633 return media_transport_->SendData(params.sid, send_params, payload).ok();
5634 }
Steve Anton75737c02017-11-06 10:37:17 -08005635 return rtp_data_channel_
5636 ? rtp_data_channel_->SendData(params, payload, result)
5637 : network_thread()->Invoke<bool>(
5638 RTC_FROM_HERE,
5639 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005640 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005641}
5642
5643bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005644 RTC_DCHECK_RUN_ON(signaling_thread());
5645 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005646 // Don't log an error here, because DataChannels are expected to call
5647 // ConnectDataChannel in this state. It's the only way to initially tell
5648 // whether or not the underlying transport is ready.
5649 return false;
5650 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005651 if (media_transport_) {
5652 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5653 &DataChannel::OnChannelReady);
5654 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5655 &DataChannel::OnDataReceived);
5656 SignalMediaTransportChannelClosing_s.connect(
5657 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5658 SignalMediaTransportChannelClosed_s.connect(
5659 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5660 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005661 rtp_data_channel_->SignalReadyToSendData.connect(
5662 webrtc_data_channel, &DataChannel::OnChannelReady);
5663 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5664 &DataChannel::OnDataReceived);
5665 } else {
5666 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5667 &DataChannel::OnChannelReady);
5668 SignalSctpDataReceived.connect(webrtc_data_channel,
5669 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005670 SignalSctpClosingProcedureStartedRemotely.connect(
5671 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5672 SignalSctpClosingProcedureComplete.connect(
5673 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005674 }
5675 return true;
5676}
5677
5678void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005679 RTC_DCHECK_RUN_ON(signaling_thread());
5680 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005681 RTC_LOG(LS_ERROR)
5682 << "DisconnectDataChannel called when rtp_data_channel_ and "
5683 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005684 return;
5685 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005686 if (media_transport_) {
5687 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5688 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5689 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5690 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5691 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005692 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5693 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5694 } else {
5695 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5696 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005697 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5698 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005699 }
5700}
5701
5702void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005703 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005704 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005705 return;
5706 }
Steve Anton75737c02017-11-06 10:37:17 -08005707 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005708 RTC_LOG(LS_ERROR)
5709 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005710 return;
5711 }
5712 network_thread()->Invoke<void>(
5713 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005714 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005715}
5716
5717void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005718 if (media_transport_) {
5719 media_transport_->CloseChannel(sid);
5720 return;
5721 }
Steve Anton75737c02017-11-06 10:37:17 -08005722 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005723 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005724 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005725 return;
5726 }
5727 network_thread()->Invoke<void>(
5728 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005729 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005730}
5731
5732bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005733 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005734 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005735 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005736 sctp_ready_to_send_data_;
5737}
5738
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005739void PeerConnection::OnDataReceived(int channel_id,
5740 DataMessageType type,
5741 const rtc::CopyOnWriteBuffer& buffer) {
5742 cricket::ReceiveDataParams params;
5743 params.sid = channel_id;
5744 params.type = ToCricketDataMessageType(type);
5745 media_transport_invoker_->AsyncInvoke<void>(
5746 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5747 RTC_DCHECK_RUN_ON(signaling_thread());
5748 if (!HandleOpenMessage_s(params, buffer)) {
5749 SignalMediaTransportReceivedData_s(params, buffer);
5750 }
5751 });
5752}
5753
5754void PeerConnection::OnChannelClosing(int channel_id) {
5755 media_transport_invoker_->AsyncInvoke<void>(
5756 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5757 RTC_DCHECK_RUN_ON(signaling_thread());
5758 SignalMediaTransportChannelClosing_s(channel_id);
5759 });
5760}
5761
5762void PeerConnection::OnChannelClosed(int channel_id) {
5763 media_transport_invoker_->AsyncInvoke<void>(
5764 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5765 RTC_DCHECK_RUN_ON(signaling_thread());
5766 SignalMediaTransportChannelClosed_s(channel_id);
5767 });
5768}
5769
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005770absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005771 if (sctp_mid_ && transport_controller_) {
5772 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5773 if (dtls_transport) {
5774 return dtls_transport->transport_name();
5775 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005776 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005777 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005778 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005779}
5780
Qingsi Wang72a43a12018-02-20 16:03:18 -08005781cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5782 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005783 network_thread()->Invoke<void>(
5784 RTC_FROM_HERE,
5785 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5786 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005787 return candidate_states_list;
5788}
5789
Steve Anton5dfde182018-02-06 10:34:40 -08005790std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5791 const {
5792 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005793 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005794 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005795 if (channel) {
5796 transport_names_by_mid[channel->content_name()] =
5797 channel->transport_name();
5798 }
Steve Anton75737c02017-11-06 10:37:17 -08005799 }
Steve Anton5dfde182018-02-06 10:34:40 -08005800 if (rtp_data_channel_) {
5801 transport_names_by_mid[rtp_data_channel_->content_name()] =
5802 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005803 }
5804 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005805 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005806 RTC_DCHECK(transport_name);
5807 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005808 }
Steve Anton5dfde182018-02-06 10:34:40 -08005809 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005810}
5811
Steve Anton5dfde182018-02-06 10:34:40 -08005812std::map<std::string, cricket::TransportStats>
5813PeerConnection::GetTransportStatsByNames(
5814 const std::set<std::string>& transport_names) {
5815 if (!network_thread()->IsCurrent()) {
5816 return network_thread()
5817 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5818 RTC_FROM_HERE,
5819 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005820 }
Steve Anton5dfde182018-02-06 10:34:40 -08005821 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5822 for (const std::string& transport_name : transport_names) {
5823 cricket::TransportStats transport_stats;
5824 bool success =
5825 transport_controller_->GetStats(transport_name, &transport_stats);
5826 if (success) {
5827 transport_stats_by_name[transport_name] = std::move(transport_stats);
5828 } else {
5829 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5830 << transport_name;
5831 }
5832 }
5833 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005834}
5835
5836bool PeerConnection::GetLocalCertificate(
5837 const std::string& transport_name,
5838 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005839 if (!certificate) {
5840 return false;
5841 }
5842 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5843 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005844}
5845
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005846std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005847 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005848 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005849}
5850
5851cricket::DataChannelType PeerConnection::data_channel_type() const {
5852 return data_channel_type_;
5853}
5854
5855bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5856 return pending_ice_restarts_.find(content_name) !=
5857 pending_ice_restarts_.end();
5858}
5859
Steve Anton75737c02017-11-06 10:37:17 -08005860bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5861 return transport_controller_->NeedsIceRestart(content_name);
5862}
5863
5864void PeerConnection::OnCertificateReady(
5865 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5866 transport_controller_->SetLocalCertificate(certificate);
5867}
5868
5869void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005870 SetSessionError(SessionError::kTransport,
5871 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005872}
5873
Alex Loiko9289eda2018-11-23 16:18:59 +00005874void PeerConnection::OnTransportControllerConnectionState(
5875 cricket::IceConnectionState state) {
5876 switch (state) {
5877 case cricket::kIceConnectionConnecting:
5878 // If the current state is Connected or Completed, then there were
5879 // writable channels but now there are not, so the next state must
5880 // be Disconnected.
5881 // kIceConnectionConnecting is currently used as the default,
5882 // un-connected state by the TransportController, so its only use is
5883 // detecting disconnections.
5884 if (ice_connection_state_ ==
5885 PeerConnectionInterface::kIceConnectionConnected ||
5886 ice_connection_state_ ==
5887 PeerConnectionInterface::kIceConnectionCompleted) {
5888 SetIceConnectionState(
5889 PeerConnectionInterface::kIceConnectionDisconnected);
5890 }
5891 break;
5892 case cricket::kIceConnectionFailed:
5893 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5894 break;
5895 case cricket::kIceConnectionConnected:
5896 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5897 "all transports are writable.";
5898 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5899 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5900 break;
5901 case cricket::kIceConnectionCompleted:
5902 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5903 "all transports are complete.";
5904 if (ice_connection_state_ !=
5905 PeerConnectionInterface::kIceConnectionConnected) {
5906 // If jumping directly from "checking" to "connected",
5907 // signal "connected" first.
5908 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5909 }
5910 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5911 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5912 ReportTransportStats();
5913 break;
5914 default:
5915 RTC_NOTREACHED();
5916 }
5917}
5918
Steve Anton75737c02017-11-06 10:37:17 -08005919void PeerConnection::OnTransportControllerCandidatesGathered(
5920 const std::string& transport_name,
5921 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005922 int sdp_mline_index;
5923 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005924 RTC_LOG(LS_ERROR)
5925 << "OnTransportControllerCandidatesGathered: content name "
5926 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005927 return;
5928 }
5929
5930 for (cricket::Candidates::const_iterator citer = candidates.begin();
5931 citer != candidates.end(); ++citer) {
5932 // Use transport_name as the candidate media id.
5933 std::unique_ptr<JsepIceCandidate> candidate(
5934 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5935 if (local_description()) {
5936 mutable_local_description()->AddCandidate(candidate.get());
5937 }
5938 OnIceCandidate(std::move(candidate));
5939 }
5940}
5941
5942void PeerConnection::OnTransportControllerCandidatesRemoved(
5943 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005944 // Sanity check.
5945 for (const cricket::Candidate& candidate : candidates) {
5946 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005947 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005948 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005949 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005950 return;
5951 }
5952 }
5953
5954 if (local_description()) {
5955 mutable_local_description()->RemoveCandidates(candidates);
5956 }
5957 OnIceCandidatesRemoved(candidates);
5958}
5959
5960void PeerConnection::OnTransportControllerDtlsHandshakeError(
5961 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005962 RTC_HISTOGRAM_ENUMERATION(
5963 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5964 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005965}
5966
Steve Antoned10bd92017-12-05 10:52:59 -08005967void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005968 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005969 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005970 if (channel && !channel->enabled()) {
5971 channel->Enable(true);
5972 }
Steve Anton75737c02017-11-06 10:37:17 -08005973 }
5974
Steve Anton4171afb2017-11-20 10:20:22 -08005975 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005976 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005977 }
Steve Anton75737c02017-11-06 10:37:17 -08005978}
5979
5980// Returns the media index for a local ice candidate given the content name.
5981bool PeerConnection::GetLocalCandidateMediaIndex(
5982 const std::string& content_name,
5983 int* sdp_mline_index) {
5984 if (!local_description() || !sdp_mline_index) {
5985 return false;
5986 }
5987
5988 bool content_found = false;
5989 const ContentInfos& contents = local_description()->description()->contents();
5990 for (size_t index = 0; index < contents.size(); ++index) {
5991 if (contents[index].name == content_name) {
5992 *sdp_mline_index = static_cast<int>(index);
5993 content_found = true;
5994 break;
5995 }
5996 }
5997 return content_found;
5998}
5999
6000bool PeerConnection::UseCandidatesInSessionDescription(
6001 const SessionDescriptionInterface* remote_desc) {
6002 if (!remote_desc) {
6003 return true;
6004 }
6005 bool ret = true;
6006
6007 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6008 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6009 for (size_t n = 0; n < candidates->count(); ++n) {
6010 const IceCandidateInterface* candidate = candidates->at(n);
6011 bool valid = false;
6012 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6013 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006014 RTC_LOG(LS_INFO)
6015 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006016 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006017 }
6018 continue;
6019 }
6020 ret = UseCandidate(candidate);
6021 if (!ret) {
6022 break;
6023 }
6024 }
6025 }
6026 return ret;
6027}
6028
6029bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6030 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6031 size_t remote_content_size =
6032 remote_description()->description()->contents().size();
6033 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006034 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006035 return false;
6036 }
6037
6038 cricket::ContentInfo content =
6039 remote_description()->description()->contents()[mediacontent_index];
6040 std::vector<cricket::Candidate> candidates;
6041 candidates.push_back(candidate->candidate());
6042 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006043 RTCError error =
6044 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006045 if (error.ok()) {
6046 // Candidates successfully submitted for checking.
6047 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6048 ice_connection_state_ ==
6049 PeerConnectionInterface::kIceConnectionDisconnected) {
6050 // If state is New, then the session has just gotten its first remote ICE
6051 // candidates, so go to Checking.
6052 // If state is Disconnected, the session is re-using old candidates or
6053 // receiving additional ones, so go to Checking.
6054 // If state is Connected, stay Connected.
6055 // TODO(bemasc): If state is Connected, and the new candidates are for a
6056 // newly added transport, then the state actually _should_ move to
6057 // checking. Add a way to distinguish that case.
6058 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6059 }
6060 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006061 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006062 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006063 }
6064 return true;
6065}
6066
6067void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006068 // Destroy video channel first since it may have a pointer to the
6069 // voice channel.
6070 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006071 if (!video_info || video_info->rejected) {
6072 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006073 }
6074
Steve Anton6fec8802017-12-04 10:37:29 -08006075 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6076 if (!audio_info || audio_info->rejected) {
6077 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006078 }
6079
6080 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6081 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006082 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006083 }
6084}
6085
Steve Antondcc3c022017-12-22 16:02:54 -08006086RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6087 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006088 const cricket::ContentGroup* bundle_group = nullptr;
6089 if (configuration_.bundle_policy ==
6090 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006091 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006092 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006093 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6094 "max-bundle configured but session description "
6095 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006096 }
6097 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006098 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006099}
6100
6101RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006102 // Creating the media channels. Transports should already have been created
6103 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006104 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006105 if (voice && !voice->rejected &&
6106 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006107 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006108 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006109 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6110 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006111 }
6112 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6113 }
6114
Steve Antondcc3c022017-12-22 16:02:54 -08006115 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006116 if (video && !video->rejected &&
6117 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006118 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006119 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006120 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6121 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006122 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006123 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006124 }
6125
Steve Antondcc3c022017-12-22 16:02:54 -08006126 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006127 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006128 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006129 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006130 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6131 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006132 }
6133 }
6134
Steve Anton8a006912017-12-04 15:25:56 -08006135 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006136}
6137
Steve Anton4171afb2017-11-20 10:20:22 -08006138// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006139cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006140 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006141 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006142 MediaTransportInterface* media_transport = nullptr;
6143 if (configuration_.use_media_transport) {
6144 media_transport = GetMediaTransport(mid);
6145 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006146
Steve Anton75737c02017-11-06 10:37:17 -08006147 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006148 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006149 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006150 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006151 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006152 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006153 }
Steve Anton75737c02017-11-06 10:37:17 -08006154 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6155 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006156 voice_channel->SignalSentPacket.connect(this,
6157 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006158 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006159
Steve Antoneda6ccd2017-12-04 10:21:55 -08006160 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006161}
6162
Steve Anton4171afb2017-11-20 10:20:22 -08006163// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006164cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006165 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006166 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006167 MediaTransportInterface* media_transport = nullptr;
6168 if (configuration_.use_media_transport) {
6169 media_transport = GetMediaTransport(mid);
6170 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006171
Steve Anton75737c02017-11-06 10:37:17 -08006172 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006173 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006174 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006175 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006176 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006177 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006178 }
Steve Anton75737c02017-11-06 10:37:17 -08006179 video_channel->SignalDtlsSrtpSetupFailure.connect(
6180 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006181 video_channel->SignalSentPacket.connect(this,
6182 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006183 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006184
Steve Antoneda6ccd2017-12-04 10:21:55 -08006185 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006186}
6187
Zhi Huange830e682018-03-30 10:48:35 -07006188bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006189 switch (data_channel_type_) {
6190 case cricket::DCT_MEDIA_TRANSPORT:
6191 if (network_thread()->Invoke<bool>(
6192 RTC_FROM_HERE,
6193 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6194 this, mid))) {
6195 for (const auto& channel : sctp_data_channels_) {
6196 channel->OnTransportChannelCreated();
6197 }
6198 return true;
6199 }
Steve Anton75737c02017-11-06 10:37:17 -08006200 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006201 case cricket::DCT_SCTP:
6202 if (!sctp_factory_) {
6203 RTC_LOG(LS_ERROR)
6204 << "Trying to create SCTP transport, but didn't compile with "
6205 "SCTP support (HAVE_SCTP)";
6206 return false;
6207 }
6208 if (!network_thread()->Invoke<bool>(
6209 RTC_FROM_HERE,
6210 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6211 return false;
6212 }
6213 for (const auto& channel : sctp_data_channels_) {
6214 channel->OnTransportChannelCreated();
6215 }
6216 return true;
6217 case cricket::DCT_RTP:
6218 default:
6219 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6220 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6221 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006222 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006223 if (!rtp_data_channel_) {
6224 return false;
6225 }
6226 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6227 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6228 rtp_data_channel_->SignalSentPacket.connect(
6229 this, &PeerConnection::OnSentPacket_w);
6230 rtp_data_channel_->SetRtpTransport(rtp_transport);
6231 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006232 }
6233
Steve Anton75737c02017-11-06 10:37:17 -08006234 return true;
6235}
6236
6237Call::Stats PeerConnection::GetCallStats() {
6238 if (!worker_thread()->IsCurrent()) {
6239 return worker_thread()->Invoke<Call::Stats>(
6240 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6241 }
6242 if (call_) {
6243 return call_->GetStats();
6244 } else {
6245 return Call::Stats();
6246 }
6247}
6248
Zhi Huange830e682018-03-30 10:48:35 -07006249bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006250 RTC_DCHECK(network_thread()->IsCurrent());
6251 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006252 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6253 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006254 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006255 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006256 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006257 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6258 sctp_factory_->CreateSctpTransport(dtls_transport);
6259 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006260 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006261 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006262 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006263 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006264 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006265 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6266 // another thread. Would be nice if there was a helper class similar to
6267 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6268 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006269 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006270 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006271 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006272 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006273 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006274 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6275 std::move(cricket_sctp_transport));
6276 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006277 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006278}
6279
6280void PeerConnection::DestroySctpTransport_n() {
6281 RTC_DCHECK(network_thread()->IsCurrent());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006282 sctp_transport_->Clear();
6283 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006284 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006285 sctp_invoker_.reset(nullptr);
6286 sctp_ready_to_send_data_ = false;
6287}
6288
6289void PeerConnection::OnSctpTransportReadyToSendData_n() {
6290 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6291 RTC_DCHECK(network_thread()->IsCurrent());
6292 // Note: Cannot use rtc::Bind here because it will grab a reference to
6293 // PeerConnection and potentially cause PeerConnection to live longer than
6294 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6295 // be destroyed before PeerConnection is destroyed, and at that point all
6296 // pending tasks will be cleared.
6297 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6298 OnSctpTransportReadyToSendData_s(true);
6299 });
6300}
6301
6302void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6303 RTC_DCHECK(signaling_thread()->IsCurrent());
6304 sctp_ready_to_send_data_ = ready;
6305 SignalSctpReadyToSendData(ready);
6306}
6307
6308void PeerConnection::OnSctpTransportDataReceived_n(
6309 const cricket::ReceiveDataParams& params,
6310 const rtc::CopyOnWriteBuffer& payload) {
6311 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6312 RTC_DCHECK(network_thread()->IsCurrent());
6313 // Note: Cannot use rtc::Bind here because it will grab a reference to
6314 // PeerConnection and potentially cause PeerConnection to live longer than
6315 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6316 // be destroyed before PeerConnection is destroyed, and at that point all
6317 // pending tasks will be cleared.
6318 sctp_invoker_->AsyncInvoke<void>(
6319 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6320 OnSctpTransportDataReceived_s(params, payload);
6321 });
6322}
6323
6324void PeerConnection::OnSctpTransportDataReceived_s(
6325 const cricket::ReceiveDataParams& params,
6326 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006327 RTC_DCHECK_RUN_ON(signaling_thread());
6328 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006329 SignalSctpDataReceived(params, payload);
6330 }
6331}
6332
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006333void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006334 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6335 RTC_DCHECK(network_thread()->IsCurrent());
6336 sctp_invoker_->AsyncInvoke<void>(
6337 RTC_FROM_HERE, signaling_thread(),
6338 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006339 &SignalSctpClosingProcedureStartedRemotely, sid));
6340}
6341
6342void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6343 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6344 RTC_DCHECK(network_thread()->IsCurrent());
6345 sctp_invoker_->AsyncInvoke<void>(
6346 RTC_FROM_HERE, signaling_thread(),
6347 rtc::Bind(&sigslot::signal1<int>::operator(),
6348 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006349}
6350
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006351bool PeerConnection::SetupMediaTransportForDataChannels_n(
6352 const std::string& mid) {
6353 media_transport_ = transport_controller_->GetMediaTransport(mid);
6354 if (!media_transport_) {
6355 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6356 return false;
6357 }
6358
6359 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6360 media_transport_->SetDataSink(this);
6361 media_transport_data_mid_ = mid;
6362 transport_controller_->SignalMediaTransportStateChanged.connect(
6363 this, &PeerConnection::OnMediaTransportStateChanged_n);
6364 // Check the initial state right away, in case transport is already writable.
6365 OnMediaTransportStateChanged_n();
6366 return true;
6367}
6368
6369void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6370 if (!media_transport_) {
6371 return;
6372 }
6373 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6374 media_transport_data_mid_.reset();
6375 media_transport_->SetDataSink(nullptr);
6376 media_transport_invoker_ = nullptr;
6377 media_transport_ = nullptr;
6378}
6379
6380void PeerConnection::OnMediaTransportStateChanged_n() {
6381 if (!media_transport_data_mid_ ||
6382 transport_controller_->GetMediaTransportState(
6383 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6384 return;
6385 }
6386 media_transport_invoker_->AsyncInvoke<void>(
6387 RTC_FROM_HERE, signaling_thread(), [this] {
6388 RTC_DCHECK_RUN_ON(signaling_thread());
6389 media_transport_ready_to_send_data_ = true;
6390 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6391 });
6392}
6393
Steve Anton75737c02017-11-06 10:37:17 -08006394// Returns false if bundle is enabled and rtcp_mux is disabled.
6395bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6396 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6397 if (!bundle_enabled)
6398 return true;
6399
6400 const cricket::ContentGroup* bundle_group =
6401 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6402 RTC_DCHECK(bundle_group != NULL);
6403
6404 const cricket::ContentInfos& contents = desc->contents();
6405 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6406 citer != contents.end(); ++citer) {
6407 const cricket::ContentInfo* content = (&*citer);
6408 RTC_DCHECK(content != NULL);
6409 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006410 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006411 if (!HasRtcpMuxEnabled(content))
6412 return false;
6413 }
6414 }
6415 // RTCP-MUX is enabled in all the contents.
6416 return true;
6417}
6418
6419bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006420 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006421}
6422
Steve Anton06817cd2018-12-18 15:55:30 -08006423static RTCError ValidateMids(const cricket::SessionDescription& description) {
6424 std::set<std::string> mids;
6425 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006426 if (content.name.empty()) {
6427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6428 "A media section is missing a MID attribute.");
6429 }
Steve Anton06817cd2018-12-18 15:55:30 -08006430 if (!mids.insert(content.name).second) {
6431 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6432 "Duplicate a=mid value '" + content.name + "'.");
6433 }
6434 }
6435 return RTCError::OK();
6436}
6437
Steve Anton8a006912017-12-04 15:25:56 -08006438RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006439 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006440 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006441 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006442 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006443 }
6444
6445 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006446 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006447 }
6448
Steve Anton3828c062017-12-06 10:34:51 -08006449 SdpType type = sdesc->GetType();
6450 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6451 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006452 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006453 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006454 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006455 }
6456
Steve Anton06817cd2018-12-18 15:55:30 -08006457 RTCError error = ValidateMids(*sdesc->description());
6458 if (!error.ok()) {
6459 return error;
6460 }
6461
Steve Anton75737c02017-11-06 10:37:17 -08006462 // Verify crypto settings.
6463 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006464 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6465 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006466 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006467 if (!crypto_error.ok()) {
6468 return crypto_error;
6469 }
Steve Anton75737c02017-11-06 10:37:17 -08006470 }
6471
6472 // Verify ice-ufrag and ice-pwd.
6473 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006474 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6475 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006476 }
6477
6478 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006479 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6480 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006481 }
6482
6483 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6484 // m-lines that do not rtcp-mux enabled.
6485
6486 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006487 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006488 // With an answer we want to compare the new answer session description with
6489 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006490 const cricket::SessionDescription* offer_desc =
6491 (source == cricket::CS_LOCAL) ? remote_description()->description()
6492 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006493 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6494 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6495 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006496 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6497 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006498 }
6499 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006500 // The re-offers should respect the order of m= sections in current
6501 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006502 // With a re-offer, either the current local or current remote descriptions
6503 // could be the most up to date, so we would like to check against both of
6504 // them if they exist. It could be the case that one of them has a 0 port
6505 // for a media section, but the other does not. This is important to check
6506 // against in the case that we are recycling an m= section.
6507 const cricket::SessionDescription* current_desc = nullptr;
6508 const cricket::SessionDescription* secondary_current_desc = nullptr;
6509 if (local_description()) {
6510 current_desc = local_description()->description();
6511 if (remote_description()) {
6512 secondary_current_desc = remote_description()->description();
6513 }
6514 } else if (remote_description()) {
6515 current_desc = remote_description()->description();
6516 }
Steve Anton75737c02017-11-06 10:37:17 -08006517 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006518 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6519 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006520 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6521 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006522 }
6523 }
6524
Steve Antonba42e992018-04-09 14:10:01 -07006525 if (IsUnifiedPlan()) {
6526 // Ensure that each audio and video media section has at most one
6527 // "StreamParams". This will return an error if receiving a session
6528 // description from a "Plan B" endpoint which adds multiple tracks of the
6529 // same type. With Unified Plan, there can only be at most one track per
6530 // media section.
6531 for (const ContentInfo& content : sdesc->description()->contents()) {
6532 const MediaContentDescription& desc = *content.description;
6533 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6534 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6535 desc.streams().size() > 1u) {
6536 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6537 "Media section has more than one track specified "
6538 "with a=ssrc lines which is not supported with "
6539 "Unified Plan.");
6540 }
6541 }
6542 }
6543
Steve Anton8a006912017-12-04 15:25:56 -08006544 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006545}
6546
Steve Anton3828c062017-12-06 10:34:51 -08006547bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006548 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006549 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006550 return (state == PeerConnectionInterface::kStable) ||
6551 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006552 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006553 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006554 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6555 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6556 }
6557}
6558
Steve Anton3828c062017-12-06 10:34:51 -08006559bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006560 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006561 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006562 return (state == PeerConnectionInterface::kStable) ||
6563 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006564 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006565 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006566 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6567 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6568 }
6569}
6570
Steve Antonf8470812017-12-04 10:46:21 -08006571const char* PeerConnection::SessionErrorToString(SessionError error) const {
6572 switch (error) {
6573 case SessionError::kNone:
6574 return "ERROR_NONE";
6575 case SessionError::kContent:
6576 return "ERROR_CONTENT";
6577 case SessionError::kTransport:
6578 return "ERROR_TRANSPORT";
6579 }
6580 RTC_NOTREACHED();
6581 return "";
6582}
6583
Steve Anton75737c02017-11-06 10:37:17 -08006584std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006585 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006586 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6587 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006588 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006589}
6590
Steve Anton8e20f172018-03-06 10:55:04 -08006591void PeerConnection::ReportSdpFormatReceived(
6592 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006593 int num_audio_mlines = 0;
6594 int num_video_mlines = 0;
6595 int num_audio_tracks = 0;
6596 int num_video_tracks = 0;
6597 for (const ContentInfo& content : remote_offer.description()->contents()) {
6598 cricket::MediaType media_type = content.media_description()->type();
6599 int num_tracks = std::max(
6600 1, static_cast<int>(content.media_description()->streams().size()));
6601 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6602 num_audio_mlines += 1;
6603 num_audio_tracks += num_tracks;
6604 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6605 num_video_mlines += 1;
6606 num_video_tracks += num_tracks;
6607 }
6608 }
6609 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6610 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6611 format = kSdpFormatReceivedComplexUnifiedPlan;
6612 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6613 format = kSdpFormatReceivedComplexPlanB;
6614 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6615 format = kSdpFormatReceivedSimple;
6616 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006617 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6618 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006619}
6620
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006621void PeerConnection::NoteUsageEvent(UsageEvent event) {
6622 RTC_DCHECK_RUN_ON(signaling_thread());
6623 usage_event_accumulator_ |= static_cast<int>(event);
6624}
6625
6626void PeerConnection::ReportUsagePattern() const {
6627 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006628 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6629 usage_event_accumulator_,
6630 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006631 const int bad_bits =
6632 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6633 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6634 const int good_bits =
6635 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6636 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6637 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6638 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6639 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006640 // If called after close(), we can't report, because observer may have
6641 // been deallocated, and therefore pointer is null. Write to log instead.
6642 if (observer_) {
6643 Observer()->OnInterestingUsage(usage_event_accumulator_);
6644 } else {
6645 RTC_LOG(LS_INFO) << "Interesting usage signature "
6646 << usage_event_accumulator_
6647 << " observed after observer shutdown";
6648 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006649 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006650}
6651
Steve Anton0ffaaa22018-02-23 10:31:30 -08006652void PeerConnection::ReportNegotiatedSdpSemantics(
6653 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006654 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006655 switch (answer.description()->msid_signaling()) {
6656 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006657 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006658 break;
6659 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006660 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006661 break;
6662 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006663 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006664 break;
6665 case cricket::kMsidSignalingMediaSection |
6666 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006667 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006668 break;
6669 default:
6670 RTC_NOTREACHED();
6671 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006672 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6673 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006674}
6675
Steve Anton75737c02017-11-06 10:37:17 -08006676// We need to check the local/remote description for the Transport instead of
6677// the session, because a new Transport added during renegotiation may have
6678// them unset while the session has them set from the previous negotiation.
6679// Not doing so may trigger the auto generation of transport description and
6680// mess up DTLS identity information, ICE credential, etc.
6681bool PeerConnection::ReadyToUseRemoteCandidate(
6682 const IceCandidateInterface* candidate,
6683 const SessionDescriptionInterface* remote_desc,
6684 bool* valid) {
6685 *valid = true;
6686
6687 const SessionDescriptionInterface* current_remote_desc =
6688 remote_desc ? remote_desc : remote_description();
6689
6690 if (!current_remote_desc) {
6691 return false;
6692 }
6693
6694 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6695 size_t remote_content_size =
6696 current_remote_desc->description()->contents().size();
6697 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006698 RTC_LOG(LS_ERROR)
6699 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6700 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006701
6702 *valid = false;
6703 return false;
6704 }
6705
6706 cricket::ContentInfo content =
6707 current_remote_desc->description()->contents()[mediacontent_index];
6708
6709 const std::string transport_name = GetTransportName(content.name);
6710 if (transport_name.empty()) {
6711 return false;
6712 }
Zhi Huange830e682018-03-30 10:48:35 -07006713 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006714}
6715
6716bool PeerConnection::SrtpRequired() const {
6717 return dtls_enabled_ ||
6718 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6719}
6720
6721void PeerConnection::OnTransportControllerGatheringState(
6722 cricket::IceGatheringState state) {
6723 RTC_DCHECK(signaling_thread()->IsCurrent());
6724 if (state == cricket::kIceGatheringGathering) {
6725 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6726 } else if (state == cricket::kIceGatheringComplete) {
6727 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6728 }
6729}
6730
6731void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006732 std::map<std::string, std::set<cricket::MediaType>>
6733 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006734 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006735 if (transceiver->internal()->channel()) {
6736 const std::string& transport_name =
6737 transceiver->internal()->channel()->transport_name();
6738 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006739 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006740 }
Steve Anton75737c02017-11-06 10:37:17 -08006741 }
6742 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006743 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6744 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006745 }
Zhi Huange830e682018-03-30 10:48:35 -07006746
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006747 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006748 if (transport_name) {
6749 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006750 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006751 }
Zhi Huange830e682018-03-30 10:48:35 -07006752
Steve Antonc7b964c2018-02-01 14:39:45 -08006753 for (const auto& entry : media_types_by_transport_name) {
6754 const std::string& transport_name = entry.first;
6755 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006756 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006757 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006758 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006759 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006760 }
6761 }
6762}
6763// Walk through the ConnectionInfos to gather best connection usage
6764// for IPv4 and IPv6.
6765void PeerConnection::ReportBestConnectionState(
6766 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006767 for (const cricket::TransportChannelStats& channel_stats :
6768 stats.channel_stats) {
6769 for (const cricket::ConnectionInfo& connection_info :
6770 channel_stats.connection_infos) {
6771 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006772 continue;
6773 }
6774
Steve Antonc7b964c2018-02-01 14:39:45 -08006775 const cricket::Candidate& local = connection_info.local_candidate;
6776 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006777
6778 // Increment the counter for IceCandidatePairType.
6779 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6780 (local.type() == RELAY_PORT_TYPE &&
6781 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006782 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6783 GetIceCandidatePairCounter(local, remote),
6784 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006785 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006786 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6787 GetIceCandidatePairCounter(local, remote),
6788 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006789 } else {
6790 RTC_CHECK(0);
6791 }
Steve Anton75737c02017-11-06 10:37:17 -08006792
6793 // Increment the counter for IP type.
6794 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006795 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6796 kBestConnections_IPv4,
6797 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006798 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006799 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6800 kBestConnections_IPv6,
6801 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006802 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006803 RTC_CHECK(!local.address().hostname().empty() &&
6804 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006805 }
6806
6807 return;
6808 }
6809 }
6810}
6811
6812void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006813 const cricket::TransportStats& stats,
6814 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006815 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6816 return;
6817 }
6818
6819 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6820 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6821 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6822 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6823 return;
6824 }
6825
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006826 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6827 for (cricket::MediaType media_type : media_types) {
6828 switch (media_type) {
6829 case cricket::MEDIA_TYPE_AUDIO:
6830 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6831 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6832 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6833 break;
6834 case cricket::MEDIA_TYPE_VIDEO:
6835 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6836 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6837 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6838 break;
6839 case cricket::MEDIA_TYPE_DATA:
6840 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6841 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6842 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6843 break;
6844 default:
6845 RTC_NOTREACHED();
6846 continue;
6847 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006848 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006849 }
6850
6851 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6852 for (cricket::MediaType media_type : media_types) {
6853 switch (media_type) {
6854 case cricket::MEDIA_TYPE_AUDIO:
6855 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6856 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6857 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6858 break;
6859 case cricket::MEDIA_TYPE_VIDEO:
6860 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6861 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6862 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6863 break;
6864 case cricket::MEDIA_TYPE_DATA:
6865 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6866 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6867 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6868 break;
6869 default:
6870 RTC_NOTREACHED();
6871 continue;
6872 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006873 }
Steve Anton75737c02017-11-06 10:37:17 -08006874 }
6875}
6876
6877void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6878 RTC_DCHECK(worker_thread()->IsCurrent());
6879 RTC_DCHECK(call_);
6880 call_->OnSentPacket(sent_packet);
6881}
6882
6883const std::string PeerConnection::GetTransportName(
6884 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006885 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006886 if (channel) {
6887 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006888 }
Steve Anton6fec8802017-12-04 10:37:29 -08006889 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006890 RTC_DCHECK(sctp_mid_);
6891 if (content_name == *sctp_mid_) {
6892 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006893 }
6894 }
6895 // Return an empty string if failed to retrieve the transport name.
6896 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006897}
6898
Steve Anton6fec8802017-12-04 10:37:29 -08006899void PeerConnection::DestroyTransceiverChannel(
6900 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6901 transceiver) {
6902 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006903
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006904 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006905 if (channel) {
6906 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006907 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006908 }
6909}
6910
6911void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006912 if (rtp_data_channel_) {
6913 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006914 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006915 rtp_data_channel_ = nullptr;
6916 }
6917
6918 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6919 // grab a reference to this PeerConnection. If this is called from the
6920 // PeerConnection destructor, the RefCountedObject vtable will have already
6921 // been destroyed (since it is a subclass of PeerConnection) and using
6922 // rtc::Bind will cause "Pure virtual function called" error to appear.
6923
6924 if (sctp_transport_) {
6925 OnDataChannelDestroyed();
6926 network_thread()->Invoke<void>(RTC_FROM_HERE,
6927 [this] { DestroySctpTransport_n(); });
6928 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006929
6930 if (media_transport_) {
6931 OnDataChannelDestroyed();
6932 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6933 RTC_DCHECK_RUN_ON(network_thread());
6934 TeardownMediaTransportForDataChannels_n();
6935 });
6936 }
Steve Anton6fec8802017-12-04 10:37:29 -08006937}
6938
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006939void PeerConnection::DestroyChannelInterface(
6940 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006941 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006942 switch (channel->media_type()) {
6943 case cricket::MEDIA_TYPE_AUDIO:
6944 channel_manager()->DestroyVoiceChannel(
6945 static_cast<cricket::VoiceChannel*>(channel));
6946 break;
6947 case cricket::MEDIA_TYPE_VIDEO:
6948 channel_manager()->DestroyVideoChannel(
6949 static_cast<cricket::VideoChannel*>(channel));
6950 break;
6951 case cricket::MEDIA_TYPE_DATA:
6952 channel_manager()->DestroyRtpDataChannel(
6953 static_cast<cricket::RtpDataChannel*>(channel));
6954 break;
6955 default:
6956 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6957 break;
6958 }
Zhi Huange830e682018-03-30 10:48:35 -07006959}
Steve Anton6fec8802017-12-04 10:37:29 -08006960
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006961bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006962 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006963 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006964 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006965 MediaTransportInterface* media_transport) {
Karl Wiberg5966c502019-02-21 23:55:09 +01006966 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006967 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006968 auto base_channel = GetChannel(mid);
6969 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006970 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006971 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006972 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006973 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006974 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006975
Karl Wiberg5966c502019-02-21 23:55:09 +01006976 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006977 // Only pass media transport to call object if media transport is used
6978 // for media (and not data channel).
6979 call_->MediaTransportChange(media_transport);
6980 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006981
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006982 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006983}
6984
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006985PeerConnectionObserver* PeerConnection::Observer() const {
6986 // In earlier production code, the pointer was not cleared on close,
6987 // which might have led to undefined behavior if the observer was not
6988 // deallocated, or strange crashes if it was.
6989 // We use CHECK in order to catch such behavior if it exists.
6990 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6991 RTC_CHECK(observer_);
6992 return observer_;
6993}
6994
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006995CryptoOptions PeerConnection::GetCryptoOptions() {
6996 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6997 // after it has been removed.
6998 return configuration_.crypto_options.has_value()
6999 ? *configuration_.crypto_options
7000 : factory_->options().crypto_options;
7001}
7002
Harald Alvestrand89061872018-01-02 14:08:34 +01007003void PeerConnection::ClearStatsCache() {
7004 if (stats_collector_) {
7005 stats_collector_->ClearCachedStatsReport();
7006 }
7007}
7008
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007009void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007010 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7011 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007012}
7013
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007014} // namespace webrtc