blob: 6a5f925732bd438c73a77ab15c7265a0341a5b0c [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) Slatalab1ae10b2019-03-01 11:14:05 -08001004 if (configuration.use_media_transport ||
1005 configuration.use_media_transport_for_data_channels) {
1006 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1007 // RTP media transport is introduced. But until then, we require SDES to
1008 // be enabled.
1009 if (configuration.enable_dtls_srtp.has_value() &&
1010 configuration.enable_dtls_srtp.value()) {
1011 RTC_LOG(LS_WARNING)
1012 << "When media transport is used, SDES must be enabled. Set "
1013 "configuration.enable_dtls_srtp to false. use_media_transport="
1014 << configuration.use_media_transport
1015 << ", use_media_transport_for_data_channels="
1016 << configuration.use_media_transport_for_data_channels;
1017 return false;
1018 }
1019 }
1020
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001021 config.use_media_transport_for_media = configuration.use_media_transport;
1022 config.use_media_transport_for_data_channels =
1023 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001024 config.media_transport_factory = factory_->media_transport_factory();
1025 }
1026
Zhi Huange830e682018-03-30 10:48:35 -07001027 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001028 signaling_thread(), network_thread(), port_allocator_.get(),
1029 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001030 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001031 this, &PeerConnection::OnTransportControllerConnectionState);
1032 transport_controller_->SignalStandardizedIceConnectionState.connect(
1033 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001034 transport_controller_->SignalConnectionState.connect(
1035 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001036 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001037 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001038 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001039 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001040 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001041 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1042 transport_controller_->SignalDtlsHandshakeError.connect(
1043 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1044
1045 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001046
deadbeefab9b2d12015-10-14 11:33:11 -07001047 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001048 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049
Steve Antonba818672017-11-06 10:21:57 -08001050 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001051 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001052
Steve Anton75737c02017-11-06 10:37:17 -08001053 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1054 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1055 if (!configuration.certificates.empty()) {
1056 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1057 // just picking the first one. The decision should be made based on the DTLS
1058 // handshake. The DTLS negotiations need to know about all certificates.
1059 certificate = configuration.certificates[0];
1060 }
1061
Steve Antond25da372017-11-06 14:50:29 -08001062 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001063
1064 if (options.disable_encryption) {
1065 dtls_enabled_ = false;
1066 } else {
1067 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001068 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001069 // |configuration| can override the default |dtls_enabled_| value.
1070 if (configuration.enable_dtls_srtp) {
1071 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1072 }
1073 }
1074
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001075 if (configuration.use_media_transport_for_data_channels) {
1076 if (configuration.enable_rtp_data_channel) {
1077 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1078 "use_media_transport_for_data_channels are "
1079 "incompatible and cannot both be set to true";
1080 return false;
1081 }
1082 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1083 } else if (configuration.enable_rtp_data_channel) {
1084 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1085 // set. It takes precendence over the disable_sctp_data_channels
1086 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001087 data_channel_type_ = cricket::DCT_RTP;
1088 } else {
1089 // DTLS has to be enabled to use SCTP.
1090 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1091 data_channel_type_ = cricket::DCT_SCTP;
1092 }
1093 }
1094
1095 video_options_.screencast_min_bitrate_kbps =
1096 configuration.screencast_min_bitrate;
1097 audio_options_.combined_audio_video_bwe =
1098 configuration.combined_audio_video_bwe;
1099
1100 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001101 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001102
1103 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001104 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001105
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001106 audio_options_.audio_jitter_buffer_min_delay_ms =
1107 configuration.audio_jitter_buffer_min_delay_ms;
1108
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001109 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1110 configuration.audio_jitter_buffer_enable_rtx_handling;
1111
Steve Anton75737c02017-11-06 10:37:17 -08001112 // Whether the certificate generator/certificate is null or not determines
1113 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1114 // the right instructions by clearing the variables if needed.
1115 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001116 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001117 certificate = nullptr;
1118 } else if (certificate) {
1119 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001120 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001121 }
1122
1123 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1124 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001125 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001126 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1127 this, &PeerConnection::OnCertificateReady);
1128
1129 if (options.disable_encryption) {
1130 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1131 }
1132
1133 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001134 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001135 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001136
Steve Anton4171afb2017-11-20 10:20:22 -08001137 // Add default audio/video transceivers for Plan B SDP.
1138 if (!IsUnifiedPlan()) {
1139 transceivers_.push_back(
1140 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1141 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1142 transceivers_.push_back(
1143 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1144 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1145 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001146 int delay_ms =
1147 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001148 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1149 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150 return true;
1151}
1152
Steve Anton038834f2017-07-14 15:59:59 -07001153RTCError PeerConnection::ValidateConfiguration(
1154 const RTCConfiguration& config) const {
1155 if (config.ice_regather_interval_range &&
1156 config.continual_gathering_policy == GATHER_ONCE) {
1157 return RTCError(RTCErrorType::INVALID_PARAMETER,
1158 "ice_regather_interval_range specified but continual "
1159 "gathering policy is GATHER_ONCE");
1160 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001161 auto result =
1162 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1163 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001164}
1165
Yves Gerey665174f2018-06-19 15:03:05 +02001166rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001167 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001168 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1169 "Plan SdpSemantics. Please use GetSenders "
1170 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001171 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172}
1173
Yves Gerey665174f2018-06-19 15:03:05 +02001174rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001175 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001176 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1177 "Plan SdpSemantics. Please use GetReceivers "
1178 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001179 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001180}
1181
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001182bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001183 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001184 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1185 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001186 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 if (IsClosed()) {
1188 return false;
1189 }
deadbeefab9b2d12015-10-14 11:33:11 -07001190 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 return false;
1192 }
deadbeefab9b2d12015-10-14 11:33:11 -07001193
1194 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001195 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1196 observer->SignalAudioTrackAdded.connect(this,
1197 &PeerConnection::OnAudioTrackAdded);
1198 observer->SignalAudioTrackRemoved.connect(
1199 this, &PeerConnection::OnAudioTrackRemoved);
1200 observer->SignalVideoTrackAdded.connect(this,
1201 &PeerConnection::OnVideoTrackAdded);
1202 observer->SignalVideoTrackRemoved.connect(
1203 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001204 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001205
deadbeefab9b2d12015-10-14 11:33:11 -07001206 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001207 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001208 }
1209 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001210 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001211 }
1212
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001213 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001214 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001215 return true;
1216}
1217
1218void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001219 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001220 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1221 "Plan SdpSemantics. Please use RemoveTrack "
1222 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001223 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001224 if (!IsClosed()) {
1225 for (const auto& track : local_stream->GetAudioTracks()) {
1226 RemoveAudioTrack(track.get(), local_stream);
1227 }
1228 for (const auto& track : local_stream->GetVideoTracks()) {
1229 RemoveVideoTrack(track.get(), local_stream);
1230 }
deadbeefab9b2d12015-10-14 11:33:11 -07001231 }
deadbeefab9b2d12015-10-14 11:33:11 -07001232 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001233 stream_observers_.erase(
1234 std::remove_if(
1235 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001236 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001237 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001238 }),
1239 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001240
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241 if (IsClosed()) {
1242 return;
1243 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001244 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245}
1246
Steve Anton2d6c76a2018-01-05 17:10:52 -08001247RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001248 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001249 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001250 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001251 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001252 if (!track) {
1253 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1254 }
1255 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1256 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1257 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1258 "Track has invalid kind: " + track->kind());
1259 }
Steve Antonf9381f02017-12-14 10:23:57 -08001260 if (IsClosed()) {
1261 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1262 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001263 }
Steve Anton4171afb2017-11-20 10:20:22 -08001264 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001265 LOG_AND_RETURN_ERROR(
1266 RTCErrorType::INVALID_PARAMETER,
1267 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001268 }
Steve Antonf9381f02017-12-14 10:23:57 -08001269 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001270 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1271 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001272 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001273 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001274 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001275 }
1276 return sender_or_error;
1277}
deadbeefe1f9d832016-01-14 15:35:42 -08001278
Steve Antonf9381f02017-12-14 10:23:57 -08001279RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1280PeerConnection::AddTrackPlanB(
1281 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001282 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001283 if (stream_ids.size() > 1u) {
1284 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1285 "AddTrack with more than one stream is not "
1286 "supported with Plan B semantics.");
1287 }
1288 std::vector<std::string> adjusted_stream_ids = stream_ids;
1289 if (adjusted_stream_ids.empty()) {
1290 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1291 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001292 cricket::MediaType media_type =
1293 (track->kind() == MediaStreamTrackInterface::kAudioKind
1294 ? cricket::MEDIA_TYPE_AUDIO
1295 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001296 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001297 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001298 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001299 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001300 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001301 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001302 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001303 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001304 if (sender_info) {
1305 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001306 }
Steve Antonf9381f02017-12-14 10:23:57 -08001307 } else {
1308 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001309 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001310 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001311 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001312 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001313 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001314 if (sender_info) {
1315 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001316 }
deadbeefe1f9d832016-01-14 15:35:42 -08001317 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001318 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001319}
deadbeefe1f9d832016-01-14 15:35:42 -08001320
Steve Antonf9381f02017-12-14 10:23:57 -08001321RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1322PeerConnection::AddTrackUnifiedPlan(
1323 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001324 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001325 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1326 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001327 RTC_LOG(LS_INFO) << "Reusing an existing "
1328 << cricket::MediaTypeToString(transceiver->media_type())
1329 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001330 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001331 transceiver->internal()->set_direction(
1332 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001333 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001334 transceiver->internal()->set_direction(
1335 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001336 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001337 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001338 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001339 } else {
1340 cricket::MediaType media_type =
1341 (track->kind() == MediaStreamTrackInterface::kAudioKind
1342 ? cricket::MEDIA_TYPE_AUDIO
1343 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001344 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1345 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001346 std::string sender_id = track->id();
1347 // Avoid creating a sender with an existing ID by generating a random ID.
1348 // This can happen if this is the second time AddTrack has created a sender
1349 // for this track.
1350 if (FindSenderById(sender_id)) {
1351 sender_id = rtc::CreateRandomUuid();
1352 }
Florent Castelli892acf02018-10-01 22:47:20 +02001353 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001354 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1355 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001356 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001357 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001358 }
Steve Antonf9381f02017-12-14 10:23:57 -08001359 return transceiver->sender();
1360}
1361
1362rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1363PeerConnection::FindFirstTransceiverForAddedTrack(
1364 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1365 RTC_DCHECK(track);
1366 for (auto transceiver : transceivers_) {
1367 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001368 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001369 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001370 !transceiver->internal()->has_ever_been_used_to_send() &&
1371 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001372 return transceiver;
1373 }
1374 }
1375 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001376}
1377
1378bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1379 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001380 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001381}
1382
Steve Anton24db5732018-07-23 10:27:33 -07001383RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001384 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001385 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001386 if (!sender) {
1387 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1388 }
deadbeefe1f9d832016-01-14 15:35:42 -08001389 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001390 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1391 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001392 }
Steve Antonf9381f02017-12-14 10:23:57 -08001393 if (IsUnifiedPlan()) {
1394 auto transceiver = FindTransceiverBySender(sender);
1395 if (!transceiver || !sender->track()) {
1396 return RTCError::OK();
1397 }
1398 sender->SetTrack(nullptr);
1399 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001400 transceiver->internal()->set_direction(
1401 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001402 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001403 transceiver->internal()->set_direction(
1404 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001405 }
Steve Anton4171afb2017-11-20 10:20:22 -08001406 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001407 bool removed;
1408 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1409 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1410 } else {
1411 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1412 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1413 }
1414 if (!removed) {
1415 LOG_AND_RETURN_ERROR(
1416 RTCErrorType::INVALID_PARAMETER,
1417 "Couldn't find sender " + sender->id() + " to remove.");
1418 }
Steve Anton4171afb2017-11-20 10:20:22 -08001419 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001420 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001421 return RTCError::OK();
1422}
1423
1424rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1425PeerConnection::FindTransceiverBySender(
1426 rtc::scoped_refptr<RtpSenderInterface> sender) {
1427 for (auto transceiver : transceivers_) {
1428 if (transceiver->sender() == sender) {
1429 return transceiver;
1430 }
1431 }
1432 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001433}
1434
Steve Anton9158ef62017-11-27 13:01:52 -08001435RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1436PeerConnection::AddTransceiver(
1437 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1438 return AddTransceiver(track, RtpTransceiverInit());
1439}
1440
1441RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1442PeerConnection::AddTransceiver(
1443 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1444 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001445 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001446 RTC_CHECK(IsUnifiedPlan())
1447 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001448 if (!track) {
1449 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1450 }
1451 cricket::MediaType media_type;
1452 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1453 media_type = cricket::MEDIA_TYPE_AUDIO;
1454 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1455 media_type = cricket::MEDIA_TYPE_VIDEO;
1456 } else {
1457 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1458 "Track kind is not audio or video");
1459 }
1460 return AddTransceiver(media_type, track, init);
1461}
1462
1463RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1464PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1465 return AddTransceiver(media_type, RtpTransceiverInit());
1466}
1467
1468RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1469PeerConnection::AddTransceiver(cricket::MediaType media_type,
1470 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001471 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001472 RTC_CHECK(IsUnifiedPlan())
1473 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001474 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1475 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1476 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1477 "media type is not audio or video");
1478 }
1479 return AddTransceiver(media_type, nullptr, init);
1480}
1481
1482RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1483PeerConnection::AddTransceiver(
1484 cricket::MediaType media_type,
1485 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001486 const RtpTransceiverInit& init,
1487 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001488 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1489 media_type == cricket::MEDIA_TYPE_VIDEO));
1490 if (track) {
1491 RTC_DCHECK_EQ(media_type,
1492 (track->kind() == MediaStreamTrackInterface::kAudioKind
1493 ? cricket::MEDIA_TYPE_AUDIO
1494 : cricket::MEDIA_TYPE_VIDEO));
1495 }
1496
Amit Hilbuchaa584152019-02-06 17:09:52 -08001497 size_t num_rids = absl::c_count_if(init.send_encodings,
1498 [](const RtpEncodingParameters& encoding) {
1499 return !encoding.rid.empty();
1500 });
1501 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001502 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001503 RTCErrorType::INVALID_PARAMETER,
1504 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001505 }
1506
Amit Hilbuchaa584152019-02-06 17:09:52 -08001507 if (absl::c_any_of(init.send_encodings,
1508 [](const RtpEncodingParameters& encoding) {
1509 return encoding.ssrc.has_value();
1510 })) {
1511 LOG_AND_RETURN_ERROR(
1512 RTCErrorType::UNSUPPORTED_PARAMETER,
1513 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001514 }
1515
1516 RtpParameters parameters;
1517 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001518
1519 // Encodings are dropped from the tail if too many are provided.
1520 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1521 parameters.encodings.erase(
1522 parameters.encodings.begin() + kMaxSimulcastStreams,
1523 parameters.encodings.end());
1524 }
1525
1526 // Single RID should be removed.
1527 if (parameters.encodings.size() == 1 &&
1528 !parameters.encodings[0].rid.empty()) {
1529 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1530 parameters.encodings[0].rid.clear();
1531 }
1532
1533 // If RIDs were not provided, they are generated for simulcast scenario.
1534 if (parameters.encodings.size() > 1 && num_rids == 0) {
1535 rtc::UniqueStringGenerator rid_generator;
1536 for (RtpEncodingParameters& encoding : parameters.encodings) {
1537 encoding.rid = rid_generator();
1538 }
1539 }
1540
Florent Castelli892acf02018-10-01 22:47:20 +02001541 if (UnimplementedRtpParameterHasValue(parameters)) {
1542 LOG_AND_RETURN_ERROR(
1543 RTCErrorType::UNSUPPORTED_PARAMETER,
1544 "Attempted to set an unimplemented parameter of RtpParameters.");
1545 }
Steve Anton9158ef62017-11-27 13:01:52 -08001546
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001547 auto result = cricket::CheckRtpParametersValues(parameters);
1548 if (!result.ok()) {
1549 LOG_AND_RETURN_ERROR(result.type(), result.message());
1550 }
1551
Steve Anton3d954a62018-04-02 11:27:23 -07001552 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1553 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001554 // Set the sender ID equal to the track ID if the track is specified unless
1555 // that sender ID is already in use.
1556 std::string sender_id =
1557 (track && !FindSenderById(track->id()) ? track->id()
1558 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001559 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001560 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001561 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1562 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1563 transceiver->internal()->set_direction(init.direction);
1564
Steve Anton22da89f2018-01-25 13:58:07 -08001565 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001566 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001567 }
Steve Antonf9381f02017-12-14 10:23:57 -08001568
1569 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1570}
1571
Steve Anton02ee47c2018-01-10 16:26:06 -08001572rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1573PeerConnection::CreateSender(
1574 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001575 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001576 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001577 const std::vector<std::string>& stream_ids,
1578 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001579 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001580 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1581 RTC_DCHECK(!track ||
1582 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1583 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1584 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001585 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001586 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001587 } else {
1588 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1589 RTC_DCHECK(!track ||
1590 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1591 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001592 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001593 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001594 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001595 bool set_track_succeeded = sender->SetTrack(track);
1596 RTC_DCHECK(set_track_succeeded);
1597 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001598 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001599 return sender;
1600}
1601
1602rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1603PeerConnection::CreateReceiver(cricket::MediaType media_type,
1604 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001605 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1606 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001607 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001608 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001609 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1610 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001611 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001612 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001613 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001614 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001615 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1616 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001617 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001618 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001619 return receiver;
1620}
1621
1622rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1623PeerConnection::CreateAndAddTransceiver(
1624 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1625 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1626 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001627 // Ensure that the new sender does not have an ID that is already in use by
1628 // another sender.
1629 // Allow receiver IDs to conflict since those come from remote SDP (which
1630 // could be invalid, but should not cause a crash).
1631 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001632 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1633 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001634 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001635 transceiver->internal()->SignalNegotiationNeeded.connect(
1636 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001637 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001638}
1639
Steve Anton52d86772018-02-20 15:48:12 -08001640void PeerConnection::OnNegotiationNeeded() {
1641 RTC_DCHECK_RUN_ON(signaling_thread());
1642 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001643 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001644}
1645
deadbeeffac06552015-11-25 11:26:01 -08001646rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001647 const std::string& kind,
1648 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001649 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001650 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1651 "Plan SdpSemantics. Please use AddTransceiver "
1652 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001653 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001654 if (IsClosed()) {
1655 return nullptr;
1656 }
Steve Anton4171afb2017-11-20 10:20:22 -08001657
Seth Hampson5b4f0752018-04-02 16:31:36 -07001658 // Internally we need to have one stream with Plan B semantics, so we
1659 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001660 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001661 if (stream_id.empty()) {
1662 stream_ids.push_back(rtc::CreateRandomUuid());
1663 RTC_LOG(LS_INFO)
1664 << "No stream_id specified for sender. Generated stream ID: "
1665 << stream_ids[0];
1666 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001667 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001668 }
1669
Steve Anton4171afb2017-11-20 10:20:22 -08001670 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001671 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001672 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001673 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001674 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001675 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001676 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001677 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001678 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001679 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001680 auto video_sender =
1681 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001682 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001683 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001684 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001685 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001686 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001687 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001688 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001689 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001690 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001691
deadbeefe1f9d832016-01-14 15:35:42 -08001692 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001693}
1694
deadbeef70ab1a12015-09-28 16:53:55 -07001695std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1696 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001697 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001698 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001699 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001700 }
1701 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001702}
1703
Steve Anton4171afb2017-11-20 10:20:22 -08001704std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1705PeerConnection::GetSendersInternal() const {
1706 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1707 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001708 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001709 auto senders = transceiver->internal()->senders();
1710 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1711 }
1712 return all_senders;
1713}
1714
deadbeef70ab1a12015-09-28 16:53:55 -07001715std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1716PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001717 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001718 for (const auto& receiver : GetReceiversInternal()) {
1719 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001720 }
1721 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001722}
1723
Steve Anton4171afb2017-11-20 10:20:22 -08001724std::vector<
1725 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1726PeerConnection::GetReceiversInternal() const {
1727 std::vector<
1728 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1729 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001730 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001731 auto receivers = transceiver->internal()->receivers();
1732 all_receivers.insert(all_receivers.end(), receivers.begin(),
1733 receivers.end());
1734 }
1735 return all_receivers;
1736}
1737
Steve Anton9158ef62017-11-27 13:01:52 -08001738std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1739PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001740 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001741 RTC_CHECK(IsUnifiedPlan())
1742 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001743 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001744 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001745 all_transceivers.push_back(transceiver);
1746 }
1747 return all_transceivers;
1748}
1749
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001750bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001751 MediaStreamTrackInterface* track,
1752 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001753 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001754 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001755 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001756 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 return false;
1758 }
1759
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001760 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001761 // The StatsCollector is used to tell if a track is valid because it may
1762 // remember tracks that the PeerConnection previously removed.
1763 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001764 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1765 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001766 return false;
1767 }
Steve Antonad182762018-09-05 20:22:40 +00001768 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1769 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001770 return true;
1771}
1772
hbos74e1a4f2016-09-15 23:33:01 -07001773void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001774 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001775 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001776 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001777 stats_collector_->GetStatsReport(callback);
1778}
1779
Henrik Boström1df1bf82018-03-20 13:24:20 +01001780void PeerConnection::GetStats(
1781 rtc::scoped_refptr<RtpSenderInterface> selector,
1782 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1783 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1784 RTC_DCHECK(callback);
1785 RTC_DCHECK(stats_collector_);
1786 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1787 if (selector) {
1788 for (const auto& proxy_transceiver : transceivers_) {
1789 for (const auto& proxy_sender :
1790 proxy_transceiver->internal()->senders()) {
1791 if (proxy_sender == selector) {
1792 internal_sender = proxy_sender->internal();
1793 break;
1794 }
1795 }
1796 if (internal_sender)
1797 break;
1798 }
1799 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001800 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001801 // belong to the PeerConnection (in Plan B, senders can be removed from the
1802 // PeerConnection). This means that "all the stats objects representing the
1803 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1804 // produces an empty stats report.
1805 stats_collector_->GetStatsReport(internal_sender, callback);
1806}
1807
1808void PeerConnection::GetStats(
1809 rtc::scoped_refptr<RtpReceiverInterface> selector,
1810 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1811 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1812 RTC_DCHECK(callback);
1813 RTC_DCHECK(stats_collector_);
1814 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1815 if (selector) {
1816 for (const auto& proxy_transceiver : transceivers_) {
1817 for (const auto& proxy_receiver :
1818 proxy_transceiver->internal()->receivers()) {
1819 if (proxy_receiver == selector) {
1820 internal_receiver = proxy_receiver->internal();
1821 break;
1822 }
1823 }
1824 if (internal_receiver)
1825 break;
1826 }
1827 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001828 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001829 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1830 // the PeerConnection). This means that "all the stats objects representing
1831 // the selector" is an empty set. Invoking GetStatsReport() with a null
1832 // selector produces an empty stats report.
1833 stats_collector_->GetStatsReport(internal_receiver, callback);
1834}
1835
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001836PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001837 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838 return signaling_state_;
1839}
1840
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841PeerConnectionInterface::IceConnectionState
1842PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001843 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844 return ice_connection_state_;
1845}
1846
Alex Loiko9289eda2018-11-23 16:18:59 +00001847PeerConnectionInterface::IceConnectionState
1848PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001849 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001850 return standardized_ice_connection_state_;
1851}
1852
Jonas Olsson635474e2018-10-18 15:58:17 +02001853PeerConnectionInterface::PeerConnectionState
1854PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001855 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001856 return connection_state_;
1857}
1858
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859PeerConnectionInterface::IceGatheringState
1860PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001861 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 return ice_gathering_state_;
1863}
1864
Yves Gerey665174f2018-06-19 15:03:05 +02001865rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866 const std::string& label,
1867 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001868 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001869 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001870
deadbeefab9b2d12015-10-14 11:33:11 -07001871 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001872
kwibergd1fe2812016-04-27 06:47:29 -07001873 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001874 if (config) {
1875 internal_config.reset(new InternalDataChannelInit(*config));
1876 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001877 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001878 InternalCreateDataChannel(label, internal_config.get()));
1879 if (!channel.get()) {
1880 return nullptr;
1881 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001882
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001883 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1884 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001885 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001886 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001887 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001888 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 return DataChannelProxy::Create(signaling_thread(), channel.get());
1890}
1891
1892void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001893 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001894 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001895 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001896
nisse7ce109a2017-01-31 00:57:56 -08001897 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001898 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001899 return;
1900 }
deadbeefab9b2d12015-10-14 11:33:11 -07001901
Steve Anton8d3444d2017-10-20 15:30:51 -07001902 if (IsClosed()) {
1903 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001904 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001905 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001906 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001907 return;
1908 }
1909
zhihuang1c378ed2017-08-17 14:10:50 -07001910 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001911 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001912 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001913 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001914 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001915 return;
1916 }
1917
Steve Anton22da89f2018-01-25 13:58:07 -08001918 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1919 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1920 if (IsUnifiedPlan()) {
1921 RTCError error = HandleLegacyOfferOptions(options);
1922 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001923 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001924 return;
1925 }
1926 }
1927
zhihuang1c378ed2017-08-17 14:10:50 -07001928 cricket::MediaSessionOptions session_options;
1929 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001930 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931}
1932
Steve Anton22da89f2018-01-25 13:58:07 -08001933RTCError PeerConnection::HandleLegacyOfferOptions(
1934 const RTCOfferAnswerOptions& options) {
1935 RTC_DCHECK(IsUnifiedPlan());
1936
1937 if (options.offer_to_receive_audio == 0) {
1938 RemoveRecvDirectionFromReceivingTransceiversOfType(
1939 cricket::MEDIA_TYPE_AUDIO);
1940 } else if (options.offer_to_receive_audio == 1) {
1941 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1942 } else if (options.offer_to_receive_audio > 1) {
1943 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1944 "offer_to_receive_audio > 1 is not supported.");
1945 }
1946
1947 if (options.offer_to_receive_video == 0) {
1948 RemoveRecvDirectionFromReceivingTransceiversOfType(
1949 cricket::MEDIA_TYPE_VIDEO);
1950 } else if (options.offer_to_receive_video == 1) {
1951 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1952 } else if (options.offer_to_receive_video > 1) {
1953 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1954 "offer_to_receive_video > 1 is not supported.");
1955 }
1956
1957 return RTCError::OK();
1958}
1959
1960void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1961 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001962 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001963 RtpTransceiverDirection new_direction =
1964 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1965 if (new_direction != transceiver->direction()) {
1966 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1967 << " transceiver (MID="
1968 << transceiver->mid().value_or("<not set>") << ") from "
1969 << RtpTransceiverDirectionToString(
1970 transceiver->direction())
1971 << " to "
1972 << RtpTransceiverDirectionToString(new_direction)
1973 << " since CreateOffer specified offer_to_receive=0";
1974 transceiver->internal()->set_direction(new_direction);
1975 }
Steve Anton22da89f2018-01-25 13:58:07 -08001976 }
1977}
1978
1979void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1980 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001981 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08001982 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001983 RTC_LOG(LS_INFO)
1984 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1985 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001986 RtpTransceiverInit init;
1987 init.direction = RtpTransceiverDirection::kRecvOnly;
1988 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1989 }
1990}
1991
1992std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1993PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1994 std::vector<
1995 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1996 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001997 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001998 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001999 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2000 receiving_transceivers.push_back(transceiver);
2001 }
2002 }
2003 return receiving_transceivers;
2004}
2005
htaa2a49d92016-03-04 02:51:39 -08002006void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2007 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002008 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002009 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002010 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002011 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002012 return;
2013 }
2014
Steve Antondffead82018-02-06 10:31:29 -08002015 if (!(signaling_state_ == kHaveRemoteOffer ||
2016 signaling_state_ == kHaveLocalPrAnswer)) {
2017 std::string error =
2018 "PeerConnection cannot create an answer in a state other than "
2019 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002020 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002021 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002022 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002023 return;
2024 }
2025
Steve Antondffead82018-02-06 10:31:29 -08002026 // The remote description should be set if we're in the right state.
2027 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002028
Steve Anton22da89f2018-01-25 13:58:07 -08002029 if (IsUnifiedPlan()) {
2030 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2031 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2032 "supported with Unified Plan semantics. Use the "
2033 "RtpTransceiver API instead.";
2034 }
2035 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2036 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2037 "supported with Unified Plan semantics. Use the "
2038 "RtpTransceiver API instead.";
2039 }
2040 }
2041
htaa2a49d92016-03-04 02:51:39 -08002042 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002043 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002044
Steve Antond25da372017-11-06 14:50:29 -08002045 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002046}
2047
2048void PeerConnection::SetLocalDescription(
2049 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002050 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002051 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002052 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002053
Steve Anton80dd7b52018-02-16 17:08:42 -08002054 // The SetLocalDescription contract is that we take ownership of the session
2055 // description regardless of the outcome, so wrap it in a unique_ptr right
2056 // away. Ideally, SetLocalDescription's signature will be changed to take the
2057 // description as a unique_ptr argument to formalize this agreement.
2058 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2059
nisse7ce109a2017-01-31 00:57:56 -08002060 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002061 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002062 return;
2063 }
Steve Anton8a006912017-12-04 15:25:56 -08002064
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002065 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002066 PostSetSessionDescriptionFailure(
2067 observer,
2068 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002069 return;
2070 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002071
Steve Anton80dd7b52018-02-16 17:08:42 -08002072 // If a session error has occurred the PeerConnection is in a possibly
2073 // inconsistent state so fail right away.
2074 if (session_error() != SessionError::kNone) {
2075 std::string error_message = GetSessionErrorMsg();
2076 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002077 PostSetSessionDescriptionFailure(
2078 observer,
2079 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002080 return;
2081 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002082
Steve Anton80dd7b52018-02-16 17:08:42 -08002083 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2084 if (!error.ok()) {
2085 std::string error_message = GetSetDescriptionErrorMessage(
2086 cricket::CS_LOCAL, desc->GetType(), error);
2087 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002088 PostSetSessionDescriptionFailure(
2089 observer,
2090 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002091 return;
2092 }
2093
2094 // Grab the description type before moving ownership to ApplyLocalDescription,
2095 // which may destroy it before returning.
2096 const SdpType type = desc->GetType();
2097
2098 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002099 // |desc| may be destroyed at this point.
2100
2101 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002102 // If ApplyLocalDescription fails, the PeerConnection could be in an
2103 // inconsistent state, so act conservatively here and set the session error
2104 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2105 SetSessionError(SessionError::kContent, error.message());
2106 std::string error_message =
2107 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2108 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002109 PostSetSessionDescriptionFailure(
2110 observer,
2111 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002112 return;
2113 }
Steve Anton8a006912017-12-04 15:25:56 -08002114 RTC_DCHECK(local_description());
2115
2116 PostSetSessionDescriptionSuccess(observer);
2117
Steve Antonad182762018-09-05 20:22:40 +00002118 // MaybeStartGathering needs to be called after posting
2119 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2120 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002121 transport_controller_->MaybeStartGathering();
2122
Steve Antona3a92c22017-12-07 10:27:41 -08002123 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002124 // TODO(deadbeef): We already had to hop to the network thread for
2125 // MaybeStartGathering...
2126 network_thread()->Invoke<void>(
2127 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2128 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002129 // Make UMA notes about what was agreed to.
2130 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002131 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002132 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002133}
2134
2135RTCError PeerConnection::ApplyLocalDescription(
2136 std::unique_ptr<SessionDescriptionInterface> desc) {
2137 RTC_DCHECK_RUN_ON(signaling_thread());
2138 RTC_DCHECK(desc);
2139
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140 // Update stats here so that we have the most recent stats for tracks and
2141 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002142 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002143
Steve Antondcc3c022017-12-22 16:02:54 -08002144 // Take a reference to the old local description since it's used below to
2145 // compare against the new local description. When setting the new local
2146 // description, grab ownership of the replaced session description in case it
2147 // is the same as |old_local_description|, to keep it alive for the duration
2148 // of the method.
2149 const SessionDescriptionInterface* old_local_description =
2150 local_description();
2151 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002152 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002153 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002154 replaced_local_description = pending_local_description_
2155 ? std::move(pending_local_description_)
2156 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002157 current_local_description_ = std::move(desc);
2158 pending_local_description_ = nullptr;
2159 current_remote_description_ = std::move(pending_remote_description_);
2160 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002161 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002162 pending_local_description_ = std::move(desc);
2163 }
2164 // The session description to apply now must be accessed by
2165 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002166 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002167
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002168 if (!is_caller_) {
2169 if (remote_description()) {
2170 // Remote description was applied first, so this PC is the callee.
2171 is_caller_ = false;
2172 } else {
2173 // Local description is applied first, so this PC is the caller.
2174 is_caller_ = true;
2175 }
2176 }
2177
Zhi Huange830e682018-03-30 10:48:35 -07002178 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2179 if (!error.ok()) {
2180 return error;
2181 }
2182
Steve Antondcc3c022017-12-22 16:02:54 -08002183 if (IsUnifiedPlan()) {
2184 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002185 cricket::CS_LOCAL, *local_description(), old_local_description,
2186 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002187 if (!error.ok()) {
2188 return error;
2189 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002190 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2191 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002192 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002193 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2194 // Note that code paths that don't set MID won't be able to use
2195 // information about DTLS transports.
2196 if (transceiver->mid()) {
2197 auto dtls_transport =
2198 LookupDtlsTransportByMidInternal(*transceiver->mid());
2199 transceiver->internal()->sender_internal()->set_transport(
2200 dtls_transport);
2201 transceiver->internal()->receiver_internal()->set_transport(
2202 dtls_transport);
2203 }
2204
Steve Antondcc3c022017-12-22 16:02:54 -08002205 const ContentInfo* content =
2206 FindMediaSectionForTransceiver(transceiver, local_description());
2207 if (!content) {
2208 continue;
2209 }
2210 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002211 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2212 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002213 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002214 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2215 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2216 // "recvonly", process the removal of a remote track for the media
2217 // description, given transceiver, removeList, and muteTracks.
2218 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2219 (transceiver->internal()->fired_direction() &&
2220 RtpTransceiverDirectionHasRecv(
2221 *transceiver->internal()->fired_direction()))) {
2222 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2223 &removed_streams);
2224 }
2225 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2226 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002227 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002228 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002229 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002230 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002231 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002232 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002233 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002234 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002235 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002236 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002237 }
2238 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002239 // Media channels will be created only when offer is set. These may use new
2240 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002241 if (type == SdpType::kOffer) {
2242 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2243 // description is applied. Restore back to old description.
2244 RTCError error = CreateChannels(*local_description()->description());
2245 if (!error.ok()) {
2246 return error;
2247 }
2248 }
Steve Antondcc3c022017-12-22 16:02:54 -08002249 // Remove unused channels if MediaContentDescription is rejected.
2250 RemoveUnusedChannels(local_description()->description());
2251 }
Steve Anton8a006912017-12-04 15:25:56 -08002252
Zhi Huange830e682018-03-30 10:48:35 -07002253 error = UpdateSessionState(type, cricket::CS_LOCAL,
2254 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002255 if (!error.ok()) {
2256 return error;
2257 }
Steve Antondcc3c022017-12-22 16:02:54 -08002258
Steve Anton8a006912017-12-04 15:25:56 -08002259 if (remote_description()) {
2260 // Now that we have a local description, we can push down remote candidates.
2261 UseCandidatesInSessionDescription(remote_description());
2262 }
2263
2264 pending_ice_restarts_.clear();
2265 if (session_error() != SessionError::kNone) {
2266 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2267 }
2268
deadbeefab9b2d12015-10-14 11:33:11 -07002269 // If setting the description decided our SSL role, allocate any necessary
2270 // SCTP sids.
2271 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002272 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002273 AllocateSctpSids(role);
2274 }
2275
Steve Antond3679212018-01-17 17:41:02 -08002276 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002277 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002278 const ContentInfo* content =
2279 FindMediaSectionForTransceiver(transceiver, local_description());
2280 if (!content) {
2281 continue;
2282 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002283 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2284 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002285 // 0 is a special value meaning "this sender has no associated send
2286 // stream". Need to call this so the sender won't attempt to configure
2287 // a no longer existing stream and run into DCHECKs in the lower
2288 // layers.
2289 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002290 } else {
2291 // Get the StreamParams from the channel which could generate SSRCs.
2292 const std::vector<StreamParams>& streams = channel->local_streams();
2293 transceiver->internal()->sender_internal()->set_stream_ids(
2294 streams[0].stream_ids());
2295 transceiver->internal()->sender_internal()->SetSsrc(
2296 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002297 }
2298 }
2299 } else {
2300 // Plan B semantics.
2301
Steve Antondcc3c022017-12-22 16:02:54 -08002302 // Update state and SSRC of local MediaStreams and DataChannels based on the
2303 // local session description.
2304 const cricket::ContentInfo* audio_content =
2305 GetFirstAudioContent(local_description()->description());
2306 if (audio_content) {
2307 if (audio_content->rejected) {
2308 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2309 } else {
2310 const cricket::AudioContentDescription* audio_desc =
2311 audio_content->media_description()->as_audio();
2312 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2313 }
deadbeeffaac4972015-11-12 15:33:07 -08002314 }
deadbeefab9b2d12015-10-14 11:33:11 -07002315
Steve Antondcc3c022017-12-22 16:02:54 -08002316 const cricket::ContentInfo* video_content =
2317 GetFirstVideoContent(local_description()->description());
2318 if (video_content) {
2319 if (video_content->rejected) {
2320 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2321 } else {
2322 const cricket::VideoContentDescription* video_desc =
2323 video_content->media_description()->as_video();
2324 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2325 }
deadbeeffaac4972015-11-12 15:33:07 -08002326 }
deadbeefab9b2d12015-10-14 11:33:11 -07002327 }
2328
2329 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002330 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002331 if (data_content) {
2332 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002333 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002334 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002335 cricket::kMediaProtocolRtpPrefix)) {
2336 UpdateLocalRtpDataChannels(data_desc->streams());
2337 }
2338 }
2339
Steve Anton8a006912017-12-04 15:25:56 -08002340 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341}
2342
Steve Anton06817cd2018-12-18 15:55:30 -08002343// The SDP parser used to populate these values by default for the 'content
2344// name' if an a=mid line was absent.
2345static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2346 switch (media_type) {
2347 case cricket::MEDIA_TYPE_AUDIO:
2348 return cricket::CN_AUDIO;
2349 case cricket::MEDIA_TYPE_VIDEO:
2350 return cricket::CN_VIDEO;
2351 case cricket::MEDIA_TYPE_DATA:
2352 return cricket::CN_DATA;
2353 }
2354 RTC_NOTREACHED();
2355 return "";
2356}
2357
2358void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002359 cricket::SessionDescription* new_remote_description) {
2360 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002361 const cricket::ContentInfos& local_contents =
2362 (local_description() ? local_description()->description()->contents()
2363 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002364 const cricket::ContentInfos& remote_contents =
2365 (remote_description() ? remote_description()->description()->contents()
2366 : cricket::ContentInfos());
2367 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2368 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002369 if (!content.name.empty()) {
2370 continue;
2371 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002372 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002373 absl::string_view source_explanation;
2374 if (IsUnifiedPlan()) {
2375 if (i < local_contents.size()) {
2376 new_mid = local_contents[i].name;
2377 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002378 } else if (i < remote_contents.size()) {
2379 new_mid = remote_contents[i].name;
2380 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002381 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002382 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002383 source_explanation = "generated just now";
2384 }
2385 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002386 new_mid = std::string(
2387 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002388 source_explanation = "to match pre-existing behavior";
2389 }
Steve Antond7180cc2019-02-07 10:44:53 -08002390 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002391 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002392 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002393 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2394 << " is missing an a=mid line. Filling in the value '"
2395 << new_mid << "' " << source_explanation << ".";
2396 }
2397}
2398
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002400 SetSessionDescriptionObserver* observer,
2401 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002402 SetRemoteDescription(
2403 std::unique_ptr<SessionDescriptionInterface>(desc),
2404 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2405 new SetRemoteDescriptionObserverAdapter(this, observer)));
2406}
2407
2408void PeerConnection::SetRemoteDescription(
2409 std::unique_ptr<SessionDescriptionInterface> desc,
2410 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002411 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002412 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002413
nisse7ce109a2017-01-31 00:57:56 -08002414 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002415 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416 return;
2417 }
Steve Anton8a006912017-12-04 15:25:56 -08002418
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002420 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002421 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002422 return;
2423 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002424
Steve Anton80dd7b52018-02-16 17:08:42 -08002425 // If a session error has occurred the PeerConnection is in a possibly
2426 // inconsistent state so fail right away.
2427 if (session_error() != SessionError::kNone) {
2428 std::string error_message = GetSessionErrorMsg();
2429 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2430 observer->OnSetRemoteDescriptionComplete(
2431 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2432 return;
2433 }
Steve Anton71439a62018-02-15 11:53:06 -08002434
Steve Antonba42e992018-04-09 14:10:01 -07002435 if (desc->GetType() == SdpType::kOffer) {
2436 // Report to UMA the format of the received offer.
2437 ReportSdpFormatReceived(*desc);
2438 }
2439
Steve Anton06817cd2018-12-18 15:55:30 -08002440 // Handle remote descriptions missing a=mid lines for interop with legacy end
2441 // points.
2442 FillInMissingRemoteMids(desc->description());
2443
Steve Anton80dd7b52018-02-16 17:08:42 -08002444 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002445 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002446 std::string error_message = GetSetDescriptionErrorMessage(
2447 cricket::CS_REMOTE, desc->GetType(), error);
2448 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002449 observer->OnSetRemoteDescriptionComplete(
2450 RTCError(error.type(), std::move(error_message)));
2451 return;
2452 }
Steve Anton71439a62018-02-15 11:53:06 -08002453
Steve Anton80dd7b52018-02-16 17:08:42 -08002454 // Grab the description type before moving ownership to
2455 // ApplyRemoteDescription, which may destroy it before returning.
2456 const SdpType type = desc->GetType();
2457
2458 error = ApplyRemoteDescription(std::move(desc));
2459 // |desc| may be destroyed at this point.
2460
2461 if (!error.ok()) {
2462 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2463 // inconsistent state, so act conservatively here and set the session error
2464 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2465 SetSessionError(SessionError::kContent, error.message());
2466 std::string error_message =
2467 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2468 RTC_LOG(LS_ERROR) << error_message;
2469 observer->OnSetRemoteDescriptionComplete(
2470 RTCError(error.type(), std::move(error_message)));
2471 return;
2472 }
2473 RTC_DCHECK(remote_description());
2474
2475 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002476 // TODO(deadbeef): We already had to hop to the network thread for
2477 // MaybeStartGathering...
2478 network_thread()->Invoke<void>(
2479 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2480 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002481 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002482 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002483 }
2484
2485 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002486 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002487}
2488
2489RTCError PeerConnection::ApplyRemoteDescription(
2490 std::unique_ptr<SessionDescriptionInterface> desc) {
2491 RTC_DCHECK_RUN_ON(signaling_thread());
2492 RTC_DCHECK(desc);
2493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494 // Update stats here so that we have the most recent stats for tracks and
2495 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002496 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002497
Steve Antondcc3c022017-12-22 16:02:54 -08002498 // Take a reference to the old remote description since it's used below to
2499 // compare against the new remote description. When setting the new remote
2500 // description, grab ownership of the replaced session description in case it
2501 // is the same as |old_remote_description|, to keep it alive for the duration
2502 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002503 const SessionDescriptionInterface* old_remote_description =
2504 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002505 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002506 SdpType type = desc->GetType();
2507 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002508 replaced_remote_description = pending_remote_description_
2509 ? std::move(pending_remote_description_)
2510 : std::move(current_remote_description_);
2511 current_remote_description_ = std::move(desc);
2512 pending_remote_description_ = nullptr;
2513 current_local_description_ = std::move(pending_local_description_);
2514 } else {
2515 replaced_remote_description = std::move(pending_remote_description_);
2516 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002517 }
Steve Anton8a006912017-12-04 15:25:56 -08002518 // The session description to apply now must be accessed by
2519 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002520 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002521
Zhi Huange830e682018-03-30 10:48:35 -07002522 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2523 if (!error.ok()) {
2524 return error;
2525 }
Steve Anton8a006912017-12-04 15:25:56 -08002526 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002527 if (IsUnifiedPlan()) {
2528 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002529 cricket::CS_REMOTE, *remote_description(), local_description(),
2530 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002531 if (!error.ok()) {
2532 return error;
2533 }
Steve Antondcc3c022017-12-22 16:02:54 -08002534 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002535 // Media channels will be created only when offer is set. These may use new
2536 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002537 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002538 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002539 // description is applied. Restore back to old description.
2540 RTCError error = CreateChannels(*remote_description()->description());
2541 if (!error.ok()) {
2542 return error;
2543 }
2544 }
Steve Antondcc3c022017-12-22 16:02:54 -08002545 // Remove unused channels if MediaContentDescription is rejected.
2546 RemoveUnusedChannels(remote_description()->description());
2547 }
Steve Anton8a006912017-12-04 15:25:56 -08002548
Zhi Huange830e682018-03-30 10:48:35 -07002549 // NOTE: Candidates allocation will be initiated only when
2550 // SetLocalDescription is called.
2551 error = UpdateSessionState(type, cricket::CS_REMOTE,
2552 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002553 if (!error.ok()) {
2554 return error;
2555 }
2556
2557 if (local_description() &&
2558 !UseCandidatesInSessionDescription(remote_description())) {
2559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2560 }
2561
2562 if (old_remote_description) {
2563 for (const cricket::ContentInfo& content :
2564 old_remote_description->description()->contents()) {
2565 // Check if this new SessionDescription contains new ICE ufrag and
2566 // password that indicates the remote peer requests an ICE restart.
2567 // TODO(deadbeef): When we start storing both the current and pending
2568 // remote description, this should reset pending_ice_restarts and compare
2569 // against the current description.
2570 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2571 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002572 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002573 pending_ice_restarts_.insert(content.name);
2574 }
2575 } else {
2576 // We retain all received candidates only if ICE is not restarted.
2577 // When ICE is restarted, all previous candidates belong to an old
2578 // generation and should not be kept.
2579 // TODO(deadbeef): This goes against the W3C spec which says the remote
2580 // description should only contain candidates from the last set remote
2581 // description plus any candidates added since then. We should remove
2582 // this once we're sure it won't break anything.
2583 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2584 old_remote_description, content.name, mutable_remote_description());
2585 }
2586 }
2587 }
2588
2589 if (session_error() != SessionError::kNone) {
2590 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2591 }
2592
2593 // Set the the ICE connection state to connecting since the connection may
2594 // become writable with peer reflexive candidates before any remote candidate
2595 // is signaled.
2596 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2597 // is to have a new signal the indicates a change in checking state from the
2598 // transport and expose a new checking() member from transport that can be
2599 // read to determine the current checking state. The existing SignalConnecting
2600 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002601 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002602 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002603 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2604 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2605 }
2606
deadbeefab9b2d12015-10-14 11:33:11 -07002607 // If setting the description decided our SSL role, allocate any necessary
2608 // SCTP sids.
2609 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002610 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002611 AllocateSctpSids(role);
2612 }
2613
Steve Antondcc3c022017-12-22 16:02:54 -08002614 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002615 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002616 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002617 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002618 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002619 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002620 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002621 const ContentInfo* content =
2622 FindMediaSectionForTransceiver(transceiver, remote_description());
2623 if (!content) {
2624 continue;
2625 }
2626 const MediaContentDescription* media_desc = content->media_description();
2627 RtpTransceiverDirection local_direction =
2628 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002629 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2630 // RTCSessionDescription: Set the associated remote streams given
2631 // transceiver.[[Receiver]], msids, addList, and removeList".
2632 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2633 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2634 std::vector<std::string> stream_ids;
2635 if (!media_desc->streams().empty()) {
2636 // The remote description has signaled the stream IDs.
2637 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002638 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002639 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2640 << " (" << GetStreamIdsString(stream_ids) << ").";
2641 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2642 stream_ids, &added_streams,
2643 &removed_streams);
2644 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2645 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2646 // and transceiver's current direction is neither sendrecv nor recvonly,
2647 // process the addition of a remote track for the media description.
2648 if (!transceiver->fired_direction() ||
2649 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2650 RTC_LOG(LS_INFO)
2651 << "Processing the addition of a remote track for MID="
2652 << content->name << ".";
2653 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002654 }
Steve Antondcc3c022017-12-22 16:02:54 -08002655 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002656 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002657 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2658 // removal of a remote track for the media description, given transceiver,
2659 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002660 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002661 (transceiver->fired_direction() &&
2662 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2663 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2664 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002665 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002666 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002667 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002668 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002669 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002670 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002671 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002672 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002673 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002674 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2675 if (transceiver->mid()) {
2676 auto dtls_transport =
2677 LookupDtlsTransportByMidInternal(*transceiver->mid());
2678 transceiver->internal()->sender_internal()->set_transport(
2679 dtls_transport);
2680 transceiver->internal()->receiver_internal()->set_transport(
2681 dtls_transport);
2682 }
Steve Antondcc3c022017-12-22 16:02:54 -08002683 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002684 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002685 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002686 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002687 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2688 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002689 transceiver->Stop();
2690 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002691 if (!content->rejected &&
2692 RtpTransceiverDirectionHasRecv(local_direction)) {
2693 // Set ssrc to 0 in the case of an unsignalled ssrc.
2694 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002695 if (!media_desc->streams().empty() &&
2696 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002697 ssrc = media_desc->streams()[0].first_ssrc();
2698 }
2699 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002700 }
Steve Antondcc3c022017-12-22 16:02:54 -08002701 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002702 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002703 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002704 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002705 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002706 observer->OnTrack(transceiver);
2707 observer->OnAddTrack(transceiver->receiver(),
2708 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002709 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002710 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002711 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002712 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002713 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002714 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002715 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002716 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002717 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002718 }
Steve Antondcc3c022017-12-22 16:02:54 -08002719 }
2720
Henrik Boströmfdb92012017-11-09 19:55:44 +01002721 const cricket::ContentInfo* audio_content =
2722 GetFirstAudioContent(remote_description()->description());
2723 const cricket::ContentInfo* video_content =
2724 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002725 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002726 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002727 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002728 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002729 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002730 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002731
2732 // Check if the descriptions include streams, just in case the peer supports
2733 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002734 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002735 (audio_desc && !audio_desc->streams().empty()) ||
2736 (video_desc && !video_desc->streams().empty())) {
2737 remote_peer_supports_msid_ = true;
2738 }
deadbeefab9b2d12015-10-14 11:33:11 -07002739
2740 // We wait to signal new streams until we finish processing the description,
2741 // since only at that point will new streams have all their tracks.
2742 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2743
Steve Antondcc3c022017-12-22 16:02:54 -08002744 if (!IsUnifiedPlan()) {
2745 // TODO(steveanton): When removing RTP senders/receivers in response to a
2746 // rejected media section, there is some cleanup logic that expects the
2747 // voice/ video channel to still be set. But in this method the voice/video
2748 // channel would have been destroyed by the SetRemoteDescription caller
2749 // above so the cleanup that relies on them fails to run. The RemoveSenders
2750 // calls should be moved to right before the DestroyChannel calls to fix
2751 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002752
Steve Antondcc3c022017-12-22 16:02:54 -08002753 // Find all audio rtp streams and create corresponding remote AudioTracks
2754 // and MediaStreams.
2755 if (audio_content) {
2756 if (audio_content->rejected) {
2757 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2758 } else {
2759 bool default_audio_track_needed =
2760 !remote_peer_supports_msid_ &&
2761 RtpTransceiverDirectionHasSend(audio_desc->direction());
2762 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2763 default_audio_track_needed, audio_desc->type(),
2764 new_streams);
2765 }
deadbeeffaac4972015-11-12 15:33:07 -08002766 }
deadbeefab9b2d12015-10-14 11:33:11 -07002767
Steve Antondcc3c022017-12-22 16:02:54 -08002768 // Find all video rtp streams and create corresponding remote VideoTracks
2769 // and MediaStreams.
2770 if (video_content) {
2771 if (video_content->rejected) {
2772 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2773 } else {
2774 bool default_video_track_needed =
2775 !remote_peer_supports_msid_ &&
2776 RtpTransceiverDirectionHasSend(video_desc->direction());
2777 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2778 default_video_track_needed, video_desc->type(),
2779 new_streams);
2780 }
deadbeeffaac4972015-11-12 15:33:07 -08002781 }
deadbeefab9b2d12015-10-14 11:33:11 -07002782
Steve Antondcc3c022017-12-22 16:02:54 -08002783 // Update the DataChannels with the information from the remote peer.
2784 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002785 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002786 cricket::kMediaProtocolRtpPrefix)) {
2787 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2788 }
deadbeefab9b2d12015-10-14 11:33:11 -07002789 }
deadbeefab9b2d12015-10-14 11:33:11 -07002790
Steve Antondcc3c022017-12-22 16:02:54 -08002791 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002792 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002793 for (size_t i = 0; i < new_streams->count(); ++i) {
2794 MediaStreamInterface* new_stream = new_streams->at(i);
2795 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002796 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002797 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2798 }
deadbeefab9b2d12015-10-14 11:33:11 -07002799
Steve Antondcc3c022017-12-22 16:02:54 -08002800 UpdateEndedRemoteMediaStreams();
2801 }
deadbeefab9b2d12015-10-14 11:33:11 -07002802
Steve Anton8a006912017-12-04 15:25:56 -08002803 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002804}
2805
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002806void PeerConnection::SetAssociatedRemoteStreams(
2807 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2808 const std::vector<std::string>& stream_ids,
2809 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2810 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2811 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2812 for (const std::string& stream_id : stream_ids) {
2813 rtc::scoped_refptr<MediaStreamInterface> stream =
2814 remote_streams_->find(stream_id);
2815 if (!stream) {
2816 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2817 MediaStream::Create(stream_id));
2818 remote_streams_->AddStream(stream);
2819 added_streams->push_back(stream);
2820 }
2821 media_streams.push_back(stream);
2822 }
2823 // Special case: "a=msid" missing, use random stream ID.
2824 if (media_streams.empty() &&
2825 !(remote_description()->description()->msid_signaling() &
2826 cricket::kMsidSignalingMediaSection)) {
2827 if (!missing_msid_default_stream_) {
2828 missing_msid_default_stream_ = MediaStreamProxy::Create(
2829 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2830 added_streams->push_back(missing_msid_default_stream_);
2831 }
2832 media_streams.push_back(missing_msid_default_stream_);
2833 }
2834 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2835 receiver->streams();
2836 // SetStreams() will add/remove the receiver's track to/from the streams. This
2837 // differs from the spec - the spec uses an "addList" and "removeList" to
2838 // update the stream-track relationships in a later step. We do this earlier,
2839 // changing the order of things, but the end-result is the same.
2840 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2841 // instead. https://crbug.com/webrtc/9480
2842 receiver->SetStreams(media_streams);
2843 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2844}
2845
Steve Anton0f5400a2018-07-17 14:25:36 -07002846void PeerConnection::ProcessRemovalOfRemoteTrack(
2847 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2848 transceiver,
2849 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2850 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2851 RTC_DCHECK(transceiver->mid());
2852 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2853 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002854 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002855 transceiver->internal()->receiver_internal()->streams();
2856 // This will remove the remote track from the streams.
2857 transceiver->internal()->receiver_internal()->set_stream_ids({});
2858 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002859 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2860}
2861
2862void PeerConnection::RemoveRemoteStreamsIfEmpty(
2863 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2864 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2865 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2866 // streams, see if the stream was removed by checking if this was the last
2867 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002868 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002869 if (remote_stream->GetAudioTracks().empty() &&
2870 remote_stream->GetVideoTracks().empty()) {
2871 remote_streams_->RemoveStream(remote_stream);
2872 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002873 }
2874 }
2875}
2876
Steve Antondcc3c022017-12-22 16:02:54 -08002877RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2878 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002879 const SessionDescriptionInterface& new_session,
2880 const SessionDescriptionInterface* old_local_description,
2881 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002882 RTC_DCHECK(IsUnifiedPlan());
2883
Steve Anton7464fca2018-01-19 11:10:37 -08002884 const cricket::ContentGroup* bundle_group = nullptr;
2885 if (new_session.GetType() == SdpType::kOffer) {
2886 auto bundle_group_or_error =
2887 GetEarlyBundleGroup(*new_session.description());
2888 if (!bundle_group_or_error.ok()) {
2889 return bundle_group_or_error.MoveError();
2890 }
2891 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002892 }
Steve Antondcc3c022017-12-22 16:02:54 -08002893
Steve Antondcc3c022017-12-22 16:02:54 -08002894 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002895 for (size_t i = 0; i < new_contents.size(); ++i) {
2896 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002897 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002898 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002899 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2900 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002901 const cricket::ContentInfo* old_local_content = nullptr;
2902 if (old_local_description &&
2903 i < old_local_description->description()->contents().size()) {
2904 old_local_content =
2905 &old_local_description->description()->contents()[i];
2906 }
2907 const cricket::ContentInfo* old_remote_content = nullptr;
2908 if (old_remote_description &&
2909 i < old_remote_description->description()->contents().size()) {
2910 old_remote_content =
2911 &old_remote_description->description()->contents()[i];
2912 }
Steve Antondcc3c022017-12-22 16:02:54 -08002913 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002914 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2915 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002916 if (!transceiver_or_error.ok()) {
2917 return transceiver_or_error.MoveError();
2918 }
2919 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002920 RTCError error =
2921 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2922 if (!error.ok()) {
2923 return error;
2924 }
2925 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002926 if (GetDataMid() && new_content.name != *GetDataMid()) {
2927 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002928 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2929 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002930 continue;
2931 }
2932 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2933 if (!error.ok()) {
2934 return error;
2935 }
Steve Antondcc3c022017-12-22 16:02:54 -08002936 } else {
2937 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2938 "Unknown section type.");
2939 }
2940 }
2941
2942 return RTCError::OK();
2943}
2944
2945RTCError PeerConnection::UpdateTransceiverChannel(
2946 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2947 transceiver,
2948 const cricket::ContentInfo& content,
2949 const cricket::ContentGroup* bundle_group) {
2950 RTC_DCHECK(IsUnifiedPlan());
2951 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002952 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002953 if (content.rejected) {
2954 if (channel) {
2955 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002956 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002957 }
2958 } else {
2959 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002960 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002961 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002962 } else {
Steve Anton69470252018-02-09 11:43:08 -08002963 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002964 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002965 }
2966 if (!channel) {
2967 LOG_AND_RETURN_ERROR(
2968 RTCErrorType::INTERNAL_ERROR,
2969 "Failed to create channel for mid=" + content.name);
2970 }
2971 transceiver->internal()->SetChannel(channel);
2972 }
2973 }
2974 return RTCError::OK();
2975}
2976
Steve Antonfa2260d2017-12-28 16:38:23 -08002977RTCError PeerConnection::UpdateDataChannel(
2978 cricket::ContentSource source,
2979 const cricket::ContentInfo& content,
2980 const cricket::ContentGroup* bundle_group) {
2981 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002982 // If data channels are disabled, ignore this media section. CreateAnswer
2983 // will take care of rejecting it.
2984 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002985 }
2986 if (content.rejected) {
2987 DestroyDataChannel();
2988 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002989 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002990 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002991 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2992 "Failed to create data channel.");
2993 }
2994 }
2995 if (source == cricket::CS_REMOTE) {
2996 const MediaContentDescription* data_desc = content.media_description();
2997 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2998 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2999 }
3000 }
3001 }
3002 return RTCError::OK();
3003}
3004
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003005// This method will extract any send encodings that were sent by the remote
3006// connection. This is currently only relevant for Simulcast scenario (where
3007// the number of layers may be communicated by the server).
3008static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3009 const MediaContentDescription& desc) {
3010 if (!desc.HasSimulcast()) {
3011 return {};
3012 }
3013 std::vector<RtpEncodingParameters> result;
3014 const SimulcastDescription& simulcast = desc.simulcast_description();
3015
3016 // This is a remote description, the parameters we are after should appear
3017 // as receive streams.
3018 for (const auto& alternatives : simulcast.receive_layers()) {
3019 RTC_DCHECK(!alternatives.empty());
3020 // There is currently no way to specify or choose from alternatives.
3021 // We will always use the first alternative, which is the most preferred.
3022 const SimulcastLayer& layer = alternatives[0];
3023 RtpEncodingParameters parameters;
3024 parameters.rid = layer.rid;
3025 parameters.active = !layer.is_paused;
3026 result.push_back(parameters);
3027 }
3028
3029 return result;
3030}
3031
3032static RTCError UpdateSimulcastLayerStatusInSender(
3033 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003034 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003035 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003036 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003037 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003038
3039 // The simulcast envelope cannot be changed, only the status of the streams.
3040 // So we will iterate over the send encodings rather than the layers.
3041 for (RtpEncodingParameters& encoding : parameters.encodings) {
3042 auto iter = std::find_if(layers.begin(), layers.end(),
3043 [&encoding](const SimulcastLayer& layer) {
3044 return layer.rid == encoding.rid;
3045 });
3046 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003047 if (iter == layers.end()) {
3048 disabled_layers.push_back(encoding.rid);
3049 continue;
3050 }
3051
3052 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003053 }
3054
Amit Hilbuch619b2942019-02-26 15:55:19 -08003055 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003056 if (result.ok()) {
3057 result = sender->DisableEncodingLayers(disabled_layers);
3058 }
3059
3060 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003061}
3062
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003063static bool SimulcastIsRejected(
3064 const ContentInfo* local_content,
3065 const MediaContentDescription& answer_media_desc) {
3066 bool simulcast_offered = local_content &&
3067 local_content->media_description() &&
3068 local_content->media_description()->HasSimulcast();
3069 bool simulcast_answered = answer_media_desc.HasSimulcast();
3070 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3071 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3072 return simulcast_offered && (!simulcast_answered || !rids_supported);
3073}
3074
Amit Hilbuch2297d332019-02-19 12:49:22 -08003075static RTCError DisableSimulcastInSender(
3076 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003077 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003078 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003079 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003080 return RTCError::OK();
3081 }
3082
Amit Hilbuch2297d332019-02-19 12:49:22 -08003083 std::vector<std::string> disabled_layers;
3084 std::transform(
3085 parameters.encodings.begin() + 1, parameters.encodings.end(),
3086 std::back_inserter(disabled_layers),
3087 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3088 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003089}
3090
Steve Antondcc3c022017-12-22 16:02:54 -08003091RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3092PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003093 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003094 size_t mline_index,
3095 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003096 const ContentInfo* old_local_content,
3097 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003098 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003099 // If this is an offer then the m= section might be recycled. If the m=
3100 // section is being recycled (defined as: rejected in the current local or
3101 // remote description and not rejected in new description), dissociate the
3102 // currently associated RtpTransceiver by setting its mid property to null,
3103 // and discard the mapping between the transceiver and its m= section index.
3104 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3105 old_remote_content)) {
3106 // We want to dissociate the transceiver that has the rejected mid.
3107 const std::string& old_mid =
3108 (old_local_content && old_local_content->rejected)
3109 ? old_local_content->name
3110 : old_remote_content->name;
3111 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003112 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003113 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3114 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003115 old_transceiver->internal()->set_mid(absl::nullopt);
3116 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003117 }
3118 }
3119 const MediaContentDescription* media_desc = content.media_description();
3120 auto transceiver = GetAssociatedTransceiver(content.name);
3121 if (source == cricket::CS_LOCAL) {
3122 // Find the RtpTransceiver that corresponds to this m= section, using the
3123 // mapping between transceivers and m= section indices established when
3124 // creating the offer.
3125 if (!transceiver) {
3126 transceiver = GetTransceiverByMLineIndex(mline_index);
3127 }
3128 if (!transceiver) {
3129 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3130 "Unknown transceiver");
3131 }
3132 } else {
3133 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3134 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3135 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003136 // When simulcast is requested, a transceiver cannot be associated because
3137 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003138 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003139 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3140 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003141 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3142 }
3143 // If no RtpTransceiver was found in the previous step, create one with a
3144 // recvonly direction.
3145 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003146 RTC_LOG(LS_INFO) << "Adding "
3147 << cricket::MediaTypeToString(media_desc->type())
3148 << " transceiver for MID=" << content.name
3149 << " at i=" << mline_index
3150 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003151 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003152 std::vector<RtpEncodingParameters> send_encodings =
3153 GetSendEncodingsFromRemoteDescription(*media_desc);
3154 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3155 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003156 std::string receiver_id;
3157 if (!media_desc->streams().empty()) {
3158 receiver_id = media_desc->streams()[0].id;
3159 } else {
3160 receiver_id = rtc::CreateRandomUuid();
3161 }
3162 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003163 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003164 transceiver->internal()->set_direction(
3165 RtpTransceiverDirection::kRecvOnly);
3166 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003167
3168 // Check if the offer indicated simulcast but the answer rejected it.
3169 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003170 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003171 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003172 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003173 if (!error.ok()) {
3174 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3175 return std::move(error);
3176 }
3177 }
Steve Antondcc3c022017-12-22 16:02:54 -08003178 }
3179 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003180 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003181 LOG_AND_RETURN_ERROR(
3182 RTCErrorType::INVALID_PARAMETER,
3183 "Transceiver type does not match media description type.");
3184 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003185 if (media_desc->HasSimulcast()) {
3186 std::vector<SimulcastLayer> layers =
3187 source == cricket::CS_LOCAL
3188 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3189 : media_desc->simulcast_description()
3190 .receive_layers()
3191 .GetAllLayers();
3192 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003193 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003194 if (!error.ok()) {
3195 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3196 return std::move(error);
3197 }
3198 }
Steve Antondcc3c022017-12-22 16:02:54 -08003199 // Associate the found or created RtpTransceiver with the m= section by
3200 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3201 // section, and establish a mapping between the transceiver and the index of
3202 // the m= section.
3203 transceiver->internal()->set_mid(content.name);
3204 transceiver->internal()->set_mline_index(mline_index);
3205 return std::move(transceiver);
3206}
3207
3208rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3209PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3210 RTC_DCHECK(IsUnifiedPlan());
3211 for (auto transceiver : transceivers_) {
3212 if (transceiver->mid() == mid) {
3213 return transceiver;
3214 }
3215 }
3216 return nullptr;
3217}
3218
3219rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3220PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3221 RTC_DCHECK(IsUnifiedPlan());
3222 for (auto transceiver : transceivers_) {
3223 if (transceiver->internal()->mline_index() == mline_index) {
3224 return transceiver;
3225 }
3226 }
3227 return nullptr;
3228}
3229
3230rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3231PeerConnection::FindAvailableTransceiverToReceive(
3232 cricket::MediaType media_type) const {
3233 RTC_DCHECK(IsUnifiedPlan());
3234 // From JSEP section 5.10 (Applying a Remote Description):
3235 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3236 // the same type that were added to the PeerConnection by addTrack and are not
3237 // associated with any m= section and are not stopped, find the first such
3238 // RtpTransceiver.
3239 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003240 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003241 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3242 !transceiver->stopped()) {
3243 return transceiver;
3244 }
3245 }
3246 return nullptr;
3247}
3248
Steve Antoned10bd92017-12-05 10:52:59 -08003249const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3250 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3251 transceiver,
3252 const SessionDescriptionInterface* sdesc) const {
3253 RTC_DCHECK(transceiver);
3254 RTC_DCHECK(sdesc);
3255 if (IsUnifiedPlan()) {
3256 if (!transceiver->internal()->mid()) {
3257 // This transceiver is not associated with a media section yet.
3258 return nullptr;
3259 }
3260 return sdesc->description()->GetContentByName(
3261 *transceiver->internal()->mid());
3262 } else {
3263 // Plan B only allows at most one audio and one video section, so use the
3264 // first media section of that type.
3265 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003266 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003267 }
3268}
3269
deadbeef46c73892016-11-16 19:42:04 -08003270PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003271 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003272 return configuration_;
3273}
3274
deadbeef293e9262017-01-11 12:28:30 -08003275bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3276 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003277 RTC_DCHECK_RUN_ON(signaling_thread());
3278 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003279 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003280 if (IsClosed()) {
3281 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3282 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3283 }
3284
Qingsi Wanga2d60672018-04-11 16:57:45 -07003285 // According to JSEP, after setLocalDescription, changing the candidate pool
3286 // size is not allowed, and changing the set of ICE servers will not result
3287 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003288 if (local_description() && configuration.ice_candidate_pool_size !=
3289 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003290 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3291 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003292 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003293 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003294
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003295 if (local_description() &&
3296 configuration.use_media_transport != configuration_.use_media_transport) {
3297 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3298 "SetLocalDescription.";
3299 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3300 }
3301
3302 if (remote_description() &&
3303 configuration.use_media_transport != configuration_.use_media_transport) {
3304 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3305 "SetRemoteDescription.";
3306 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3307 }
3308
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003309 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003310 configuration.use_media_transport_for_data_channels !=
3311 configuration_.use_media_transport_for_data_channels) {
3312 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3313 "after calling SetLocalDescription.";
3314 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3315 }
3316
3317 if (remote_description() &&
3318 configuration.use_media_transport_for_data_channels !=
3319 configuration_.use_media_transport_for_data_channels) {
3320 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3321 "after calling SetRemoteDescription.";
3322 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3323 }
3324
3325 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003326 configuration.crypto_options != configuration_.crypto_options) {
3327 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3328 "SetLocalDescription.";
3329 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3330 }
3331
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003332 if (configuration.use_media_transport_for_data_channels ||
3333 configuration.use_media_transport) {
3334 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3335 << "Media transport requires MaxBundle policy.";
3336 }
3337
deadbeef293e9262017-01-11 12:28:30 -08003338 // The simplest (and most future-compatible) way to tell if the config was
3339 // modified in an invalid way is to copy each property we do support
3340 // modifying, then use operator==. There are far more properties we don't
3341 // support modifying than those we do, and more could be added.
3342 RTCConfiguration modified_config = configuration_;
3343 modified_config.servers = configuration.servers;
3344 modified_config.type = configuration.type;
3345 modified_config.ice_candidate_pool_size =
3346 configuration.ice_candidate_pool_size;
3347 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003348 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003349 modified_config.ice_check_interval_strong_connectivity =
3350 configuration.ice_check_interval_strong_connectivity;
3351 modified_config.ice_check_interval_weak_connectivity =
3352 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003353 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3354 modified_config.ice_unwritable_min_checks =
3355 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003356 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003357 modified_config.stun_candidate_keepalive_interval =
3358 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003359 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003360 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003361 modified_config.active_reset_srtp_params =
3362 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003363 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003364 modified_config.use_media_transport_for_data_channels =
3365 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003366 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003367 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003368 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3369 }
3370
Steve Anton038834f2017-07-14 15:59:59 -07003371 // Validate the modified configuration.
3372 RTCError validate_error = ValidateConfiguration(modified_config);
3373 if (!validate_error.ok()) {
3374 return SafeSetError(std::move(validate_error), error);
3375 }
3376
deadbeef293e9262017-01-11 12:28:30 -08003377 // Note that this isn't possible through chromium, since it's an unsigned
3378 // short in WebIDL.
3379 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003380 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003381 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3382 }
3383
3384 // Parse ICE servers before hopping to network thread.
3385 cricket::ServerAddresses stun_servers;
3386 std::vector<cricket::RelayServerConfig> turn_servers;
3387 RTCErrorType parse_error =
3388 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3389 if (parse_error != RTCErrorType::NONE) {
3390 return SafeSetError(parse_error, error);
3391 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003392 // Note if STUN or TURN servers were supplied.
3393 if (!stun_servers.empty()) {
3394 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3395 }
3396 if (!turn_servers.empty()) {
3397 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3398 }
deadbeef293e9262017-01-11 12:28:30 -08003399
3400 // In theory this shouldn't fail.
3401 if (!network_thread()->Invoke<bool>(
3402 RTC_FROM_HERE,
3403 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3404 stun_servers, turn_servers, modified_config.type,
3405 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003406 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003407 modified_config.turn_customizer,
3408 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003409 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003410 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3411 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003412
deadbeefd1a38b52016-12-10 13:15:33 -08003413 // As described in JSEP, calling setConfiguration with new ICE servers or
3414 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3415 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003416 if (modified_config.servers != configuration_.servers ||
3417 modified_config.type != configuration_.type ||
3418 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003419 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003420 }
skvladd1f5fda2017-02-03 16:54:05 -08003421
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003422 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003423 transport_controller_->SetMediaTransportSettings(
3424 modified_config.use_media_transport,
3425 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003426
Zhi Huangb57e1692018-06-12 11:41:11 -07003427 if (configuration_.active_reset_srtp_params !=
3428 modified_config.active_reset_srtp_params) {
3429 transport_controller_->SetActiveResetSrtpParams(
3430 modified_config.active_reset_srtp_params);
3431 }
3432
deadbeef293e9262017-01-11 12:28:30 -08003433 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003434 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003435 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003436}
3437
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438bool PeerConnection::AddIceCandidate(
3439 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003440 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003441 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003442 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003443 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003444 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003445 return false;
3446 }
Steve Antond25da372017-11-06 14:50:29 -08003447
3448 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003449 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003450 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003451 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003452 return false;
3453 }
3454
3455 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003456 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003457 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003458 return false;
3459 }
3460
3461 bool valid = false;
3462 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3463 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003464 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003465 return false;
3466 }
3467
3468 // Add this candidate to the remote session description.
3469 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003470 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003471 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003472 return false;
3473 }
3474
3475 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003476 bool result = UseCandidate(ice_candidate);
3477 if (result) {
3478 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3479 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3480 } else {
3481 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3482 }
3483 return result;
Steve Antond25da372017-11-06 14:50:29 -08003484 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003485 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003486 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003487 return true;
3488 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003489}
3490
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003491bool PeerConnection::RemoveIceCandidates(
3492 const std::vector<cricket::Candidate>& candidates) {
3493 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003494 if (IsClosed()) {
3495 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3496 return false;
3497 }
3498
Steve Antond25da372017-11-06 14:50:29 -08003499 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003500 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3501 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003502 return false;
3503 }
3504
3505 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003506 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003507 return false;
3508 }
3509
3510 size_t number_removed =
3511 mutable_remote_description()->RemoveCandidates(candidates);
3512 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003513 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003514 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003515 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003516 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003517 }
3518
3519 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003520 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3521 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003522 RTC_LOG(LS_ERROR)
3523 << "RemoveIceCandidates: Error when removing remote candidates: "
3524 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003525 }
3526 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003527}
3528
Niels Möller0c4f7be2018-05-07 14:01:37 +02003529RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003530 if (!worker_thread()->IsCurrent()) {
3531 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003532 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003533 }
3534
Niels Möller0c4f7be2018-05-07 14:01:37 +02003535 const bool has_min = bitrate.min_bitrate_bps.has_value();
3536 const bool has_start = bitrate.start_bitrate_bps.has_value();
3537 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003538 if (has_min && *bitrate.min_bitrate_bps < 0) {
3539 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3540 "min_bitrate_bps <= 0");
3541 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003542 if (has_start) {
3543 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003544 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003545 "start_bitrate_bps < min_bitrate_bps");
3546 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003547 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3548 "curent_bitrate_bps < 0");
3549 }
3550 }
3551 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003552 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003553 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003554 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003555 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3556 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3557 "max_bitrate_bps < min_bitrate_bps");
3558 } else if (*bitrate.max_bitrate_bps < 0) {
3559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3560 "max_bitrate_bps < 0");
3561 }
3562 }
3563
zstein4b979802017-06-02 14:37:37 -07003564 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003565 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003566
3567 return RTCError::OK();
3568}
3569
Alex Narest78609d52017-10-20 10:37:47 +02003570void PeerConnection::SetBitrateAllocationStrategy(
3571 std::unique_ptr<rtc::BitrateAllocationStrategy>
3572 bitrate_allocation_strategy) {
3573 rtc::Thread* worker_thread = factory_->worker_thread();
3574 if (!worker_thread->IsCurrent()) {
3575 rtc::BitrateAllocationStrategy* strategy_raw =
3576 bitrate_allocation_strategy.release();
3577 auto functor = [this, strategy_raw]() {
3578 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003579 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003580 };
3581 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3582 return;
3583 }
3584 RTC_DCHECK(call_.get());
3585 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3586}
3587
henrika5f6bf242017-11-01 11:06:56 +01003588void PeerConnection::SetAudioPlayout(bool playout) {
3589 if (!worker_thread()->IsCurrent()) {
3590 worker_thread()->Invoke<void>(
3591 RTC_FROM_HERE,
3592 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3593 return;
3594 }
3595 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003596 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003597 audio_state->SetPlayout(playout);
3598}
3599
3600void PeerConnection::SetAudioRecording(bool recording) {
3601 if (!worker_thread()->IsCurrent()) {
3602 worker_thread()->Invoke<void>(
3603 RTC_FROM_HERE,
3604 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3605 return;
3606 }
3607 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003608 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003609 audio_state->SetRecording(recording);
3610}
3611
Steve Anton8c0f7a72017-10-03 10:03:10 -07003612std::unique_ptr<rtc::SSLCertificate>
3613PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003614 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3615 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003616 return nullptr;
3617 }
Steve Antonf25303e2018-10-16 15:23:31 -07003618 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003619}
3620
Zhi Huang70b820f2018-01-27 14:16:15 -08003621std::unique_ptr<rtc::SSLCertChain>
3622PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003623 auto audio_transceiver = GetFirstAudioTransceiver();
3624 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003625 return nullptr;
3626 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003627 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003628 audio_transceiver->internal()->channel()->transport_name());
3629}
3630
3631rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3632PeerConnection::GetFirstAudioTransceiver() const {
3633 for (auto transceiver : transceivers_) {
3634 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3635 return transceiver;
3636 }
3637 }
3638 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003639}
3640
ivoc14d5dbe2016-07-04 07:06:55 -07003641bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3642 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003643 // TODO(eladalon): It would be better to not allow negative values into PC.
3644 const size_t max_size = (max_size_bytes < 0)
3645 ? RtcEventLog::kUnlimitedOutput
3646 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003647 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3648 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3649 output_period_ms = 5000;
3650 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003651 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003652 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003653 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003654}
3655
Bjorn Tereliusde939432017-11-20 17:38:14 +01003656bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3657 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003658 // TODO(eladalon): In C++14, this can be done with a lambda.
3659 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003660 bool operator()() {
3661 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3662 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003663 PeerConnection* const pc;
3664 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003665 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003666 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003667 return worker_thread()->Invoke<bool>(
3668 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003669}
3670
3671void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003672 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003673 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3674}
3675
Harald Alvestrandad88c882018-11-28 16:47:46 +01003676rtc::scoped_refptr<DtlsTransportInterface>
3677PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3678 return transport_controller_->LookupDtlsTransportByMid(mid);
3679}
3680
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003681rtc::scoped_refptr<DtlsTransport>
3682PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3683 return transport_controller_->LookupDtlsTransportByMid(mid);
3684}
3685
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003686rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3687 const {
3688 return sctp_transport_;
3689}
3690
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003691const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003692 return pending_local_description_ ? pending_local_description_.get()
3693 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003694}
3695
3696const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003697 return pending_remote_description_ ? pending_remote_description_.get()
3698 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003699}
3700
deadbeeffe4a8a42016-12-20 17:56:17 -08003701const SessionDescriptionInterface* PeerConnection::current_local_description()
3702 const {
Steve Anton75737c02017-11-06 10:37:17 -08003703 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003704}
3705
3706const SessionDescriptionInterface* PeerConnection::current_remote_description()
3707 const {
Steve Anton75737c02017-11-06 10:37:17 -08003708 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003709}
3710
3711const SessionDescriptionInterface* PeerConnection::pending_local_description()
3712 const {
Steve Anton75737c02017-11-06 10:37:17 -08003713 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003714}
3715
3716const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3717 const {
Steve Anton75737c02017-11-06 10:37:17 -08003718 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003719}
3720
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003721void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003722 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003723 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003724 // Update stats here so that we have the most recent stats for tracks and
3725 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003726 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003727
Steve Anton75737c02017-11-06 10:37:17 -08003728 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003729 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003730
Mirko Bonadei739baf02019-01-27 17:29:42 +01003731 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003732 transceiver->Stop();
3733 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003734
3735 // Ensure that all asynchronous stats requests are completed before destroying
3736 // the transport controller below.
3737 if (stats_collector_) {
3738 stats_collector_->WaitForPendingRequest();
3739 }
3740
3741 // Don't destroy BaseChannels until after stats has been cleaned up so that
3742 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003743 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003744
Qingsi Wang93a84392018-01-30 17:13:09 -08003745 // The event log is used in the transport controller, which must be outlived
3746 // by the former. CreateOffer by the peer connection is implemented
3747 // asynchronously and if the peer connection is closed without resetting the
3748 // WebRTC session description factory, the session description factory would
3749 // call the transport controller.
3750 webrtc_session_desc_factory_.reset();
3751 transport_controller_.reset();
3752
deadbeef42a42632017-03-10 15:18:00 -08003753 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003754 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3755 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003756
Steve Anton978b8762017-09-29 12:15:02 -07003757 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003758 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003759 call_.reset();
3760 // The event log must outlive call (and any other object that uses it).
3761 event_log_.reset();
3762 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003763 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003764 // The .h file says that observer can be discarded after close() returns.
3765 // Make sure this is true.
3766 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003767}
3768
Steve Antonad182762018-09-05 20:22:40 +00003769void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003770 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003771 switch (msg->message_id) {
3772 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3773 SetSessionDescriptionMsg* param =
3774 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3775 param->observer->OnSuccess();
3776 delete param;
3777 break;
3778 }
3779 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3780 SetSessionDescriptionMsg* param =
3781 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3782 param->observer->OnFailure(std::move(param->error));
3783 delete param;
3784 break;
3785 }
3786 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3787 CreateSessionDescriptionMsg* param =
3788 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3789 param->observer->OnFailure(std::move(param->error));
3790 delete param;
3791 break;
3792 }
3793 case MSG_GETSTATS: {
3794 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3795 StatsReports reports;
3796 stats_->GetStats(param->track, &reports);
3797 param->observer->OnComplete(reports);
3798 delete param;
3799 break;
3800 }
3801 case MSG_FREE_DATACHANNELS: {
3802 sctp_data_channels_to_free_.clear();
3803 break;
3804 }
3805 case MSG_REPORT_USAGE_PATTERN: {
3806 ReportUsagePattern();
3807 break;
3808 }
3809 default:
3810 RTC_NOTREACHED() << "Not implemented";
3811 break;
3812 }
3813}
3814
Steve Antonafb0bb72018-02-20 11:35:37 -08003815cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3816 RTC_DCHECK(!IsUnifiedPlan());
3817 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3818 GetAudioTransceiver()->internal()->channel());
3819 if (voice_channel) {
3820 return voice_channel->media_channel();
3821 } else {
3822 return nullptr;
3823 }
3824}
3825
3826cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3827 RTC_DCHECK(!IsUnifiedPlan());
3828 auto* video_channel = static_cast<cricket::VideoChannel*>(
3829 GetVideoTransceiver()->internal()->channel());
3830 if (video_channel) {
3831 return video_channel->media_channel();
3832 } else {
3833 return nullptr;
3834 }
3835}
3836
Steve Anton4171afb2017-11-20 10:20:22 -08003837void PeerConnection::CreateAudioReceiver(
3838 MediaStreamInterface* stream,
3839 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003840 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3841 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003842 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3843 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003844 auto* audio_receiver = new AudioRtpReceiver(
3845 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003846 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003847 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3848 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3849 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003850 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003851 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003852 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003853}
3854
Steve Anton4171afb2017-11-20 10:20:22 -08003855void PeerConnection::CreateVideoReceiver(
3856 MediaStreamInterface* stream,
3857 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003858 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3859 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003860 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3861 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003862 auto* video_receiver = new VideoRtpReceiver(
3863 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003864 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003865 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3866 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3867 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003868 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003869 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003870 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003871}
3872
deadbeef70ab1a12015-09-28 16:53:55 -07003873// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3874// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003875rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003876 const RtpSenderInfo& remote_sender_info) {
3877 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3878 if (!receiver) {
3879 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3880 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003881 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003882 }
Steve Anton4171afb2017-11-20 10:20:22 -08003883 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3884 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3885 } else {
3886 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3887 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003888 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003889}
3890
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003891void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3892 MediaStreamInterface* stream) {
3893 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003894 RTC_DCHECK(track);
3895 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003896 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003897 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003898 // We already have a sender for this track, so just change the stream_id
3899 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003900 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003901 return;
3902 }
3903
3904 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003905 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003906 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003907 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003908 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003909 // If the sender has already been configured in SDP, we call SetSsrc,
3910 // which will connect the sender to the underlying transport. This can
3911 // occur if a local session description that contains the ID of the sender
3912 // is set before AddStream is called. It can also occur if the local
3913 // session description is not changed and RemoveStream is called, and
3914 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003915 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003916 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003917 if (sender_info) {
3918 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003919 }
3920}
3921
3922// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3923// indefinitely, when we have unified plan SDP.
3924void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3925 MediaStreamInterface* stream) {
3926 RTC_DCHECK(!IsClosed());
3927 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003928 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003929 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3930 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003931 return;
3932 }
Steve Anton4171afb2017-11-20 10:20:22 -08003933 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003934}
3935
3936void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3937 MediaStreamInterface* stream) {
3938 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003939 RTC_DCHECK(track);
3940 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003941 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003942 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003943 // We already have a sender for this track, so just change the stream_id
3944 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003945 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003946 return;
3947 }
3948
3949 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003950 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003951 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003952 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003953 GetVideoTransceiver()->internal()->AddSender(new_sender);
3954 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003955 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003956 if (sender_info) {
3957 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003958 }
3959}
3960
3961void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3962 MediaStreamInterface* stream) {
3963 RTC_DCHECK(!IsClosed());
3964 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003965 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003966 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3967 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003968 return;
3969 }
Steve Anton4171afb2017-11-20 10:20:22 -08003970 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003971}
3972
Steve Antonba818672017-11-06 10:21:57 -08003973void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08003974 if (ice_connection_state_ == new_state) {
3975 return;
3976 }
3977
deadbeefcbecd352015-09-23 11:50:27 -07003978 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003979 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003980 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003981 return;
3982 }
Steve Antonba818672017-11-06 10:21:57 -08003983
Mirko Bonadei675513b2017-11-09 11:09:25 +01003984 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3985 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003986 RTC_DCHECK(ice_connection_state_ !=
3987 PeerConnectionInterface::kIceConnectionClosed);
3988
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003989 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003990 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003991}
3992
Alex Loiko9289eda2018-11-23 16:18:59 +00003993void PeerConnection::SetStandardizedIceConnectionState(
3994 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00003995 if (standardized_ice_connection_state_ == new_state)
3996 return;
3997 if (IsClosed())
3998 return;
3999 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004000 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004001}
4002
Jonas Olsson635474e2018-10-18 15:58:17 +02004003void PeerConnection::SetConnectionState(
4004 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004005 if (connection_state_ == new_state)
4006 return;
4007 if (IsClosed())
4008 return;
4009 connection_state_ = new_state;
4010 Observer()->OnConnectionChange(new_state);
4011}
4012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004013void PeerConnection::OnIceGatheringChange(
4014 PeerConnectionInterface::IceGatheringState new_state) {
4015 if (IsClosed()) {
4016 return;
4017 }
4018 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004019 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004020}
4021
jbauch81bf7b02017-03-25 08:31:12 -07004022void PeerConnection::OnIceCandidate(
4023 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004024 if (IsClosed()) {
4025 return;
4026 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004027 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004028 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4029 candidate->candidate().address().IsPrivateIP()) {
4030 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4031 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004032 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004033}
4034
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004035void PeerConnection::OnIceCandidatesRemoved(
4036 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004037 if (IsClosed()) {
4038 return;
4039 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004040 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004041}
4042
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004043void PeerConnection::ChangeSignalingState(
4044 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004045 if (signaling_state_ == signaling_state) {
4046 return;
4047 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004048 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4049 << GetSignalingStateString(signaling_state_)
4050 << " New state: "
4051 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004052 signaling_state_ = signaling_state;
4053 if (signaling_state == kClosed) {
4054 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004055 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004056 standardized_ice_connection_state_ =
4057 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004058 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4059 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004060 if (ice_gathering_state_ != kIceGatheringComplete) {
4061 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004062 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004063 }
4064 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004065 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004066}
4067
deadbeefeb459812015-12-15 19:24:43 -08004068void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4069 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004070 if (IsClosed()) {
4071 return;
4072 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004073 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004074 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004075}
4076
deadbeefeb459812015-12-15 19:24:43 -08004077void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4078 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004079 if (IsClosed()) {
4080 return;
4081 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004082 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004083 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004084}
4085
4086void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4087 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004088 if (IsClosed()) {
4089 return;
4090 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004091 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004092 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004093}
4094
4095void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4096 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004097 if (IsClosed()) {
4098 return;
4099 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004100 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004101 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004102}
4103
Henrik Boström31638672017-11-23 17:48:32 +01004104void PeerConnection::PostSetSessionDescriptionSuccess(
4105 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004106 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4107 signaling_thread()->Post(RTC_FROM_HERE, this,
4108 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004109}
4110
deadbeefab9b2d12015-10-14 11:33:11 -07004111void PeerConnection::PostSetSessionDescriptionFailure(
4112 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004113 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004114 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004115 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4116 msg->error = std::move(error);
4117 signaling_thread()->Post(RTC_FROM_HERE, this,
4118 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004119}
4120
4121void PeerConnection::PostCreateSessionDescriptionFailure(
4122 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004123 RTCError error) {
4124 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004125 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4126 msg->error = std::move(error);
4127 signaling_thread()->Post(RTC_FROM_HERE, this,
4128 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004129}
4130
zhihuang1c378ed2017-08-17 14:10:50 -07004131void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004132 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004133 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004134 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004135
Steve Antondcc3c022017-12-22 16:02:54 -08004136 if (IsUnifiedPlan()) {
4137 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4138 } else {
4139 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4140 }
4141
Steve Antonfa2260d2017-12-28 16:38:23 -08004142 // Intentionally unset the data channel type for RTP data channel with the
4143 // second condition. Otherwise the RTP data channels would be successfully
4144 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4145 // when building with chromium. We want to leave RTP data channels broken, so
4146 // people won't try to use them.
4147 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4148 session_options->data_channel_type = data_channel_type();
4149 }
4150
Steve Antondcc3c022017-12-22 16:02:54 -08004151 // Apply ICE restart flag and renomination flag.
4152 for (auto& options : session_options->media_description_options) {
4153 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4154 options.transport_options.enable_ice_renomination =
4155 configuration_.enable_ice_renomination;
4156 }
4157
4158 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004159 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004160 session_options->pooled_ice_credentials =
4161 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4162 RTC_FROM_HERE,
4163 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4164 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004165 session_options->offer_extmap_allow_mixed =
4166 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004167
4168 if (configuration_.enable_dtls_srtp &&
4169 !configuration_.enable_dtls_srtp.value()) {
4170 session_options->media_transport_settings =
4171 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4172 }
Steve Antondcc3c022017-12-22 16:02:54 -08004173}
4174
4175void PeerConnection::GetOptionsForPlanBOffer(
4176 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4177 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004178 // Figure out transceiver directional preferences.
4179 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4180 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4181
4182 // By default, generate sendrecv/recvonly m= sections.
4183 bool recv_audio = true;
4184 bool recv_video = true;
4185
4186 // By default, only offer a new m= section if we have media to send with it.
4187 bool offer_new_audio_description = send_audio;
4188 bool offer_new_video_description = send_video;
4189 bool offer_new_data_description = HasDataChannels();
4190
4191 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004192 if (offer_answer_options.offer_to_receive_audio !=
4193 RTCOfferAnswerOptions::kUndefined) {
4194 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004195 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004196 offer_new_audio_description ||
4197 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004198 }
Steve Antondcc3c022017-12-22 16:02:54 -08004199 if (offer_answer_options.offer_to_receive_video !=
4200 RTCOfferAnswerOptions::kUndefined) {
4201 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004202 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004203 offer_new_video_description ||
4204 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004205 }
4206
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004207 absl::optional<size_t> audio_index;
4208 absl::optional<size_t> video_index;
4209 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004210 // If a current description exists, generate m= sections in the same order,
4211 // using the first audio/video/data section that appears and rejecting
4212 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004213 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004214 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004215 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004216 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4217 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4218 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004219 }
4220
zhihuang1c378ed2017-08-17 14:10:50 -07004221 // Add audio/video/data m= sections to the end if needed.
4222 if (!audio_index && offer_new_audio_description) {
4223 session_options->media_description_options.push_back(
4224 cricket::MediaDescriptionOptions(
4225 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004226 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4227 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004228 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004229 }
zhihuang1c378ed2017-08-17 14:10:50 -07004230 if (!video_index && offer_new_video_description) {
4231 session_options->media_description_options.push_back(
4232 cricket::MediaDescriptionOptions(
4233 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004234 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4235 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004236 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004237 }
zhihuang1c378ed2017-08-17 14:10:50 -07004238 if (!data_index && offer_new_data_description) {
4239 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004240 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004241 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004242 }
4243
4244 cricket::MediaDescriptionOptions* audio_media_description_options =
4245 !audio_index ? nullptr
4246 : &session_options->media_description_options[*audio_index];
4247 cricket::MediaDescriptionOptions* video_media_description_options =
4248 !video_index ? nullptr
4249 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004250
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004251 AddPlanBRtpSenderOptions(GetSendersInternal(),
4252 audio_media_description_options,
4253 video_media_description_options,
4254 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004255}
4256
Steve Antondcc3c022017-12-22 16:02:54 -08004257static cricket::MediaDescriptionOptions
4258GetMediaDescriptionOptionsForTransceiver(
4259 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4260 transceiver,
4261 const std::string& mid) {
4262 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004263 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004264 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004265 // This behavior is specified in JSEP. The gist is that:
4266 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4267 // sendrecv.
4268 // 2. If the MSID is included, then it must be included in any subsequent
4269 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004270 if (transceiver->stopped() ||
4271 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4272 !transceiver->internal()->has_ever_been_used_to_send())) {
4273 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004274 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004275
4276 cricket::SenderOptions sender_options;
4277 sender_options.track_id = transceiver->sender()->id();
4278 sender_options.stream_ids = transceiver->sender()->stream_ids();
4279
4280 // The following sets up RIDs and Simulcast.
4281 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004282 RtpParameters send_parameters =
4283 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004284 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4285 send_parameters.encodings.end(),
4286 [](const RtpEncodingParameters& encoding) {
4287 return !encoding.rid.empty();
4288 });
4289
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004290 std::vector<RidDescription> send_rids;
4291 SimulcastLayerList send_layers;
4292 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4293 if (encoding.rid.empty()) {
4294 continue;
4295 }
4296 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4297 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4298 }
4299
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004300 if (has_rids) {
4301 sender_options.rids = send_rids;
4302 }
4303
4304 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004305 // When RIDs are configured, we must set num_sim_layers to 0 to.
4306 // Otherwise, num_sim_layers must be 1 because either there is no
4307 // simulcast, or simulcast is acheived by munging the SDP.
4308 sender_options.num_sim_layers = has_rids ? 0 : 1;
4309 media_description_options.sender_options.push_back(sender_options);
4310
Steve Antondcc3c022017-12-22 16:02:54 -08004311 return media_description_options;
4312}
4313
Steve Anton5c72e712018-12-10 14:25:30 -08004314// Returns the ContentInfo at mline index |i|, or null if none exists.
4315static const ContentInfo* GetContentByIndex(
4316 const SessionDescriptionInterface* sdesc,
4317 size_t i) {
4318 if (!sdesc) {
4319 return nullptr;
4320 }
4321 const ContentInfos& contents = sdesc->description()->contents();
4322 return (i < contents.size() ? &contents[i] : nullptr);
4323}
4324
Steve Antondcc3c022017-12-22 16:02:54 -08004325void PeerConnection::GetOptionsForUnifiedPlanOffer(
4326 const RTCOfferAnswerOptions& offer_answer_options,
4327 cricket::MediaSessionOptions* session_options) {
4328 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4329 // Offers) and 5.2.2 (Subsequent Offers).
4330 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4331 const ContentInfos& local_contents =
4332 (local_description() ? local_description()->description()->contents()
4333 : ContentInfos());
4334 const ContentInfos& remote_contents =
4335 (remote_description() ? remote_description()->description()->contents()
4336 : ContentInfos());
4337 // The mline indices that can be recycled. New transceivers should reuse these
4338 // slots first.
4339 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004340 // First, go through each media section that exists in either the local or
4341 // remote description and generate a media section in this offer for the
4342 // associated transceiver. If a media section can be recycled, generate a
4343 // default, rejected media section here that can be later overwritten.
4344 for (size_t i = 0;
4345 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4346 // Either |local_content| or |remote_content| is non-null.
4347 const ContentInfo* local_content =
4348 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004349 const ContentInfo* current_local_content =
4350 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004351 const ContentInfo* remote_content =
4352 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004353 const ContentInfo* current_remote_content =
4354 GetContentByIndex(current_remote_description(), i);
4355 bool had_been_rejected =
4356 (current_local_content && current_local_content->rejected) ||
4357 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004358 const std::string& mid =
4359 (local_content ? local_content->name : remote_content->name);
4360 cricket::MediaType media_type =
4361 (local_content ? local_content->media_description()->type()
4362 : remote_content->media_description()->type());
4363 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4364 media_type == cricket::MEDIA_TYPE_VIDEO) {
4365 auto transceiver = GetAssociatedTransceiver(mid);
4366 RTC_CHECK(transceiver);
4367 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004368 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004369 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004370 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004371 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4372 RtpTransceiverDirection::kInactive,
4373 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004374 recycleable_mline_indices.push(i);
4375 } else {
4376 session_options->media_description_options.push_back(
4377 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4378 // CreateOffer shouldn't really cause any state changes in
4379 // PeerConnection, but we need a way to match new transceivers to new
4380 // media sections in SetLocalDescription and JSEP specifies this is done
4381 // by recording the index of the media section generated for the
4382 // transceiver in the offer.
4383 transceiver->internal()->set_mline_index(i);
4384 }
4385 } else {
4386 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004387 RTC_CHECK(GetDataMid());
4388 if (had_been_rejected || mid != *GetDataMid()) {
4389 session_options->media_description_options.push_back(
4390 GetMediaDescriptionOptionsForRejectedData(mid));
4391 } else {
4392 session_options->media_description_options.push_back(
4393 GetMediaDescriptionOptionsForActiveData(mid));
4394 }
Steve Antondcc3c022017-12-22 16:02:54 -08004395 }
4396 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004397
Steve Antondcc3c022017-12-22 16:02:54 -08004398 // Next, look for transceivers that are newly added (that is, are not stopped
4399 // and not associated). Reuse media sections marked as recyclable first,
4400 // otherwise append to the end of the offer. New media sections should be
4401 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004402 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004403 if (transceiver->mid() || transceiver->stopped()) {
4404 continue;
4405 }
4406 size_t mline_index;
4407 if (!recycleable_mline_indices.empty()) {
4408 mline_index = recycleable_mline_indices.front();
4409 recycleable_mline_indices.pop();
4410 session_options->media_description_options[mline_index] =
4411 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004412 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004413 } else {
4414 mline_index = session_options->media_description_options.size();
4415 session_options->media_description_options.push_back(
4416 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004417 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004418 }
4419 // See comment above for why CreateOffer changes the transceiver's state.
4420 transceiver->internal()->set_mline_index(mline_index);
4421 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004422 // Lastly, add a m-section if we have local data channels and an m section
4423 // does not already exist.
4424 if (!GetDataMid() && HasDataChannels()) {
4425 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004426 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004427 }
Steve Antondcc3c022017-12-22 16:02:54 -08004428}
4429
4430void PeerConnection::GetOptionsForAnswer(
4431 const RTCOfferAnswerOptions& offer_answer_options,
4432 cricket::MediaSessionOptions* session_options) {
4433 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4434
4435 if (IsUnifiedPlan()) {
4436 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4437 } else {
4438 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4439 }
4440
Steve Antonfa2260d2017-12-28 16:38:23 -08004441 // Intentionally unset the data channel type for RTP data channel. Otherwise
4442 // the RTP data channels would be successfully negotiated by default and the
4443 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4444 // We want to leave RTP data channels broken, so people won't try to use them.
4445 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4446 session_options->data_channel_type = data_channel_type();
4447 }
4448
Steve Antondcc3c022017-12-22 16:02:54 -08004449 // Apply ICE renomination flag.
4450 for (auto& options : session_options->media_description_options) {
4451 options.transport_options.enable_ice_renomination =
4452 configuration_.enable_ice_renomination;
4453 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004454
4455 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004456 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004457 session_options->pooled_ice_credentials =
4458 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4459 RTC_FROM_HERE,
4460 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4461 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004462}
4463
Steve Antondcc3c022017-12-22 16:02:54 -08004464void PeerConnection::GetOptionsForPlanBAnswer(
4465 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004466 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004467 // Figure out transceiver directional preferences.
4468 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4469 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4470
4471 // By default, generate sendrecv/recvonly m= sections. The direction is also
4472 // restricted by the direction in the offer.
4473 bool recv_audio = true;
4474 bool recv_video = true;
4475
4476 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004477 if (offer_answer_options.offer_to_receive_audio !=
4478 RTCOfferAnswerOptions::kUndefined) {
4479 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004480 }
Steve Antondcc3c022017-12-22 16:02:54 -08004481 if (offer_answer_options.offer_to_receive_video !=
4482 RTCOfferAnswerOptions::kUndefined) {
4483 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004484 }
4485
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004486 absl::optional<size_t> audio_index;
4487 absl::optional<size_t> video_index;
4488 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004489
4490 // Generate m= sections that match those in the offer.
4491 // Note that mediasession.cc will handle intersection our preferred
4492 // direction with the offered direction.
4493 GenerateMediaDescriptionOptions(
4494 remote_description(),
4495 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4496 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4497 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004498
4499 cricket::MediaDescriptionOptions* audio_media_description_options =
4500 !audio_index ? nullptr
4501 : &session_options->media_description_options[*audio_index];
4502 cricket::MediaDescriptionOptions* video_media_description_options =
4503 !video_index ? nullptr
4504 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004505
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004506 AddPlanBRtpSenderOptions(GetSendersInternal(),
4507 audio_media_description_options,
4508 video_media_description_options,
4509 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004510}
zhihuangaf388472016-11-02 16:49:48 -07004511
Steve Antondcc3c022017-12-22 16:02:54 -08004512void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4513 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4514 cricket::MediaSessionOptions* session_options) {
4515 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4516 // Answers) and 5.3.2 (Subsequent Answers).
4517 RTC_DCHECK(remote_description());
4518 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4519 for (const ContentInfo& content :
4520 remote_description()->description()->contents()) {
4521 cricket::MediaType media_type = content.media_description()->type();
4522 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4523 media_type == cricket::MEDIA_TYPE_VIDEO) {
4524 auto transceiver = GetAssociatedTransceiver(content.name);
4525 RTC_CHECK(transceiver);
4526 session_options->media_description_options.push_back(
4527 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4528 } else {
4529 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004530 // Reject all data sections if data channels are disabled.
4531 // Reject a data section if it has already been rejected.
4532 // Reject all data sections except for the first one.
4533 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4534 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004535 session_options->media_description_options.push_back(
4536 GetMediaDescriptionOptionsForRejectedData(content.name));
4537 } else {
4538 session_options->media_description_options.push_back(
4539 GetMediaDescriptionOptionsForActiveData(content.name));
4540 }
Steve Antondcc3c022017-12-22 16:02:54 -08004541 }
4542 }
htaa2a49d92016-03-04 02:51:39 -08004543}
4544
zhihuang1c378ed2017-08-17 14:10:50 -07004545void PeerConnection::GenerateMediaDescriptionOptions(
4546 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004547 RtpTransceiverDirection audio_direction,
4548 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004549 absl::optional<size_t>* audio_index,
4550 absl::optional<size_t>* video_index,
4551 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004552 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004553 for (const cricket::ContentInfo& content :
4554 session_desc->description()->contents()) {
4555 if (IsAudioContent(&content)) {
4556 // If we already have an audio m= section, reject this extra one.
4557 if (*audio_index) {
4558 session_options->media_description_options.push_back(
4559 cricket::MediaDescriptionOptions(
4560 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004561 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004562 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004563 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004564 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004565 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4566 content.name, audio_direction,
4567 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004568 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004569 }
4570 } else if (IsVideoContent(&content)) {
4571 // If we already have an video m= section, reject this extra one.
4572 if (*video_index) {
4573 session_options->media_description_options.push_back(
4574 cricket::MediaDescriptionOptions(
4575 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004576 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004577 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004578 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004579 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004580 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4581 content.name, video_direction,
4582 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004583 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004584 }
4585 } else {
4586 RTC_DCHECK(IsDataContent(&content));
4587 // If we already have an data m= section, reject this extra one.
4588 if (*data_index) {
4589 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004590 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004591 } else {
4592 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004593 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004594 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004595 }
4596 }
htaa2a49d92016-03-04 02:51:39 -08004597 }
deadbeefab9b2d12015-10-14 11:33:11 -07004598}
4599
Steve Antonfa2260d2017-12-28 16:38:23 -08004600cricket::MediaDescriptionOptions
4601PeerConnection::GetMediaDescriptionOptionsForActiveData(
4602 const std::string& mid) const {
4603 // Direction for data sections is meaningless, but legacy endpoints might
4604 // expect sendrecv.
4605 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4606 RtpTransceiverDirection::kSendRecv,
4607 /*stopped=*/false);
4608 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4609 return options;
4610}
4611
4612cricket::MediaDescriptionOptions
4613PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4614 const std::string& mid) const {
4615 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4616 RtpTransceiverDirection::kInactive,
4617 /*stopped=*/true);
4618 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4619 return options;
4620}
4621
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004622absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004623 switch (data_channel_type_) {
4624 case cricket::DCT_RTP:
4625 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004626 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004627 }
4628 return rtp_data_channel_->content_name();
4629 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004630 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004631 case cricket::DCT_MEDIA_TRANSPORT:
4632 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004633 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004634 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004635 }
4636}
4637
Steve Anton4171afb2017-11-20 10:20:22 -08004638void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4639 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4640 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004641 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004642}
4643
Steve Anton4171afb2017-11-20 10:20:22 -08004644void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004645 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004646 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004647 cricket::MediaType media_type,
4648 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004649 RTC_DCHECK(!IsUnifiedPlan());
4650
Steve Anton4171afb2017-11-20 10:20:22 -08004651 std::vector<RtpSenderInfo>* current_senders =
4652 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004653
Steve Anton4171afb2017-11-20 10:20:22 -08004654 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004655 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004656 for (auto sender_it = current_senders->begin();
4657 sender_it != current_senders->end();
4658 /* incremented manually */) {
4659 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004660 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004661 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004662 std::string params_stream_id;
4663 if (params) {
4664 params_stream_id =
4665 (!params->first_stream_id().empty() ? params->first_stream_id()
4666 : kDefaultStreamId);
4667 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004668 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004669 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004670 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004671 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004672 sender_exists) {
4673 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004674 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004675 OnRemoteSenderRemoved(info, media_type);
4676 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004677 }
4678 }
4679
Steve Anton4171afb2017-11-20 10:20:22 -08004680 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004681 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004682 if (!params.has_ssrcs()) {
4683 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4684 // sender, this means it is coming from a Unified Plan endpoint,so we just
4685 // create a default.
4686 default_sender_needed = true;
4687 break;
4688 }
4689
Seth Hampson845e8782018-03-02 11:34:10 -08004690 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004691 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004692 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4693 // not supported in Plan B, we just take the first here and create the
4694 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004695 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004696 (!params.first_stream_id().empty() ? params.first_stream_id()
4697 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004698 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004699 uint32_t ssrc = params.first_ssrc();
4700
4701 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004702 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004703 if (!stream) {
4704 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004705 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004706 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004707 remote_streams_->AddStream(stream);
4708 new_streams->AddStream(stream);
4709 }
4710
Steve Anton4171afb2017-11-20 10:20:22 -08004711 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004712 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004713 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004714 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004715 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004716 }
4717 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004718
Steve Anton4171afb2017-11-20 10:20:22 -08004719 // Add default sender if necessary.
4720 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004721 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004722 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004723 if (!default_stream) {
4724 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004725 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004726 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004727 remote_streams_->AddStream(default_stream);
4728 new_streams->AddStream(default_stream);
4729 }
Steve Anton4171afb2017-11-20 10:20:22 -08004730 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4731 ? kDefaultAudioSenderId
4732 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004733 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004734 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004735 if (!default_sender_info) {
4736 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004737 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004738 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004739 }
4740 }
deadbeefab9b2d12015-10-14 11:33:11 -07004741}
4742
Steve Anton4171afb2017-11-20 10:20:22 -08004743void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4744 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004745 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4746 << " receiver for track_id=" << sender_info.sender_id
4747 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004748
Steve Anton3d954a62018-04-02 11:27:23 -07004749 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004750 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004751 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004752 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004753 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004754 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004755 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004756 }
4757}
4758
Steve Anton4171afb2017-11-20 10:20:22 -08004759void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4760 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004761 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4762 << " receiver for track_id=" << sender_info.sender_id
4763 << " and stream_id=" << sender_info.stream_id;
4764
Seth Hampson845e8782018-03-02 11:34:10 -08004765 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004766
Henrik Boström933d8b02017-10-10 10:05:16 -07004767 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004768 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004769 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4770 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004771 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004772 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004773 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004774 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004775 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004776 }
4777 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004778 // Stopping or destroying a VideoRtpReceiver will end the
4779 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004780 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004781 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004782 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004783 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004784 // There's no guarantee the track is still available, e.g. the track may
4785 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004786 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004787 }
4788 } else {
nisseede5da42017-01-12 05:15:36 -08004789 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004790 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004791 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004792 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004793 }
deadbeefab9b2d12015-10-14 11:33:11 -07004794}
4795
4796void PeerConnection::UpdateEndedRemoteMediaStreams() {
4797 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4798 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4799 MediaStreamInterface* stream = remote_streams_->at(i);
4800 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4801 streams_to_remove.push_back(stream);
4802 }
4803 }
4804
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004805 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004806 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004807 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004808 }
4809}
4810
Steve Anton4171afb2017-11-20 10:20:22 -08004811void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004812 const std::vector<cricket::StreamParams>& streams,
4813 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004814 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004815
Seth Hampson845e8782018-03-02 11:34:10 -08004816 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004817 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004818 for (auto sender_it = current_senders->begin();
4819 sender_it != current_senders->end();
4820 /* incremented manually */) {
4821 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004822 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004823 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4824 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004825 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004826 OnLocalSenderRemoved(info, media_type);
4827 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004828 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004829 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004830 }
4831 }
4832
Steve Anton4171afb2017-11-20 10:20:22 -08004833 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004834 for (const cricket::StreamParams& params : streams) {
4835 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004836 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004837 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004838 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004839 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004840 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004841 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004842 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004843 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004844 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004845 }
4846 }
4847}
4848
Steve Anton4171afb2017-11-20 10:20:22 -08004849void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4850 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004851 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004852 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004853 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004854 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4855 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004856 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004857 return;
4858 }
4859
deadbeeffac06552015-11-25 11:26:01 -08004860 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004861 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004862 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004863 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004864 }
deadbeeffac06552015-11-25 11:26:01 -08004865
Seth Hampson5b4f0752018-04-02 16:31:36 -07004866 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004867 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004868}
4869
Steve Anton4171afb2017-11-20 10:20:22 -08004870void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4871 cricket::MediaType media_type) {
4872 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004873 if (!sender) {
4874 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004875 // SessionDescriptions has been renegotiated.
4876 return;
4877 }
deadbeeffac06552015-11-25 11:26:01 -08004878
4879 // A sender has been removed from the SessionDescription but it's still
4880 // associated with the PeerConnection. This only occurs if the SDP doesn't
4881 // match with the calls to CreateSender, AddStream and RemoveStream.
4882 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004883 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004884 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004885 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004886 }
deadbeeffac06552015-11-25 11:26:01 -08004887
Steve Anton4171afb2017-11-20 10:20:22 -08004888 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004889}
4890
4891void PeerConnection::UpdateLocalRtpDataChannels(
4892 const cricket::StreamParamsVec& streams) {
4893 std::vector<std::string> existing_channels;
4894
4895 // Find new and active data channels.
4896 for (const cricket::StreamParams& params : streams) {
4897 // |it->sync_label| is actually the data channel label. The reason is that
4898 // we use the same naming of data channels as we do for
4899 // MediaStreams and Tracks.
4900 // For MediaStreams, the sync_label is the MediaStream label and the
4901 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004902 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004903 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004904 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004905 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004906 continue;
4907 }
4908 // Set the SSRC the data channel should use for sending.
4909 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4910 existing_channels.push_back(data_channel_it->first);
4911 }
4912
4913 UpdateClosingRtpDataChannels(existing_channels, true);
4914}
4915
4916void PeerConnection::UpdateRemoteRtpDataChannels(
4917 const cricket::StreamParamsVec& streams) {
4918 std::vector<std::string> existing_channels;
4919
4920 // Find new and active data channels.
4921 for (const cricket::StreamParams& params : streams) {
4922 // The data channel label is either the mslabel or the SSRC if the mslabel
4923 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004924 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004925 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004926 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004927 auto data_channel_it = rtp_data_channels_.find(label);
4928 if (data_channel_it == rtp_data_channels_.end()) {
4929 // This is a new data channel.
4930 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4931 } else {
4932 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4933 }
4934 existing_channels.push_back(label);
4935 }
4936
4937 UpdateClosingRtpDataChannels(existing_channels, false);
4938}
4939
4940void PeerConnection::UpdateClosingRtpDataChannels(
4941 const std::vector<std::string>& active_channels,
4942 bool is_local_update) {
4943 auto it = rtp_data_channels_.begin();
4944 while (it != rtp_data_channels_.end()) {
4945 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004946 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004947 ++it;
4948 continue;
4949 }
4950
4951 if (is_local_update) {
4952 data_channel->SetSendSsrc(0);
4953 } else {
4954 data_channel->RemotePeerRequestClose();
4955 }
4956
4957 if (data_channel->state() == DataChannel::kClosed) {
4958 rtp_data_channels_.erase(it);
4959 it = rtp_data_channels_.begin();
4960 } else {
4961 ++it;
4962 }
4963 }
4964}
4965
4966void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4967 uint32_t remote_ssrc) {
4968 rtc::scoped_refptr<DataChannel> channel(
4969 InternalCreateDataChannel(label, nullptr));
4970 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004971 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004972 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004973 return;
4974 }
4975 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004976 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4977 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004978 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004979}
4980
4981rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4982 const std::string& label,
4983 const InternalDataChannelInit* config) {
4984 if (IsClosed()) {
4985 return nullptr;
4986 }
Steve Anton75737c02017-11-06 10:37:17 -08004987 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004988 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004989 << "InternalCreateDataChannel: Data is not supported in this call.";
4990 return nullptr;
4991 }
4992 InternalDataChannelInit new_config =
4993 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004994 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004995 if (new_config.id < 0) {
4996 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004997 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004998 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004999 RTC_LOG(LS_ERROR)
5000 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005001 return nullptr;
5002 }
5003 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005004 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005005 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005006 return nullptr;
5007 }
5008 }
5009
Steve Anton75737c02017-11-06 10:37:17 -08005010 rtc::scoped_refptr<DataChannel> channel(
5011 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005012 if (!channel) {
5013 sid_allocator_.ReleaseSid(new_config.id);
5014 return nullptr;
5015 }
5016
5017 if (channel->data_channel_type() == cricket::DCT_RTP) {
5018 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005019 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5020 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005021 return nullptr;
5022 }
5023 rtp_data_channels_[channel->label()] = channel;
5024 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005025 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005026 sctp_data_channels_.push_back(channel);
5027 channel->SignalClosed.connect(this,
5028 &PeerConnection::OnSctpDataChannelClosed);
5029 }
5030
Steve Anton2d8609c2018-01-23 16:38:46 -08005031 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005032 return channel;
5033}
5034
5035bool PeerConnection::HasDataChannels() const {
5036 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5037}
5038
5039void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
5040 for (const auto& channel : sctp_data_channels_) {
5041 if (channel->id() < 0) {
5042 int sid;
5043 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005044 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07005045 continue;
5046 }
5047 channel->SetSctpSid(sid);
5048 }
5049 }
5050}
5051
5052void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005053 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005054 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5055 ++it) {
5056 if (it->get() == channel) {
5057 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005058 // After the closing procedure is done, it's safe to use this ID for
5059 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005060 sid_allocator_.ReleaseSid(channel->id());
5061 }
deadbeefbd292462015-12-14 18:15:29 -08005062 // Since this method is triggered by a signal from the DataChannel,
5063 // we can't free it directly here; we need to free it asynchronously.
5064 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005065 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005066 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5067 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005068 return;
5069 }
5070 }
5071}
5072
deadbeefab9b2d12015-10-14 11:33:11 -07005073void PeerConnection::OnDataChannelDestroyed() {
5074 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5075 // DataChannel may callback to us and try to modify the list.
5076 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5077 temp_rtp_dcs.swap(rtp_data_channels_);
5078 for (const auto& kv : temp_rtp_dcs) {
5079 kv.second->OnTransportChannelDestroyed();
5080 }
5081
5082 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5083 temp_sctp_dcs.swap(sctp_data_channels_);
5084 for (const auto& channel : temp_sctp_dcs) {
5085 channel->OnTransportChannelDestroyed();
5086 }
5087}
5088
5089void PeerConnection::OnDataChannelOpenMessage(
5090 const std::string& label,
5091 const InternalDataChannelInit& config) {
5092 rtc::scoped_refptr<DataChannel> channel(
5093 InternalCreateDataChannel(label, &config));
5094 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005095 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005096 return;
5097 }
5098
deadbeefa601f5c2016-06-06 14:27:39 -07005099 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5100 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005101 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005102 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005103}
5104
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005105bool PeerConnection::HandleOpenMessage_s(
5106 const cricket::ReceiveDataParams& params,
5107 const rtc::CopyOnWriteBuffer& buffer) {
5108 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5109 // Received OPEN message; parse and signal that a new data channel should
5110 // be created.
5111 std::string label;
5112 InternalDataChannelInit config;
5113 config.id = params.ssrc;
5114 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5115 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5116 << params.ssrc;
5117 return true;
5118 }
5119 config.open_handshake_role = InternalDataChannelInit::kAcker;
5120 OnDataChannelOpenMessage(label, config);
5121 return true;
5122 }
5123 return false;
5124}
5125
Steve Anton4171afb2017-11-20 10:20:22 -08005126rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5127PeerConnection::GetAudioTransceiver() const {
5128 // This method only works with Plan B SDP, where there is a single
5129 // audio/video transceiver.
5130 RTC_DCHECK(!IsUnifiedPlan());
5131 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005132 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005133 return transceiver;
5134 }
5135 }
5136 RTC_NOTREACHED();
5137 return nullptr;
5138}
5139
5140rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5141PeerConnection::GetVideoTransceiver() const {
5142 // This method only works with Plan B SDP, where there is a single
5143 // audio/video transceiver.
5144 RTC_DCHECK(!IsUnifiedPlan());
5145 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005146 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005147 return transceiver;
5148 }
5149 }
5150 RTC_NOTREACHED();
5151 return nullptr;
5152}
5153
5154// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5155// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005156bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005157 switch (type) {
5158 case cricket::MEDIA_TYPE_AUDIO:
5159 return !GetAudioTransceiver()->internal()->senders().empty();
5160 case cricket::MEDIA_TYPE_VIDEO:
5161 return !GetVideoTransceiver()->internal()->senders().empty();
5162 case cricket::MEDIA_TYPE_DATA:
5163 return false;
5164 }
5165 RTC_NOTREACHED();
5166 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005167}
5168
Steve Anton4171afb2017-11-20 10:20:22 -08005169rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5170PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005171 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005172 for (auto sender : transceiver->internal()->senders()) {
5173 if (sender->track() == track) {
5174 return sender;
5175 }
5176 }
5177 }
5178 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005179}
5180
Steve Anton4171afb2017-11-20 10:20:22 -08005181rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5182PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005183 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005184 for (auto sender : transceiver->internal()->senders()) {
5185 if (sender->id() == sender_id) {
5186 return sender;
5187 }
5188 }
5189 }
5190 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005191}
5192
Steve Anton4171afb2017-11-20 10:20:22 -08005193rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5194PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005195 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005196 for (auto receiver : transceiver->internal()->receivers()) {
5197 if (receiver->id() == receiver_id) {
5198 return receiver;
5199 }
5200 }
5201 }
5202 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005203}
5204
Steve Anton4171afb2017-11-20 10:20:22 -08005205std::vector<PeerConnection::RtpSenderInfo>*
5206PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5207 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5208 media_type == cricket::MEDIA_TYPE_VIDEO);
5209 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5210 ? &remote_audio_sender_infos_
5211 : &remote_video_sender_infos_;
5212}
5213
5214std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005215 cricket::MediaType media_type) {
5216 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5217 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005218 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5219 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005220}
5221
Steve Anton4171afb2017-11-20 10:20:22 -08005222const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5223 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005224 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005225 const std::string sender_id) const {
5226 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005227 if (sender_info.stream_id == stream_id &&
5228 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005229 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005230 }
5231 }
5232 return nullptr;
5233}
5234
5235DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5236 for (const auto& channel : sctp_data_channels_) {
5237 if (channel->id() == sid) {
5238 return channel;
5239 }
5240 }
5241 return nullptr;
5242}
5243
deadbeef91dd5672016-05-18 16:55:30 -07005244bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005245 const cricket::ServerAddresses& stun_servers,
5246 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005247 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005248 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005249 // To handle both internal and externally created port allocator, we will
5250 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005251 port_allocator_flags_ = port_allocator_->flags();
5252 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5253 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5254 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005255 // If the disable-IPv6 flag was specified, we'll not override it
5256 // by experiment.
5257 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005258 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005259 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5260 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005261 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005262 }
5263
zhihuangb09b3f92017-03-07 14:40:51 -08005264 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005265 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005266 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005267 }
5268
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005269 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005270 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005271 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005272 }
5273
honghaiz60347052016-05-31 18:29:12 -07005274 if (configuration.candidate_network_policy ==
5275 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005276 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005277 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005278 }
5279
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005280 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005281 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005282 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5283 }
5284
Qingsi Wanga2d60672018-04-11 16:57:45 -07005285 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005286 // No step delay is used while allocating ports.
5287 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5288 port_allocator_->set_candidate_filter(
5289 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005290 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005291
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005292 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005293 for (auto& turn_server : turn_servers_copy) {
5294 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005295 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005296 // Call this last since it may create pooled allocator sessions using the
5297 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005298 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005299 stun_servers, std::move(turn_servers_copy),
5300 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5301 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005302 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005303 return true;
5304}
5305
deadbeef91dd5672016-05-18 16:55:30 -07005306bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005307 const cricket::ServerAddresses& stun_servers,
5308 const std::vector<cricket::RelayServerConfig>& turn_servers,
5309 IceTransportsType type,
5310 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005311 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005312 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005313 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005314 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005315 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005316 // According to JSEP, after setLocalDescription, changing the candidate pool
5317 // size is not allowed, and changing the set of ICE servers will not result
5318 // in new candidates being gathered.
5319 if (local_description()) {
5320 port_allocator_->FreezeCandidatePool();
5321 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005322 // Add the custom tls turn servers if they exist.
5323 auto turn_servers_copy = turn_servers;
5324 for (auto& turn_server : turn_servers_copy) {
5325 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5326 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005327 // Call this last since it may create pooled allocator sessions using the
5328 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005329 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005330 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5331 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005332}
5333
Steve Antonba818672017-11-06 10:21:57 -08005334cricket::ChannelManager* PeerConnection::channel_manager() const {
5335 return factory_->channel_manager();
5336}
5337
Elad Alon99c3fe52017-10-13 16:29:40 +02005338bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005339 std::unique_ptr<RtcEventLogOutput> output,
5340 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005341 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005342 if (!event_log_) {
5343 return false;
5344 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005345 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005346}
5347
5348void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005349 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005350 if (event_log_) {
5351 event_log_->StopLogging();
5352 }
ivoc14d5dbe2016-07-04 07:06:55 -07005353}
nisseeaabdf62017-05-05 02:23:02 -07005354
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005355cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005356 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005357 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005358 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005359 if (channel && channel->content_name() == content_name) {
5360 return channel;
5361 }
Steve Anton75737c02017-11-06 10:37:17 -08005362 }
5363 if (rtp_data_channel() &&
5364 rtp_data_channel()->content_name() == content_name) {
5365 return rtp_data_channel();
5366 }
5367 return nullptr;
5368}
5369
5370bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005371 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005372 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005373 RTC_LOG(LS_INFO)
5374 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005375 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005376 return false;
5377 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005378 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005379 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005380 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005381 return false;
5382 }
5383
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005384 absl::optional<rtc::SSLRole> dtls_role;
5385 if (sctp_mid_) {
5386 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5387 } else if (is_caller_) {
5388 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5389 }
Zhi Huange830e682018-03-30 10:48:35 -07005390 if (dtls_role) {
5391 *role = *dtls_role;
5392 return true;
5393 }
5394 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005395}
5396
5397bool PeerConnection::GetSslRole(const std::string& content_name,
5398 rtc::SSLRole* role) {
5399 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005400 RTC_LOG(LS_INFO)
5401 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005402 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005403 return false;
5404 }
5405
Zhi Huange830e682018-03-30 10:48:35 -07005406 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5407 if (dtls_role) {
5408 *role = *dtls_role;
5409 return true;
5410 }
5411 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005412}
5413
Steve Antonf8470812017-12-04 10:46:21 -08005414void PeerConnection::SetSessionError(SessionError error,
5415 const std::string& error_desc) {
5416 RTC_DCHECK_RUN_ON(signaling_thread());
5417 if (error != session_error_) {
5418 session_error_ = error;
5419 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005420 }
5421}
5422
Zhi Huange830e682018-03-30 10:48:35 -07005423RTCError PeerConnection::UpdateSessionState(
5424 SdpType type,
5425 cricket::ContentSource source,
5426 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005427 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005428
5429 // If there's already a pending error then no state transition should happen.
5430 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005431 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005432
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005433 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005434 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005435 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005436 }
5437
5438 // Update the signaling state according to the specified state machine (see
5439 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005440 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005441 ChangeSignalingState(source == cricket::CS_LOCAL
5442 ? PeerConnectionInterface::kHaveLocalOffer
5443 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005444 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005445 ChangeSignalingState(source == cricket::CS_LOCAL
5446 ? PeerConnectionInterface::kHaveLocalPrAnswer
5447 : PeerConnectionInterface::kHaveRemotePrAnswer);
5448 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005449 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005450 ChangeSignalingState(PeerConnectionInterface::kStable);
5451 }
5452
5453 // Update internal objects according to the session description's media
5454 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005455 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005456 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005457 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005458 }
5459
Steve Anton8a006912017-12-04 15:25:56 -08005460 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005461}
5462
Steve Anton8a006912017-12-04 15:25:56 -08005463RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005464 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005465 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005466 const SessionDescriptionInterface* sdesc =
5467 (source == cricket::CS_LOCAL ? local_description()
5468 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005469 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005470
5471 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005472 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005473 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005474 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005475 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005476 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005477 continue;
5478 }
5479 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005480 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005481 if (!content_desc) {
5482 continue;
5483 }
5484 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005485 bool success = (source == cricket::CS_LOCAL)
5486 ? channel->SetLocalContent(content_desc, type, &error)
5487 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005488 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005489 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005490 }
5491 }
5492
5493 // If using the RtpDataChannel, push down the new SDP section for it too.
5494 if (rtp_data_channel_) {
5495 const ContentInfo* data_content =
5496 cricket::GetFirstDataContent(sdesc->description());
5497 if (data_content && !data_content->rejected) {
5498 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005499 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005500 if (data_desc) {
5501 std::string error;
5502 bool success =
5503 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005504 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005505 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005506 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005507 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005508 }
Steve Anton75737c02017-11-06 10:37:17 -08005509 }
5510 }
5511 }
Steve Antoned10bd92017-12-05 10:52:59 -08005512
Steve Anton75737c02017-11-06 10:37:17 -08005513 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5514 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5515 if (sctp_transport_ && local_description() && remote_description() &&
5516 cricket::GetFirstDataContent(local_description()->description()) &&
5517 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005518 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005519 RTC_FROM_HERE,
5520 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005521 if (!success) {
5522 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5523 "Failed to push down SCTP parameters.");
5524 }
Steve Anton75737c02017-11-06 10:37:17 -08005525 }
Steve Antoned10bd92017-12-05 10:52:59 -08005526
Steve Anton8a006912017-12-04 15:25:56 -08005527 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005528}
5529
5530bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5531 RTC_DCHECK(network_thread()->IsCurrent());
5532 RTC_DCHECK(local_description());
5533 RTC_DCHECK(remote_description());
5534 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5535 // When we support "max-message-size", that would also be pushed down here.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005536 return cricket_sctp_transport()->Start(
Steve Anton75737c02017-11-06 10:37:17 -08005537 GetSctpPort(local_description()->description()),
5538 GetSctpPort(remote_description()->description()));
5539}
5540
Steve Anton8a006912017-12-04 15:25:56 -08005541RTCError PeerConnection::PushdownTransportDescription(
5542 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005543 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005544 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005545
Zhi Huange830e682018-03-30 10:48:35 -07005546 if (source == cricket::CS_LOCAL) {
5547 const SessionDescriptionInterface* sdesc = local_description();
5548 RTC_DCHECK(sdesc);
5549 return transport_controller_->SetLocalDescription(type,
5550 sdesc->description());
5551 } else {
5552 const SessionDescriptionInterface* sdesc = remote_description();
5553 RTC_DCHECK(sdesc);
5554 return transport_controller_->SetRemoteDescription(type,
5555 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005556 }
Steve Anton75737c02017-11-06 10:37:17 -08005557}
5558
5559bool PeerConnection::GetTransportDescription(
5560 const SessionDescription* description,
5561 const std::string& content_name,
5562 cricket::TransportDescription* tdesc) {
5563 if (!description || !tdesc) {
5564 return false;
5565 }
5566 const TransportInfo* transport_info =
5567 description->GetTransportInfoByName(content_name);
5568 if (!transport_info) {
5569 return false;
5570 }
5571 *tdesc = transport_info->description;
5572 return true;
5573}
5574
Steve Anton75737c02017-11-06 10:37:17 -08005575cricket::IceConfig PeerConnection::ParseIceConfig(
5576 const PeerConnectionInterface::RTCConfiguration& config) const {
5577 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005578 switch (config.continual_gathering_policy) {
5579 case PeerConnectionInterface::GATHER_ONCE:
5580 gathering_policy = cricket::GATHER_ONCE;
5581 break;
5582 case PeerConnectionInterface::GATHER_CONTINUALLY:
5583 gathering_policy = cricket::GATHER_CONTINUALLY;
5584 break;
5585 default:
5586 RTC_NOTREACHED();
5587 gathering_policy = cricket::GATHER_ONCE;
5588 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005589
Steve Anton75737c02017-11-06 10:37:17 -08005590 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005591 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5592 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005593 ice_config.prioritize_most_likely_candidate_pairs =
5594 config.prioritize_most_likely_ice_candidate_pairs;
5595 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005596 RTCConfigurationToIceConfigOptionalInt(
5597 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005598 ice_config.continual_gathering_policy = gathering_policy;
5599 ice_config.presume_writable_when_fully_relayed =
5600 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005601 ice_config.ice_check_interval_strong_connectivity =
5602 config.ice_check_interval_strong_connectivity;
5603 ice_config.ice_check_interval_weak_connectivity =
5604 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005605 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005606 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5607 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005608 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005609 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005610 ice_config.regather_all_networks_interval_range =
5611 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005612 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005613 return ice_config;
5614}
5615
Steve Antona41959e2018-11-28 11:15:33 -08005616static absl::string_view GetTrackIdBySsrc(
5617 const SessionDescriptionInterface* session_description,
5618 uint32_t ssrc) {
5619 if (!session_description) {
5620 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005621 }
Steve Antona41959e2018-11-28 11:15:33 -08005622 for (const cricket::ContentInfo& content :
5623 session_description->description()->contents()) {
5624 const cricket::MediaContentDescription& media =
5625 *content.media_description();
5626 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5627 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5628 const cricket::StreamParams* stream_params =
5629 cricket::GetStreamBySsrc(media.streams(), ssrc);
5630 if (stream_params) {
5631 return stream_params->id;
5632 }
5633 }
5634 }
5635 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005636}
5637
Steve Antona41959e2018-11-28 11:15:33 -08005638absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5639 return GetTrackIdBySsrc(local_description(), ssrc);
5640}
5641
5642absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5643 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005644}
5645
5646bool PeerConnection::SendData(const cricket::SendDataParams& params,
5647 const rtc::CopyOnWriteBuffer& payload,
5648 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005649 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5650 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5651 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005652 return false;
5653 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005654 if (media_transport_) {
5655 SendDataParams send_params;
5656 send_params.type = ToWebrtcDataMessageType(params.type);
5657 send_params.ordered = params.ordered;
5658 if (params.max_rtx_count >= 0) {
5659 send_params.max_rtx_count = params.max_rtx_count;
5660 } else if (params.max_rtx_ms >= 0) {
5661 send_params.max_rtx_ms = params.max_rtx_ms;
5662 }
5663 return media_transport_->SendData(params.sid, send_params, payload).ok();
5664 }
Steve Anton75737c02017-11-06 10:37:17 -08005665 return rtp_data_channel_
5666 ? rtp_data_channel_->SendData(params, payload, result)
5667 : network_thread()->Invoke<bool>(
5668 RTC_FROM_HERE,
5669 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005670 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005671}
5672
5673bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005674 RTC_DCHECK_RUN_ON(signaling_thread());
5675 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005676 // Don't log an error here, because DataChannels are expected to call
5677 // ConnectDataChannel in this state. It's the only way to initially tell
5678 // whether or not the underlying transport is ready.
5679 return false;
5680 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005681 if (media_transport_) {
5682 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5683 &DataChannel::OnChannelReady);
5684 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5685 &DataChannel::OnDataReceived);
5686 SignalMediaTransportChannelClosing_s.connect(
5687 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5688 SignalMediaTransportChannelClosed_s.connect(
5689 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5690 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005691 rtp_data_channel_->SignalReadyToSendData.connect(
5692 webrtc_data_channel, &DataChannel::OnChannelReady);
5693 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5694 &DataChannel::OnDataReceived);
5695 } else {
5696 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5697 &DataChannel::OnChannelReady);
5698 SignalSctpDataReceived.connect(webrtc_data_channel,
5699 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005700 SignalSctpClosingProcedureStartedRemotely.connect(
5701 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5702 SignalSctpClosingProcedureComplete.connect(
5703 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005704 }
5705 return true;
5706}
5707
5708void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005709 RTC_DCHECK_RUN_ON(signaling_thread());
5710 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005711 RTC_LOG(LS_ERROR)
5712 << "DisconnectDataChannel called when rtp_data_channel_ and "
5713 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005714 return;
5715 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005716 if (media_transport_) {
5717 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5718 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5719 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5720 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5721 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005722 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5723 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5724 } else {
5725 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5726 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005727 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5728 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005729 }
5730}
5731
5732void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005733 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005734 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005735 return;
5736 }
Steve Anton75737c02017-11-06 10:37:17 -08005737 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005738 RTC_LOG(LS_ERROR)
5739 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005740 return;
5741 }
5742 network_thread()->Invoke<void>(
5743 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005744 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005745}
5746
5747void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005748 if (media_transport_) {
5749 media_transport_->CloseChannel(sid);
5750 return;
5751 }
Steve Anton75737c02017-11-06 10:37:17 -08005752 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005753 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005754 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005755 return;
5756 }
5757 network_thread()->Invoke<void>(
5758 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005759 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005760}
5761
5762bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005763 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005764 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005765 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005766 sctp_ready_to_send_data_;
5767}
5768
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005769void PeerConnection::OnDataReceived(int channel_id,
5770 DataMessageType type,
5771 const rtc::CopyOnWriteBuffer& buffer) {
5772 cricket::ReceiveDataParams params;
5773 params.sid = channel_id;
5774 params.type = ToCricketDataMessageType(type);
5775 media_transport_invoker_->AsyncInvoke<void>(
5776 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5777 RTC_DCHECK_RUN_ON(signaling_thread());
5778 if (!HandleOpenMessage_s(params, buffer)) {
5779 SignalMediaTransportReceivedData_s(params, buffer);
5780 }
5781 });
5782}
5783
5784void PeerConnection::OnChannelClosing(int channel_id) {
5785 media_transport_invoker_->AsyncInvoke<void>(
5786 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5787 RTC_DCHECK_RUN_ON(signaling_thread());
5788 SignalMediaTransportChannelClosing_s(channel_id);
5789 });
5790}
5791
5792void PeerConnection::OnChannelClosed(int channel_id) {
5793 media_transport_invoker_->AsyncInvoke<void>(
5794 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5795 RTC_DCHECK_RUN_ON(signaling_thread());
5796 SignalMediaTransportChannelClosed_s(channel_id);
5797 });
5798}
5799
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005800absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005801 if (sctp_mid_ && transport_controller_) {
5802 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5803 if (dtls_transport) {
5804 return dtls_transport->transport_name();
5805 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005806 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005807 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005808 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005809}
5810
Qingsi Wang72a43a12018-02-20 16:03:18 -08005811cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5812 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005813 network_thread()->Invoke<void>(
5814 RTC_FROM_HERE,
5815 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5816 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005817 return candidate_states_list;
5818}
5819
Steve Anton5dfde182018-02-06 10:34:40 -08005820std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5821 const {
5822 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005823 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005824 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005825 if (channel) {
5826 transport_names_by_mid[channel->content_name()] =
5827 channel->transport_name();
5828 }
Steve Anton75737c02017-11-06 10:37:17 -08005829 }
Steve Anton5dfde182018-02-06 10:34:40 -08005830 if (rtp_data_channel_) {
5831 transport_names_by_mid[rtp_data_channel_->content_name()] =
5832 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005833 }
5834 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005835 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005836 RTC_DCHECK(transport_name);
5837 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005838 }
Steve Anton5dfde182018-02-06 10:34:40 -08005839 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005840}
5841
Steve Anton5dfde182018-02-06 10:34:40 -08005842std::map<std::string, cricket::TransportStats>
5843PeerConnection::GetTransportStatsByNames(
5844 const std::set<std::string>& transport_names) {
5845 if (!network_thread()->IsCurrent()) {
5846 return network_thread()
5847 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5848 RTC_FROM_HERE,
5849 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005850 }
Steve Anton5dfde182018-02-06 10:34:40 -08005851 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5852 for (const std::string& transport_name : transport_names) {
5853 cricket::TransportStats transport_stats;
5854 bool success =
5855 transport_controller_->GetStats(transport_name, &transport_stats);
5856 if (success) {
5857 transport_stats_by_name[transport_name] = std::move(transport_stats);
5858 } else {
5859 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5860 << transport_name;
5861 }
5862 }
5863 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005864}
5865
5866bool PeerConnection::GetLocalCertificate(
5867 const std::string& transport_name,
5868 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005869 if (!certificate) {
5870 return false;
5871 }
5872 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5873 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005874}
5875
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005876std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005877 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005878 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005879}
5880
5881cricket::DataChannelType PeerConnection::data_channel_type() const {
5882 return data_channel_type_;
5883}
5884
5885bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5886 return pending_ice_restarts_.find(content_name) !=
5887 pending_ice_restarts_.end();
5888}
5889
Steve Anton75737c02017-11-06 10:37:17 -08005890bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5891 return transport_controller_->NeedsIceRestart(content_name);
5892}
5893
5894void PeerConnection::OnCertificateReady(
5895 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5896 transport_controller_->SetLocalCertificate(certificate);
5897}
5898
5899void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005900 SetSessionError(SessionError::kTransport,
5901 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005902}
5903
Alex Loiko9289eda2018-11-23 16:18:59 +00005904void PeerConnection::OnTransportControllerConnectionState(
5905 cricket::IceConnectionState state) {
5906 switch (state) {
5907 case cricket::kIceConnectionConnecting:
5908 // If the current state is Connected or Completed, then there were
5909 // writable channels but now there are not, so the next state must
5910 // be Disconnected.
5911 // kIceConnectionConnecting is currently used as the default,
5912 // un-connected state by the TransportController, so its only use is
5913 // detecting disconnections.
5914 if (ice_connection_state_ ==
5915 PeerConnectionInterface::kIceConnectionConnected ||
5916 ice_connection_state_ ==
5917 PeerConnectionInterface::kIceConnectionCompleted) {
5918 SetIceConnectionState(
5919 PeerConnectionInterface::kIceConnectionDisconnected);
5920 }
5921 break;
5922 case cricket::kIceConnectionFailed:
5923 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5924 break;
5925 case cricket::kIceConnectionConnected:
5926 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5927 "all transports are writable.";
5928 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5929 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5930 break;
5931 case cricket::kIceConnectionCompleted:
5932 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5933 "all transports are complete.";
5934 if (ice_connection_state_ !=
5935 PeerConnectionInterface::kIceConnectionConnected) {
5936 // If jumping directly from "checking" to "connected",
5937 // signal "connected" first.
5938 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5939 }
5940 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5941 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5942 ReportTransportStats();
5943 break;
5944 default:
5945 RTC_NOTREACHED();
5946 }
5947}
5948
Steve Anton75737c02017-11-06 10:37:17 -08005949void PeerConnection::OnTransportControllerCandidatesGathered(
5950 const std::string& transport_name,
5951 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005952 int sdp_mline_index;
5953 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005954 RTC_LOG(LS_ERROR)
5955 << "OnTransportControllerCandidatesGathered: content name "
5956 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005957 return;
5958 }
5959
5960 for (cricket::Candidates::const_iterator citer = candidates.begin();
5961 citer != candidates.end(); ++citer) {
5962 // Use transport_name as the candidate media id.
5963 std::unique_ptr<JsepIceCandidate> candidate(
5964 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5965 if (local_description()) {
5966 mutable_local_description()->AddCandidate(candidate.get());
5967 }
5968 OnIceCandidate(std::move(candidate));
5969 }
5970}
5971
5972void PeerConnection::OnTransportControllerCandidatesRemoved(
5973 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005974 // Sanity check.
5975 for (const cricket::Candidate& candidate : candidates) {
5976 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005977 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005978 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005979 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005980 return;
5981 }
5982 }
5983
5984 if (local_description()) {
5985 mutable_local_description()->RemoveCandidates(candidates);
5986 }
5987 OnIceCandidatesRemoved(candidates);
5988}
5989
5990void PeerConnection::OnTransportControllerDtlsHandshakeError(
5991 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005992 RTC_HISTOGRAM_ENUMERATION(
5993 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5994 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005995}
5996
Steve Antoned10bd92017-12-05 10:52:59 -08005997void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005998 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005999 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006000 if (channel && !channel->enabled()) {
6001 channel->Enable(true);
6002 }
Steve Anton75737c02017-11-06 10:37:17 -08006003 }
6004
Steve Anton4171afb2017-11-20 10:20:22 -08006005 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006006 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006007 }
Steve Anton75737c02017-11-06 10:37:17 -08006008}
6009
6010// Returns the media index for a local ice candidate given the content name.
6011bool PeerConnection::GetLocalCandidateMediaIndex(
6012 const std::string& content_name,
6013 int* sdp_mline_index) {
6014 if (!local_description() || !sdp_mline_index) {
6015 return false;
6016 }
6017
6018 bool content_found = false;
6019 const ContentInfos& contents = local_description()->description()->contents();
6020 for (size_t index = 0; index < contents.size(); ++index) {
6021 if (contents[index].name == content_name) {
6022 *sdp_mline_index = static_cast<int>(index);
6023 content_found = true;
6024 break;
6025 }
6026 }
6027 return content_found;
6028}
6029
6030bool PeerConnection::UseCandidatesInSessionDescription(
6031 const SessionDescriptionInterface* remote_desc) {
6032 if (!remote_desc) {
6033 return true;
6034 }
6035 bool ret = true;
6036
6037 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6038 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6039 for (size_t n = 0; n < candidates->count(); ++n) {
6040 const IceCandidateInterface* candidate = candidates->at(n);
6041 bool valid = false;
6042 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6043 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006044 RTC_LOG(LS_INFO)
6045 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006046 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006047 }
6048 continue;
6049 }
6050 ret = UseCandidate(candidate);
6051 if (!ret) {
6052 break;
6053 }
6054 }
6055 }
6056 return ret;
6057}
6058
6059bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6060 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6061 size_t remote_content_size =
6062 remote_description()->description()->contents().size();
6063 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006064 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006065 return false;
6066 }
6067
6068 cricket::ContentInfo content =
6069 remote_description()->description()->contents()[mediacontent_index];
6070 std::vector<cricket::Candidate> candidates;
6071 candidates.push_back(candidate->candidate());
6072 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006073 RTCError error =
6074 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006075 if (error.ok()) {
6076 // Candidates successfully submitted for checking.
6077 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6078 ice_connection_state_ ==
6079 PeerConnectionInterface::kIceConnectionDisconnected) {
6080 // If state is New, then the session has just gotten its first remote ICE
6081 // candidates, so go to Checking.
6082 // If state is Disconnected, the session is re-using old candidates or
6083 // receiving additional ones, so go to Checking.
6084 // If state is Connected, stay Connected.
6085 // TODO(bemasc): If state is Connected, and the new candidates are for a
6086 // newly added transport, then the state actually _should_ move to
6087 // checking. Add a way to distinguish that case.
6088 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6089 }
6090 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006091 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006092 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006093 }
6094 return true;
6095}
6096
6097void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006098 // Destroy video channel first since it may have a pointer to the
6099 // voice channel.
6100 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006101 if (!video_info || video_info->rejected) {
6102 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006103 }
6104
Steve Anton6fec8802017-12-04 10:37:29 -08006105 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6106 if (!audio_info || audio_info->rejected) {
6107 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006108 }
6109
6110 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6111 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006112 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006113 }
6114}
6115
Steve Antondcc3c022017-12-22 16:02:54 -08006116RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6117 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006118 const cricket::ContentGroup* bundle_group = nullptr;
6119 if (configuration_.bundle_policy ==
6120 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006121 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006122 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006123 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6124 "max-bundle configured but session description "
6125 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006126 }
6127 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006128 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006129}
6130
6131RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006132 // Creating the media channels. Transports should already have been created
6133 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006134 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006135 if (voice && !voice->rejected &&
6136 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006137 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006138 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006139 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6140 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006141 }
6142 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6143 }
6144
Steve Antondcc3c022017-12-22 16:02:54 -08006145 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006146 if (video && !video->rejected &&
6147 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006148 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006149 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006150 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6151 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006152 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006153 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006154 }
6155
Steve Antondcc3c022017-12-22 16:02:54 -08006156 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006157 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006158 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006159 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006160 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6161 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006162 }
6163 }
6164
Steve Anton8a006912017-12-04 15:25:56 -08006165 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006166}
6167
Steve Anton4171afb2017-11-20 10:20:22 -08006168// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006169cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006170 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006171 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006172 MediaTransportInterface* media_transport = nullptr;
6173 if (configuration_.use_media_transport) {
6174 media_transport = GetMediaTransport(mid);
6175 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006176
Steve Anton75737c02017-11-06 10:37:17 -08006177 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006178 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006179 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006180 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006181 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006182 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006183 }
Steve Anton75737c02017-11-06 10:37:17 -08006184 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6185 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006186 voice_channel->SignalSentPacket.connect(this,
6187 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006188 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006189
Steve Antoneda6ccd2017-12-04 10:21:55 -08006190 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006191}
6192
Steve Anton4171afb2017-11-20 10:20:22 -08006193// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006194cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006195 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006196 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006197 MediaTransportInterface* media_transport = nullptr;
6198 if (configuration_.use_media_transport) {
6199 media_transport = GetMediaTransport(mid);
6200 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006201
Steve Anton75737c02017-11-06 10:37:17 -08006202 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006203 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006204 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006205 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006206 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006207 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006208 }
Steve Anton75737c02017-11-06 10:37:17 -08006209 video_channel->SignalDtlsSrtpSetupFailure.connect(
6210 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006211 video_channel->SignalSentPacket.connect(this,
6212 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006213 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006214
Steve Antoneda6ccd2017-12-04 10:21:55 -08006215 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006216}
6217
Zhi Huange830e682018-03-30 10:48:35 -07006218bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006219 switch (data_channel_type_) {
6220 case cricket::DCT_MEDIA_TRANSPORT:
6221 if (network_thread()->Invoke<bool>(
6222 RTC_FROM_HERE,
6223 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6224 this, mid))) {
6225 for (const auto& channel : sctp_data_channels_) {
6226 channel->OnTransportChannelCreated();
6227 }
6228 return true;
6229 }
Steve Anton75737c02017-11-06 10:37:17 -08006230 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006231 case cricket::DCT_SCTP:
6232 if (!sctp_factory_) {
6233 RTC_LOG(LS_ERROR)
6234 << "Trying to create SCTP transport, but didn't compile with "
6235 "SCTP support (HAVE_SCTP)";
6236 return false;
6237 }
6238 if (!network_thread()->Invoke<bool>(
6239 RTC_FROM_HERE,
6240 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6241 return false;
6242 }
6243 for (const auto& channel : sctp_data_channels_) {
6244 channel->OnTransportChannelCreated();
6245 }
6246 return true;
6247 case cricket::DCT_RTP:
6248 default:
6249 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6250 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6251 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006252 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006253 if (!rtp_data_channel_) {
6254 return false;
6255 }
6256 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6257 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6258 rtp_data_channel_->SignalSentPacket.connect(
6259 this, &PeerConnection::OnSentPacket_w);
6260 rtp_data_channel_->SetRtpTransport(rtp_transport);
6261 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006262 }
6263
Steve Anton75737c02017-11-06 10:37:17 -08006264 return true;
6265}
6266
6267Call::Stats PeerConnection::GetCallStats() {
6268 if (!worker_thread()->IsCurrent()) {
6269 return worker_thread()->Invoke<Call::Stats>(
6270 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6271 }
6272 if (call_) {
6273 return call_->GetStats();
6274 } else {
6275 return Call::Stats();
6276 }
6277}
6278
Zhi Huange830e682018-03-30 10:48:35 -07006279bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006280 RTC_DCHECK(network_thread()->IsCurrent());
6281 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006282 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6283 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006284 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006285 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006286 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006287 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6288 sctp_factory_->CreateSctpTransport(dtls_transport);
6289 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006290 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006291 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006292 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006293 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006294 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006295 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6296 // another thread. Would be nice if there was a helper class similar to
6297 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6298 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006299 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006300 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006301 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006302 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006303 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006304 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6305 std::move(cricket_sctp_transport));
6306 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006307 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006308}
6309
6310void PeerConnection::DestroySctpTransport_n() {
6311 RTC_DCHECK(network_thread()->IsCurrent());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006312 sctp_transport_->Clear();
6313 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006314 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006315 sctp_invoker_.reset(nullptr);
6316 sctp_ready_to_send_data_ = false;
6317}
6318
6319void PeerConnection::OnSctpTransportReadyToSendData_n() {
6320 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6321 RTC_DCHECK(network_thread()->IsCurrent());
6322 // Note: Cannot use rtc::Bind here because it will grab a reference to
6323 // PeerConnection and potentially cause PeerConnection to live longer than
6324 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6325 // be destroyed before PeerConnection is destroyed, and at that point all
6326 // pending tasks will be cleared.
6327 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6328 OnSctpTransportReadyToSendData_s(true);
6329 });
6330}
6331
6332void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6333 RTC_DCHECK(signaling_thread()->IsCurrent());
6334 sctp_ready_to_send_data_ = ready;
6335 SignalSctpReadyToSendData(ready);
6336}
6337
6338void PeerConnection::OnSctpTransportDataReceived_n(
6339 const cricket::ReceiveDataParams& params,
6340 const rtc::CopyOnWriteBuffer& payload) {
6341 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6342 RTC_DCHECK(network_thread()->IsCurrent());
6343 // Note: Cannot use rtc::Bind here because it will grab a reference to
6344 // PeerConnection and potentially cause PeerConnection to live longer than
6345 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6346 // be destroyed before PeerConnection is destroyed, and at that point all
6347 // pending tasks will be cleared.
6348 sctp_invoker_->AsyncInvoke<void>(
6349 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6350 OnSctpTransportDataReceived_s(params, payload);
6351 });
6352}
6353
6354void PeerConnection::OnSctpTransportDataReceived_s(
6355 const cricket::ReceiveDataParams& params,
6356 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006357 RTC_DCHECK_RUN_ON(signaling_thread());
6358 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006359 SignalSctpDataReceived(params, payload);
6360 }
6361}
6362
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006363void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006364 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6365 RTC_DCHECK(network_thread()->IsCurrent());
6366 sctp_invoker_->AsyncInvoke<void>(
6367 RTC_FROM_HERE, signaling_thread(),
6368 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006369 &SignalSctpClosingProcedureStartedRemotely, sid));
6370}
6371
6372void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6373 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6374 RTC_DCHECK(network_thread()->IsCurrent());
6375 sctp_invoker_->AsyncInvoke<void>(
6376 RTC_FROM_HERE, signaling_thread(),
6377 rtc::Bind(&sigslot::signal1<int>::operator(),
6378 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006379}
6380
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006381bool PeerConnection::SetupMediaTransportForDataChannels_n(
6382 const std::string& mid) {
6383 media_transport_ = transport_controller_->GetMediaTransport(mid);
6384 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006385 RTC_LOG(LS_ERROR)
6386 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006387 return false;
6388 }
6389
6390 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6391 media_transport_->SetDataSink(this);
6392 media_transport_data_mid_ = mid;
6393 transport_controller_->SignalMediaTransportStateChanged.connect(
6394 this, &PeerConnection::OnMediaTransportStateChanged_n);
6395 // Check the initial state right away, in case transport is already writable.
6396 OnMediaTransportStateChanged_n();
6397 return true;
6398}
6399
6400void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6401 if (!media_transport_) {
6402 return;
6403 }
6404 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6405 media_transport_data_mid_.reset();
6406 media_transport_->SetDataSink(nullptr);
6407 media_transport_invoker_ = nullptr;
6408 media_transport_ = nullptr;
6409}
6410
6411void PeerConnection::OnMediaTransportStateChanged_n() {
6412 if (!media_transport_data_mid_ ||
6413 transport_controller_->GetMediaTransportState(
6414 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6415 return;
6416 }
6417 media_transport_invoker_->AsyncInvoke<void>(
6418 RTC_FROM_HERE, signaling_thread(), [this] {
6419 RTC_DCHECK_RUN_ON(signaling_thread());
6420 media_transport_ready_to_send_data_ = true;
6421 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6422 });
6423}
6424
Steve Anton75737c02017-11-06 10:37:17 -08006425// Returns false if bundle is enabled and rtcp_mux is disabled.
6426bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6427 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6428 if (!bundle_enabled)
6429 return true;
6430
6431 const cricket::ContentGroup* bundle_group =
6432 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6433 RTC_DCHECK(bundle_group != NULL);
6434
6435 const cricket::ContentInfos& contents = desc->contents();
6436 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6437 citer != contents.end(); ++citer) {
6438 const cricket::ContentInfo* content = (&*citer);
6439 RTC_DCHECK(content != NULL);
6440 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006441 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006442 if (!HasRtcpMuxEnabled(content))
6443 return false;
6444 }
6445 }
6446 // RTCP-MUX is enabled in all the contents.
6447 return true;
6448}
6449
6450bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006451 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006452}
6453
Steve Anton06817cd2018-12-18 15:55:30 -08006454static RTCError ValidateMids(const cricket::SessionDescription& description) {
6455 std::set<std::string> mids;
6456 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006457 if (content.name.empty()) {
6458 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6459 "A media section is missing a MID attribute.");
6460 }
Steve Anton06817cd2018-12-18 15:55:30 -08006461 if (!mids.insert(content.name).second) {
6462 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6463 "Duplicate a=mid value '" + content.name + "'.");
6464 }
6465 }
6466 return RTCError::OK();
6467}
6468
Steve Anton8a006912017-12-04 15:25:56 -08006469RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006470 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006471 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006472 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006473 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006474 }
6475
6476 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006477 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006478 }
6479
Steve Anton3828c062017-12-06 10:34:51 -08006480 SdpType type = sdesc->GetType();
6481 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6482 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006483 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006484 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006485 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006486 }
6487
Steve Anton06817cd2018-12-18 15:55:30 -08006488 RTCError error = ValidateMids(*sdesc->description());
6489 if (!error.ok()) {
6490 return error;
6491 }
6492
Steve Anton75737c02017-11-06 10:37:17 -08006493 // Verify crypto settings.
6494 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006495 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6496 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006497 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006498 if (!crypto_error.ok()) {
6499 return crypto_error;
6500 }
Steve Anton75737c02017-11-06 10:37:17 -08006501 }
6502
6503 // Verify ice-ufrag and ice-pwd.
6504 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6506 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006507 }
6508
6509 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6511 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006512 }
6513
6514 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6515 // m-lines that do not rtcp-mux enabled.
6516
6517 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006518 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006519 // With an answer we want to compare the new answer session description with
6520 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006521 const cricket::SessionDescription* offer_desc =
6522 (source == cricket::CS_LOCAL) ? remote_description()->description()
6523 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006524 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6525 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6526 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006527 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6528 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006529 }
6530 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006531 // The re-offers should respect the order of m= sections in current
6532 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006533 // With a re-offer, either the current local or current remote descriptions
6534 // could be the most up to date, so we would like to check against both of
6535 // them if they exist. It could be the case that one of them has a 0 port
6536 // for a media section, but the other does not. This is important to check
6537 // against in the case that we are recycling an m= section.
6538 const cricket::SessionDescription* current_desc = nullptr;
6539 const cricket::SessionDescription* secondary_current_desc = nullptr;
6540 if (local_description()) {
6541 current_desc = local_description()->description();
6542 if (remote_description()) {
6543 secondary_current_desc = remote_description()->description();
6544 }
6545 } else if (remote_description()) {
6546 current_desc = remote_description()->description();
6547 }
Steve Anton75737c02017-11-06 10:37:17 -08006548 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006549 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6550 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006551 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6552 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006553 }
6554 }
6555
Steve Antonba42e992018-04-09 14:10:01 -07006556 if (IsUnifiedPlan()) {
6557 // Ensure that each audio and video media section has at most one
6558 // "StreamParams". This will return an error if receiving a session
6559 // description from a "Plan B" endpoint which adds multiple tracks of the
6560 // same type. With Unified Plan, there can only be at most one track per
6561 // media section.
6562 for (const ContentInfo& content : sdesc->description()->contents()) {
6563 const MediaContentDescription& desc = *content.description;
6564 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6565 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6566 desc.streams().size() > 1u) {
6567 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6568 "Media section has more than one track specified "
6569 "with a=ssrc lines which is not supported with "
6570 "Unified Plan.");
6571 }
6572 }
6573 }
6574
Steve Anton8a006912017-12-04 15:25:56 -08006575 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006576}
6577
Steve Anton3828c062017-12-06 10:34:51 -08006578bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006579 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006580 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006581 return (state == PeerConnectionInterface::kStable) ||
6582 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006583 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006584 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006585 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6586 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6587 }
6588}
6589
Steve Anton3828c062017-12-06 10:34:51 -08006590bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006591 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006592 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006593 return (state == PeerConnectionInterface::kStable) ||
6594 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006595 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006596 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006597 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6598 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6599 }
6600}
6601
Steve Antonf8470812017-12-04 10:46:21 -08006602const char* PeerConnection::SessionErrorToString(SessionError error) const {
6603 switch (error) {
6604 case SessionError::kNone:
6605 return "ERROR_NONE";
6606 case SessionError::kContent:
6607 return "ERROR_CONTENT";
6608 case SessionError::kTransport:
6609 return "ERROR_TRANSPORT";
6610 }
6611 RTC_NOTREACHED();
6612 return "";
6613}
6614
Steve Anton75737c02017-11-06 10:37:17 -08006615std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006616 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006617 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6618 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006619 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006620}
6621
Steve Anton8e20f172018-03-06 10:55:04 -08006622void PeerConnection::ReportSdpFormatReceived(
6623 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006624 int num_audio_mlines = 0;
6625 int num_video_mlines = 0;
6626 int num_audio_tracks = 0;
6627 int num_video_tracks = 0;
6628 for (const ContentInfo& content : remote_offer.description()->contents()) {
6629 cricket::MediaType media_type = content.media_description()->type();
6630 int num_tracks = std::max(
6631 1, static_cast<int>(content.media_description()->streams().size()));
6632 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6633 num_audio_mlines += 1;
6634 num_audio_tracks += num_tracks;
6635 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6636 num_video_mlines += 1;
6637 num_video_tracks += num_tracks;
6638 }
6639 }
6640 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6641 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6642 format = kSdpFormatReceivedComplexUnifiedPlan;
6643 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6644 format = kSdpFormatReceivedComplexPlanB;
6645 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6646 format = kSdpFormatReceivedSimple;
6647 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006648 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6649 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006650}
6651
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006652void PeerConnection::NoteUsageEvent(UsageEvent event) {
6653 RTC_DCHECK_RUN_ON(signaling_thread());
6654 usage_event_accumulator_ |= static_cast<int>(event);
6655}
6656
6657void PeerConnection::ReportUsagePattern() const {
6658 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006659 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6660 usage_event_accumulator_,
6661 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006662 const int bad_bits =
6663 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6664 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6665 const int good_bits =
6666 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6667 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6668 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6669 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6670 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006671 // If called after close(), we can't report, because observer may have
6672 // been deallocated, and therefore pointer is null. Write to log instead.
6673 if (observer_) {
6674 Observer()->OnInterestingUsage(usage_event_accumulator_);
6675 } else {
6676 RTC_LOG(LS_INFO) << "Interesting usage signature "
6677 << usage_event_accumulator_
6678 << " observed after observer shutdown";
6679 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006680 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006681}
6682
Steve Anton0ffaaa22018-02-23 10:31:30 -08006683void PeerConnection::ReportNegotiatedSdpSemantics(
6684 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006685 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006686 switch (answer.description()->msid_signaling()) {
6687 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006688 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006689 break;
6690 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006691 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006692 break;
6693 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006694 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006695 break;
6696 case cricket::kMsidSignalingMediaSection |
6697 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006698 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006699 break;
6700 default:
6701 RTC_NOTREACHED();
6702 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006703 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6704 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006705}
6706
Steve Anton75737c02017-11-06 10:37:17 -08006707// We need to check the local/remote description for the Transport instead of
6708// the session, because a new Transport added during renegotiation may have
6709// them unset while the session has them set from the previous negotiation.
6710// Not doing so may trigger the auto generation of transport description and
6711// mess up DTLS identity information, ICE credential, etc.
6712bool PeerConnection::ReadyToUseRemoteCandidate(
6713 const IceCandidateInterface* candidate,
6714 const SessionDescriptionInterface* remote_desc,
6715 bool* valid) {
6716 *valid = true;
6717
6718 const SessionDescriptionInterface* current_remote_desc =
6719 remote_desc ? remote_desc : remote_description();
6720
6721 if (!current_remote_desc) {
6722 return false;
6723 }
6724
6725 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6726 size_t remote_content_size =
6727 current_remote_desc->description()->contents().size();
6728 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006729 RTC_LOG(LS_ERROR)
6730 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6731 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006732
6733 *valid = false;
6734 return false;
6735 }
6736
6737 cricket::ContentInfo content =
6738 current_remote_desc->description()->contents()[mediacontent_index];
6739
6740 const std::string transport_name = GetTransportName(content.name);
6741 if (transport_name.empty()) {
6742 return false;
6743 }
Zhi Huange830e682018-03-30 10:48:35 -07006744 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006745}
6746
6747bool PeerConnection::SrtpRequired() const {
6748 return dtls_enabled_ ||
6749 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6750}
6751
6752void PeerConnection::OnTransportControllerGatheringState(
6753 cricket::IceGatheringState state) {
6754 RTC_DCHECK(signaling_thread()->IsCurrent());
6755 if (state == cricket::kIceGatheringGathering) {
6756 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6757 } else if (state == cricket::kIceGatheringComplete) {
6758 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6759 }
6760}
6761
6762void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006763 std::map<std::string, std::set<cricket::MediaType>>
6764 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006765 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006766 if (transceiver->internal()->channel()) {
6767 const std::string& transport_name =
6768 transceiver->internal()->channel()->transport_name();
6769 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006770 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006771 }
Steve Anton75737c02017-11-06 10:37:17 -08006772 }
6773 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006774 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6775 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006776 }
Zhi Huange830e682018-03-30 10:48:35 -07006777
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006778 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006779 if (transport_name) {
6780 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006781 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006782 }
Zhi Huange830e682018-03-30 10:48:35 -07006783
Steve Antonc7b964c2018-02-01 14:39:45 -08006784 for (const auto& entry : media_types_by_transport_name) {
6785 const std::string& transport_name = entry.first;
6786 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006787 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006788 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006789 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006790 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006791 }
6792 }
6793}
6794// Walk through the ConnectionInfos to gather best connection usage
6795// for IPv4 and IPv6.
6796void PeerConnection::ReportBestConnectionState(
6797 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006798 for (const cricket::TransportChannelStats& channel_stats :
6799 stats.channel_stats) {
6800 for (const cricket::ConnectionInfo& connection_info :
6801 channel_stats.connection_infos) {
6802 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006803 continue;
6804 }
6805
Steve Antonc7b964c2018-02-01 14:39:45 -08006806 const cricket::Candidate& local = connection_info.local_candidate;
6807 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006808
6809 // Increment the counter for IceCandidatePairType.
6810 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6811 (local.type() == RELAY_PORT_TYPE &&
6812 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006813 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6814 GetIceCandidatePairCounter(local, remote),
6815 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006816 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006817 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6818 GetIceCandidatePairCounter(local, remote),
6819 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006820 } else {
6821 RTC_CHECK(0);
6822 }
Steve Anton75737c02017-11-06 10:37:17 -08006823
6824 // Increment the counter for IP type.
6825 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006826 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6827 kBestConnections_IPv4,
6828 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006829 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006830 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6831 kBestConnections_IPv6,
6832 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006833 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006834 RTC_CHECK(!local.address().hostname().empty() &&
6835 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006836 }
6837
6838 return;
6839 }
6840 }
6841}
6842
6843void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006844 const cricket::TransportStats& stats,
6845 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006846 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6847 return;
6848 }
6849
6850 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6851 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6852 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6853 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6854 return;
6855 }
6856
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006857 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6858 for (cricket::MediaType media_type : media_types) {
6859 switch (media_type) {
6860 case cricket::MEDIA_TYPE_AUDIO:
6861 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6862 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6863 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6864 break;
6865 case cricket::MEDIA_TYPE_VIDEO:
6866 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6867 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6868 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6869 break;
6870 case cricket::MEDIA_TYPE_DATA:
6871 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6872 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6873 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6874 break;
6875 default:
6876 RTC_NOTREACHED();
6877 continue;
6878 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006879 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006880 }
6881
6882 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6883 for (cricket::MediaType media_type : media_types) {
6884 switch (media_type) {
6885 case cricket::MEDIA_TYPE_AUDIO:
6886 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6887 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6888 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6889 break;
6890 case cricket::MEDIA_TYPE_VIDEO:
6891 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6892 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6893 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6894 break;
6895 case cricket::MEDIA_TYPE_DATA:
6896 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6897 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6898 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6899 break;
6900 default:
6901 RTC_NOTREACHED();
6902 continue;
6903 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006904 }
Steve Anton75737c02017-11-06 10:37:17 -08006905 }
6906}
6907
6908void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6909 RTC_DCHECK(worker_thread()->IsCurrent());
6910 RTC_DCHECK(call_);
6911 call_->OnSentPacket(sent_packet);
6912}
6913
6914const std::string PeerConnection::GetTransportName(
6915 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006916 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006917 if (channel) {
6918 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006919 }
Steve Anton6fec8802017-12-04 10:37:29 -08006920 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006921 RTC_DCHECK(sctp_mid_);
6922 if (content_name == *sctp_mid_) {
6923 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006924 }
6925 }
6926 // Return an empty string if failed to retrieve the transport name.
6927 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006928}
6929
Steve Anton6fec8802017-12-04 10:37:29 -08006930void PeerConnection::DestroyTransceiverChannel(
6931 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6932 transceiver) {
6933 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006934
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006935 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006936 if (channel) {
6937 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006938 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006939 }
6940}
6941
6942void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006943 if (rtp_data_channel_) {
6944 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006945 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006946 rtp_data_channel_ = nullptr;
6947 }
6948
6949 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6950 // grab a reference to this PeerConnection. If this is called from the
6951 // PeerConnection destructor, the RefCountedObject vtable will have already
6952 // been destroyed (since it is a subclass of PeerConnection) and using
6953 // rtc::Bind will cause "Pure virtual function called" error to appear.
6954
6955 if (sctp_transport_) {
6956 OnDataChannelDestroyed();
6957 network_thread()->Invoke<void>(RTC_FROM_HERE,
6958 [this] { DestroySctpTransport_n(); });
6959 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006960
6961 if (media_transport_) {
6962 OnDataChannelDestroyed();
6963 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6964 RTC_DCHECK_RUN_ON(network_thread());
6965 TeardownMediaTransportForDataChannels_n();
6966 });
6967 }
Steve Anton6fec8802017-12-04 10:37:29 -08006968}
6969
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006970void PeerConnection::DestroyChannelInterface(
6971 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006972 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006973 switch (channel->media_type()) {
6974 case cricket::MEDIA_TYPE_AUDIO:
6975 channel_manager()->DestroyVoiceChannel(
6976 static_cast<cricket::VoiceChannel*>(channel));
6977 break;
6978 case cricket::MEDIA_TYPE_VIDEO:
6979 channel_manager()->DestroyVideoChannel(
6980 static_cast<cricket::VideoChannel*>(channel));
6981 break;
6982 case cricket::MEDIA_TYPE_DATA:
6983 channel_manager()->DestroyRtpDataChannel(
6984 static_cast<cricket::RtpDataChannel*>(channel));
6985 break;
6986 default:
6987 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6988 break;
6989 }
Zhi Huange830e682018-03-30 10:48:35 -07006990}
Steve Anton6fec8802017-12-04 10:37:29 -08006991
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006992bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006993 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006994 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006995 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006996 MediaTransportInterface* media_transport) {
Karl Wiberg5966c502019-02-21 23:55:09 +01006997 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006998 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006999 auto base_channel = GetChannel(mid);
7000 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007001 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007002 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007003 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007004 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007005 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007006
Karl Wiberg5966c502019-02-21 23:55:09 +01007007 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007008 // Only pass media transport to call object if media transport is used
7009 // for media (and not data channel).
7010 call_->MediaTransportChange(media_transport);
7011 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007012
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007013 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007014}
7015
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007016PeerConnectionObserver* PeerConnection::Observer() const {
7017 // In earlier production code, the pointer was not cleared on close,
7018 // which might have led to undefined behavior if the observer was not
7019 // deallocated, or strange crashes if it was.
7020 // We use CHECK in order to catch such behavior if it exists.
7021 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7022 RTC_CHECK(observer_);
7023 return observer_;
7024}
7025
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007026CryptoOptions PeerConnection::GetCryptoOptions() {
7027 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7028 // after it has been removed.
7029 return configuration_.crypto_options.has_value()
7030 ? *configuration_.crypto_options
7031 : factory_->options().crypto_options;
7032}
7033
Harald Alvestrand89061872018-01-02 14:08:34 +01007034void PeerConnection::ClearStatsCache() {
7035 if (stats_collector_) {
7036 stats_collector_->ClearCachedStatsReport();
7037 }
7038}
7039
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007040void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007041 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7042 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007043}
7044
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007045} // namespace webrtc