blob: fccd6df73a9233a9e8422b9d3d172918349d90ff [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"
44#include "pc/sctp_utils.h"
45#include "pc/sdp_utils.h"
46#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010047#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/bind.h"
50#include "rtc_base/checks.h"
51#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010052#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020054#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020055#include "rtc_base/trace_event.h"
56#include "system_wrappers/include/clock.h"
57#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070058#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::ContentInfo;
61using cricket::ContentInfos;
62using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080063using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080064using cricket::RidDescription;
65using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080066using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080067using cricket::SimulcastDescription;
68using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080069using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080070using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080071using cricket::TransportInfo;
72
73using cricket::LOCAL_PORT_TYPE;
74using cricket::STUN_PORT_TYPE;
75using cricket::RELAY_PORT_TYPE;
76using cricket::PRFLX_PORT_TYPE;
77
Steve Antonba818672017-11-06 10:21:57 -080078namespace webrtc {
79
Steve Anton75737c02017-11-06 10:37:17 -080080// Error messages
81const char kBundleWithoutRtcpMux[] =
82 "rtcp-mux must be enabled when BUNDLE "
83 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kInvalidCandidates[] = "Description contains invalid candidates.";
85const char kInvalidSdp[] = "Invalid session description.";
86const char kMlineMismatchInAnswer[] =
87 "The order of m-lines in answer doesn't match order in offer. Rejecting "
88 "answer.";
89const char kMlineMismatchInSubsequentOffer[] =
90 "The order of m-lines in subsequent offer doesn't match order from "
91 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080092const char kSdpWithoutDtlsFingerprint[] =
93 "Called with SDP without DTLS fingerprint.";
94const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
95const char kSdpWithoutIceUfragPwd[] =
96 "Called with SDP without ice-ufrag and ice-pwd.";
97const char kSessionError[] = "Session error code: ";
98const char kSessionErrorDesc[] = "Session error description: ";
99const char kDtlsSrtpSetupFailureRtp[] =
100 "Couldn't set up DTLS-SRTP on RTP channel.";
101const char kDtlsSrtpSetupFailureRtcp[] =
102 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103
Steve Anton75737c02017-11-06 10:37:17 -0800104namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105
Seth Hampson845e8782018-03-02 11:34:10 -0800106static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800107static const char kDefaultAudioSenderId[] = "defaulta0";
108static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700109
zhihuang8f65cdf2016-05-06 18:40:30 -0700110// The length of RTCP CNAMEs.
111static const int kRtcpCnameLength = 16;
112
Steve Antonad182762018-09-05 20:22:40 +0000113enum {
114 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
115 MSG_SET_SESSIONDESCRIPTION_FAILED,
116 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
117 MSG_GETSTATS,
118 MSG_FREE_DATACHANNELS,
119 MSG_REPORT_USAGE_PATTERN,
120};
121
Harald Alvestrand19793842018-06-25 12:03:50 +0200122static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
123
Steve Antonad182762018-09-05 20:22:40 +0000124struct SetSessionDescriptionMsg : public rtc::MessageData {
125 explicit SetSessionDescriptionMsg(
126 webrtc::SetSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
130 RTCError error;
131};
132
133struct CreateSessionDescriptionMsg : public rtc::MessageData {
134 explicit CreateSessionDescriptionMsg(
135 webrtc::CreateSessionDescriptionObserver* observer)
136 : observer(observer) {}
137
138 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
139 RTCError error;
140};
141
142struct GetStatsMsg : public rtc::MessageData {
143 GetStatsMsg(webrtc::StatsObserver* observer,
144 webrtc::MediaStreamTrackInterface* track)
145 : observer(observer), track(track) {}
146 rtc::scoped_refptr<webrtc::StatsObserver> observer;
147 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
148};
149
deadbeefab9b2d12015-10-14 11:33:11 -0700150// Check if we can send |new_stream| on a PeerConnection.
151bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
152 webrtc::MediaStreamInterface* new_stream) {
153 if (!new_stream || !current_streams) {
154 return false;
155 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700156 if (current_streams->find(new_stream->id()) != nullptr) {
157 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100158 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700159 return false;
160 }
161 return true;
162}
163
deadbeef5e97fb52015-10-15 12:49:08 -0700164// If the direction is "recvonly" or "inactive", treat the description
165// as containing no streams.
166// See: https://code.google.com/p/webrtc/issues/detail?id=5054
167std::vector<cricket::StreamParams> GetActiveStreams(
168 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800169 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700170 ? desc->streams()
171 : std::vector<cricket::StreamParams>();
172}
173
deadbeefab9b2d12015-10-14 11:33:11 -0700174bool IsValidOfferToReceiveMedia(int value) {
175 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
176 return (value >= Options::kUndefined) &&
177 (value <= Options::kMaxOfferToReceiveMedia);
178}
179
zhihuang1c378ed2017-08-17 14:10:50 -0700180// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800181void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700182 const std::vector<rtc::scoped_refptr<
183 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700184 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200185 cricket::MediaDescriptionOptions* video_media_description_options,
186 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700187 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700188 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
189 if (audio_media_description_options) {
190 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700191 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700192 }
193 } else {
194 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
195 if (video_media_description_options) {
196 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800197 sender->id(), sender->internal()->stream_ids(), {},
198 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700199 }
200 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700201 }
zhihuang1c378ed2017-08-17 14:10:50 -0700202}
olka3c747662017-08-17 06:50:32 -0700203
zhihuang1c378ed2017-08-17 14:10:50 -0700204// Add options to |session_options| from |rtp_data_channels|.
205void AddRtpDataChannelOptions(
206 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
207 rtp_data_channels,
208 cricket::MediaDescriptionOptions* data_media_description_options) {
209 if (!data_media_description_options) {
210 return;
211 }
deadbeefab9b2d12015-10-14 11:33:11 -0700212 // Check for data channels.
213 for (const auto& kv : rtp_data_channels) {
214 const DataChannel* channel = kv.second;
215 if (channel->state() == DataChannel::kConnecting ||
216 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700217 // Legacy RTP data channels are signaled with the track/stream ID set to
218 // the data channel's label.
219 data_media_description_options->AddRtpDataChannel(channel->label(),
220 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700221 }
222 }
223}
224
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225uint32_t ConvertIceTransportTypeToCandidateFilter(
226 PeerConnectionInterface::IceTransportsType type) {
227 switch (type) {
228 case PeerConnectionInterface::kNone:
229 return cricket::CF_NONE;
230 case PeerConnectionInterface::kRelay:
231 return cricket::CF_RELAY;
232 case PeerConnectionInterface::kNoHost:
233 return (cricket::CF_ALL & ~cricket::CF_HOST);
234 case PeerConnectionInterface::kAll:
235 return cricket::CF_ALL;
236 default:
nissec80e7412017-01-11 05:56:46 -0800237 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238 }
239 return cricket::CF_NONE;
240}
241
deadbeef293e9262017-01-11 12:28:30 -0800242// Helper to set an error and return from a method.
243bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
244 if (error) {
245 error->set_type(type);
246 }
247 return type == webrtc::RTCErrorType::NONE;
248}
249
Steve Anton038834f2017-07-14 15:59:59 -0700250bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700251 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700252 if (error_out) {
253 *error_out = std::move(error);
254 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700255 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700256}
257
Steve Antonba818672017-11-06 10:21:57 -0800258std::string GetSignalingStateString(
259 PeerConnectionInterface::SignalingState state) {
260 switch (state) {
261 case PeerConnectionInterface::kStable:
262 return "kStable";
263 case PeerConnectionInterface::kHaveLocalOffer:
264 return "kHaveLocalOffer";
265 case PeerConnectionInterface::kHaveLocalPrAnswer:
266 return "kHavePrAnswer";
267 case PeerConnectionInterface::kHaveRemoteOffer:
268 return "kHaveRemoteOffer";
269 case PeerConnectionInterface::kHaveRemotePrAnswer:
270 return "kHaveRemotePrAnswer";
271 case PeerConnectionInterface::kClosed:
272 return "kClosed";
273 }
274 RTC_NOTREACHED();
275 return "";
276}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700277
Steve Anton75737c02017-11-06 10:37:17 -0800278IceCandidatePairType GetIceCandidatePairCounter(
279 const cricket::Candidate& local,
280 const cricket::Candidate& remote) {
281 const auto& l = local.type();
282 const auto& r = remote.type();
283 const auto& host = LOCAL_PORT_TYPE;
284 const auto& srflx = STUN_PORT_TYPE;
285 const auto& relay = RELAY_PORT_TYPE;
286 const auto& prflx = PRFLX_PORT_TYPE;
287 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800288 bool local_hostname =
289 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
290 bool remote_hostname = !remote.address().hostname().empty() &&
291 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800292 bool local_private = IPIsPrivate(local.address().ipaddr());
293 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800294 if (local_hostname) {
295 if (remote_hostname) {
296 return kIceCandidatePairHostNameHostName;
297 } else if (remote_private) {
298 return kIceCandidatePairHostNameHostPrivate;
299 } else {
300 return kIceCandidatePairHostNameHostPublic;
301 }
302 } else if (local_private) {
303 if (remote_hostname) {
304 return kIceCandidatePairHostPrivateHostName;
305 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800306 return kIceCandidatePairHostPrivateHostPrivate;
307 } else {
308 return kIceCandidatePairHostPrivateHostPublic;
309 }
310 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800311 if (remote_hostname) {
312 return kIceCandidatePairHostPublicHostName;
313 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800314 return kIceCandidatePairHostPublicHostPrivate;
315 } else {
316 return kIceCandidatePairHostPublicHostPublic;
317 }
318 }
319 }
320 if (l == host && r == srflx)
321 return kIceCandidatePairHostSrflx;
322 if (l == host && r == relay)
323 return kIceCandidatePairHostRelay;
324 if (l == host && r == prflx)
325 return kIceCandidatePairHostPrflx;
326 if (l == srflx && r == host)
327 return kIceCandidatePairSrflxHost;
328 if (l == srflx && r == srflx)
329 return kIceCandidatePairSrflxSrflx;
330 if (l == srflx && r == relay)
331 return kIceCandidatePairSrflxRelay;
332 if (l == srflx && r == prflx)
333 return kIceCandidatePairSrflxPrflx;
334 if (l == relay && r == host)
335 return kIceCandidatePairRelayHost;
336 if (l == relay && r == srflx)
337 return kIceCandidatePairRelaySrflx;
338 if (l == relay && r == relay)
339 return kIceCandidatePairRelayRelay;
340 if (l == relay && r == prflx)
341 return kIceCandidatePairRelayPrflx;
342 if (l == prflx && r == host)
343 return kIceCandidatePairPrflxHost;
344 if (l == prflx && r == srflx)
345 return kIceCandidatePairPrflxSrflx;
346 if (l == prflx && r == relay)
347 return kIceCandidatePairPrflxRelay;
348 return kIceCandidatePairMax;
349}
350
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800351// Logic to decide if an m= section can be recycled. This means that the new
352// m= section is not rejected, but the old local or remote m= section is
353// rejected. |old_content_one| and |old_content_two| refer to the m= section
354// of the old remote and old local descriptions in no particular order.
355// We need to check both the old local and remote because either
356// could be the most current from the latest negotation.
357bool IsMediaSectionBeingRecycled(SdpType type,
358 const ContentInfo& content,
359 const ContentInfo* old_content_one,
360 const ContentInfo* old_content_two) {
361 return type == SdpType::kOffer && !content.rejected &&
362 ((old_content_one && old_content_one->rejected) ||
363 (old_content_two && old_content_two->rejected));
364}
365
Steve Anton75737c02017-11-06 10:37:17 -0800366// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800367// |current_desc|. The number of m= sections in |new_desc| should be no
368// less than |current_desc|. In the case of checking an answer's
369// |new_desc|, the |current_desc| is the last offer that was set as the
370// local or remote. In the case of checking an offer's |new_desc| we
371// check against the local and remote descriptions stored from the last
372// negotiation, because either of these could be the most up to date for
373// possible rejected m sections. These are the |current_desc| and
374// |secondary_current_desc|.
375bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
376 const SessionDescription* secondary_current_desc,
377 const SessionDescription& new_desc,
378 const SdpType type) {
379 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800383 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
384 const cricket::ContentInfo* secondary_content_info = nullptr;
385 if (secondary_current_desc &&
386 i < secondary_current_desc->contents().size()) {
387 secondary_content_info = &secondary_current_desc->contents()[i];
388 }
389 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
390 &current_desc.contents()[i],
391 secondary_content_info)) {
392 // For new offer descriptions, if the media section can be recycled, it's
393 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800394 continue;
395 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800400 new_desc.contents()[i].media_description();
401 const MediaContentDescription* current_desc_mdesc =
402 current_desc.contents()[i].media_description();
403 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800404 return false;
405 }
406 }
407 return true;
408}
409
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800410bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
411 const SessionDescription& desc2) {
412 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800413}
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
416 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200417 // Array of structs needed to map {KeyExchangeProtocolType,
418 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
419 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
420 static constexpr struct {
421 KeyExchangeProtocolType protocol_type;
422 cricket::MediaType media_type;
423 KeyExchangeProtocolMedia protocol_media;
424 } kEnumCounterKeyProtocolMediaMap[] = {
425 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
426 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
427 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
428 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
429 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
430 kEnumCounterKeyProtocolMediaTypeDtlsData},
431 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
432 kEnumCounterKeyProtocolMediaTypeSdesAudio},
433 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
434 kEnumCounterKeyProtocolMediaTypeSdesVideo},
435 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
436 kEnumCounterKeyProtocolMediaTypeSdesData},
437 };
438
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700439 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
440 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100441
Mirko Bonadeiab499822018-09-11 10:43:20 +0200442 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
443 if (i.protocol_type == protocol_type && i.media_type == media_type) {
444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
445 i.protocol_media,
446 kEnumCounterKeyProtocolMediaTypeMax);
447 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100448 }
449}
450
Harald Alvestrand76829d72018-07-18 23:24:36 +0200451void NoteAddIceCandidateResult(int result) {
452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
453 kAddIceCandidateMax);
454}
455
Steve Anton75737c02017-11-06 10:37:17 -0800456// Checks that each non-rejected content has SDES crypto keys or a DTLS
457// fingerprint, unless it's in a BUNDLE group, in which case only the
458// BUNDLE-tag section (first media section/description in the BUNDLE group)
459// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
460// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
461// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700462RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800463 const cricket::ContentGroup* bundle =
464 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800465 for (const cricket::ContentInfo& content_info : desc->contents()) {
466 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800467 continue;
468 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100469 // Note what media is used with each crypto protocol, for all sections.
470 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
471 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700472 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800473 const std::string& mid = content_info.name;
474 if (bundle && bundle->HasContentName(mid) &&
475 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 // This isn't the first media section in the BUNDLE group, so it's not
477 // required to have crypto attributes, since only the crypto attributes
478 // from the first section actually get used.
479 continue;
480 }
481
482 // If the content isn't rejected or bundled into another m= section, crypto
483 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800484 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800485 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800486 if (!media || !tinfo) {
487 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800488 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800489 }
490 if (dtls_enabled) {
491 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100492 RTC_LOG(LS_WARNING)
493 << "Session description must have DTLS fingerprint if "
494 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800495 return RTCError(RTCErrorType::INVALID_PARAMETER,
496 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800497 }
498 } else {
499 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100500 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800501 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800502 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800503 }
504 }
505 }
Steve Anton8a006912017-12-04 15:25:56 -0800506 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800507}
508
509// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
510// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
511// media section/description in the BUNDLE group) needs a ufrag and pwd.
512bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
513 const cricket::ContentGroup* bundle =
514 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800515 for (const cricket::ContentInfo& content_info : desc->contents()) {
516 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800517 continue;
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 const std::string& mid = content_info.name;
520 if (bundle && bundle->HasContentName(mid) &&
521 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 // This isn't the first media section in the BUNDLE group, so it's not
523 // required to have ufrag/password, since only the ufrag/password from
524 // the first section actually get used.
525 continue;
526 }
527
528 // If the content isn't rejected or bundled into another m= section,
529 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800530 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800531 if (!tinfo) {
532 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100533 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800534 return false;
535 }
536 if (tinfo->description.ice_ufrag.empty() ||
537 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 }
542 return true;
543}
544
Steve Anton75737c02017-11-06 10:37:17 -0800545// Get the SCTP port out of a SessionDescription.
546// Return -1 if not found.
547int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 const cricket::DataContentDescription* data_desc =
549 GetFirstDataContentDescription(session_description);
550 RTC_DCHECK(data_desc);
551 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800552 return -1;
553 }
Steve Anton75737c02017-11-06 10:37:17 -0800554 std::string value;
555 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
556 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800557 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800558 if (!codec.Matches(match_pattern)) {
559 continue;
560 }
561 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
562 return rtc::FromString<int>(value);
563 }
564 }
565 return -1;
566}
567
Steve Anton75737c02017-11-06 10:37:17 -0800568// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
569bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
570 const SessionDescriptionInterface* new_desc,
571 const std::string& content_name) {
572 if (!old_desc) {
573 return false;
574 }
575 const SessionDescription* new_sd = new_desc->description();
576 const SessionDescription* old_sd = old_desc->description();
577 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
578 if (!cinfo || cinfo->rejected) {
579 return false;
580 }
581 // If the content isn't rejected, check if ufrag and password has changed.
582 const cricket::TransportDescription* new_transport_desc =
583 new_sd->GetTransportDescriptionByName(content_name);
584 const cricket::TransportDescription* old_transport_desc =
585 old_sd->GetTransportDescriptionByName(content_name);
586 if (!new_transport_desc || !old_transport_desc) {
587 // No transport description exists. This is not an ICE restart.
588 return false;
589 }
590 if (cricket::IceCredentialsChanged(
591 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
592 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100593 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
594 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800595 return true;
596 }
597 return false;
598}
599
Steve Anton80dd7b52018-02-16 17:08:42 -0800600// Generates a string error message for SetLocalDescription/SetRemoteDescription
601// from an RTCError.
602std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
603 SdpType type,
604 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200605 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800606 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
607 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200608 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800609}
610
Seth Hampson5b4f0752018-04-02 16:31:36 -0700611std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
612 std::string output = "streams=[";
613 const char* separator = "";
614 for (const auto& stream_id : stream_ids) {
615 output.append(separator).append(stream_id);
616 separator = ", ";
617 }
618 output.append("]");
619 return output;
620}
621
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200622absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700623 int rtc_configuration_parameter) {
624 if (rtc_configuration_parameter ==
625 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200626 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700627 }
628 return rtc_configuration_parameter;
629}
630
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800631cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
632 switch (type) {
633 case DataMessageType::kText:
634 return cricket::DMT_TEXT;
635 case DataMessageType::kBinary:
636 return cricket::DMT_BINARY;
637 case DataMessageType::kControl:
638 return cricket::DMT_CONTROL;
639 default:
640 return cricket::DMT_NONE;
641 }
642 return cricket::DMT_NONE;
643}
644
645DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
646 switch (type) {
647 case cricket::DMT_TEXT:
648 return DataMessageType::kText;
649 case cricket::DMT_BINARY:
650 return DataMessageType::kBinary;
651 case cricket::DMT_CONTROL:
652 return DataMessageType::kControl;
653 case cricket::DMT_NONE:
654 default:
655 RTC_NOTREACHED();
656 }
657 return DataMessageType::kControl;
658}
659
Steve Anton75737c02017-11-06 10:37:17 -0800660} // namespace
661
Henrik Boström31638672017-11-23 17:48:32 +0100662// Upon completion, posts a task to execute the callback of the
663// SetSessionDescriptionObserver asynchronously on the same thread. At this
664// point, the state of the peer connection might no longer reflect the effects
665// of the SetRemoteDescription operation, as the peer connection could have been
666// modified during the post.
667// TODO(hbos): Remove this class once we remove the version of
668// PeerConnectionInterface::SetRemoteDescription() that takes a
669// SetSessionDescriptionObserver as an argument.
670class PeerConnection::SetRemoteDescriptionObserverAdapter
671 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
672 public:
673 SetRemoteDescriptionObserverAdapter(
674 rtc::scoped_refptr<PeerConnection> pc,
675 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
676 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
677
678 // SetRemoteDescriptionObserverInterface implementation.
679 void OnSetRemoteDescriptionComplete(RTCError error) override {
680 if (error.ok())
681 pc_->PostSetSessionDescriptionSuccess(wrapper_);
682 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100683 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100684 }
685
686 private:
687 rtc::scoped_refptr<PeerConnection> pc_;
688 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
689};
690
deadbeef293e9262017-01-11 12:28:30 -0800691bool PeerConnectionInterface::RTCConfiguration::operator==(
692 const PeerConnectionInterface::RTCConfiguration& o) const {
693 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700694 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800695 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000696 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800698 BundlePolicy bundle_policy;
699 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
701 int ice_candidate_pool_size;
702 bool disable_ipv6;
703 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700704 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100705 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700706 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200707 absl::optional<int> screencast_min_bitrate;
708 absl::optional<bool> combined_audio_video_bwe;
709 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800710 TcpCandidatePolicy tcp_candidate_policy;
711 CandidateNetworkPolicy candidate_network_policy;
712 int audio_jitter_buffer_max_packets;
713 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100714 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100715 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800716 int ice_connection_receiving_timeout;
717 int ice_backup_candidate_pair_ping_interval;
718 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800719 bool prioritize_most_likely_ice_candidate_pairs;
720 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800721 bool prune_turn_ports;
722 bool presume_writable_when_fully_relayed;
723 bool enable_ice_renomination;
724 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200725 absl::optional<int> ice_check_interval_strong_connectivity;
726 absl::optional<int> ice_check_interval_weak_connectivity;
727 absl::optional<int> ice_check_min_interval;
728 absl::optional<int> ice_unwritable_timeout;
729 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800730 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200731 absl::optional<int> stun_candidate_keepalive_interval;
732 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200733 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800734 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700736 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700737 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700738 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700739 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100740 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800741 };
742 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
743 "Did you add something to RTCConfiguration and forget to "
744 "update operator==?");
745 return type == o.type && servers == o.servers &&
746 bundle_policy == o.bundle_policy &&
747 rtcp_mux_policy == o.rtcp_mux_policy &&
748 tcp_candidate_policy == o.tcp_candidate_policy &&
749 candidate_network_policy == o.candidate_network_policy &&
750 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
751 audio_jitter_buffer_fast_accelerate ==
752 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100753 audio_jitter_buffer_min_delay_ms ==
754 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100755 audio_jitter_buffer_enable_rtx_handling ==
756 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800757 ice_connection_receiving_timeout ==
758 o.ice_connection_receiving_timeout &&
759 ice_backup_candidate_pair_ping_interval ==
760 o.ice_backup_candidate_pair_ping_interval &&
761 continual_gathering_policy == o.continual_gathering_policy &&
762 certificates == o.certificates &&
763 prioritize_most_likely_ice_candidate_pairs ==
764 o.prioritize_most_likely_ice_candidate_pairs &&
765 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800766 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700767 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100768 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800769 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800770 screencast_min_bitrate == o.screencast_min_bitrate &&
771 combined_audio_video_bwe == o.combined_audio_video_bwe &&
772 enable_dtls_srtp == o.enable_dtls_srtp &&
773 ice_candidate_pool_size == o.ice_candidate_pool_size &&
774 prune_turn_ports == o.prune_turn_ports &&
775 presume_writable_when_fully_relayed ==
776 o.presume_writable_when_fully_relayed &&
777 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800778 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800779 ice_check_interval_strong_connectivity ==
780 o.ice_check_interval_strong_connectivity &&
781 ice_check_interval_weak_connectivity ==
782 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700783 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700784 ice_unwritable_timeout == o.ice_unwritable_timeout &&
785 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800786 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800787 stun_candidate_keepalive_interval ==
788 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200789 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800790 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800791 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700792 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700793 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700794 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700795 use_media_transport_for_data_channels ==
796 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100797 crypto_options == o.crypto_options &&
798 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800799}
800
801bool PeerConnectionInterface::RTCConfiguration::operator!=(
802 const PeerConnectionInterface::RTCConfiguration& o) const {
803 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800804}
805
zhihuang8f65cdf2016-05-06 18:40:30 -0700806// Generate a RTCP CNAME when a PeerConnection is created.
807std::string GenerateRtcpCname() {
808 std::string cname;
809 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100810 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800811 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700812 }
813 return cname;
814}
815
zhihuang1c378ed2017-08-17 14:10:50 -0700816bool ValidateOfferAnswerOptions(
817 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
818 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
819 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700820}
821
zhihuang1c378ed2017-08-17 14:10:50 -0700822// From |rtc_options|, fill parts of |session_options| shared by all generated
823// m= sections (in other words, nothing that involves a map/array).
824void ExtractSharedMediaSessionOptions(
825 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
826 cricket::MediaSessionOptions* session_options) {
827 session_options->vad_enabled = rtc_options.voice_activity_detection;
828 session_options->bundle_enabled = rtc_options.use_rtp_mux;
829}
zhihuanga77e6bb2017-08-14 18:17:48 -0700830
zhihuang38ede132017-06-15 12:52:32 -0700831PeerConnection::PeerConnection(PeerConnectionFactory* factory,
832 std::unique_ptr<RtcEventLog> event_log,
833 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700835 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700836 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700837 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700838 remote_streams_(StreamCollection::Create()),
839 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840
841PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100842 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800843 RTC_DCHECK_RUN_ON(signaling_thread());
844
Steve Anton8af21862017-12-15 11:20:13 -0800845 // Need to stop transceivers before destroying the stats collector because
846 // AudioRtpSender has a reference to the StatsCollector it will update when
847 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100848 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800849 transceiver->Stop();
850 }
Steve Anton4171afb2017-11-20 10:20:22 -0800851
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700852 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800853 if (stats_collector_) {
854 stats_collector_->WaitForPendingRequest();
855 stats_collector_ = nullptr;
856 }
Steve Anton75737c02017-11-06 10:37:17 -0800857
Steve Anton8af21862017-12-15 11:20:13 -0800858 // Don't destroy BaseChannels until after stats has been cleaned up so that
859 // the last stats request can still read from the channels.
860 DestroyAllChannels();
861
Mirko Bonadei675513b2017-11-09 11:09:25 +0100862 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800863
864 webrtc_session_desc_factory_.reset();
865 sctp_invoker_.reset();
866 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800867 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800868 transport_controller_.reset();
869
deadbeef91dd5672016-05-18 16:55:30 -0700870 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700871 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700872 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700873 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700874 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700875 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800876 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700877 event_log_.reset();
878 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879}
880
Steve Anton8af21862017-12-15 11:20:13 -0800881void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800882 // Destroy video channels first since they may have a pointer to a voice
883 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100884 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800885 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800886 DestroyTransceiverChannel(transceiver);
887 }
888 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100889 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800890 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800891 DestroyTransceiverChannel(transceiver);
892 }
893 }
894 DestroyDataChannel();
895}
896
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000898 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700899 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100900 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700901
902 RTCError config_error = ValidateConfiguration(configuration);
903 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700905 return false;
906 }
907
Benjamin Wrightcab58882018-05-02 15:12:47 -0700908 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100909 RTC_LOG(LS_ERROR)
910 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100911 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800912 return false;
913 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200914
Benjamin Wrightcab58882018-05-02 15:12:47 -0700915 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800916 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100917 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100918 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800919 return false;
920 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700921
Benjamin Wrightcab58882018-05-02 15:12:47 -0700922 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700923 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700924 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700925 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800926
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200927 cricket::ServerAddresses stun_servers;
928 std::vector<cricket::RelayServerConfig> turn_servers;
929
930 RTCErrorType parse_error =
931 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
932 if (parse_error != RTCErrorType::NONE) {
933 return false;
934 }
935
deadbeef91dd5672016-05-18 16:55:30 -0700936 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700937 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700938 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200939 RTC_FROM_HERE,
940 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
941 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942 return false;
943 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200944 // If initialization was successful, note if STUN or TURN servers
945 // were supplied.
946 if (!stun_servers.empty()) {
947 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
948 }
949 if (!turn_servers.empty()) {
950 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
951 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700953 // Send information about IPv4/IPv6 status.
954 PeerConnectionAddressFamilyCounter address_family;
955 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
956 address_family = kPeerConnection_IPv6;
957 } else {
958 address_family = kPeerConnection_IPv4;
959 }
960 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
961 kPeerConnectionAddressFamilyCounter_Max);
962
Zhi Huange830e682018-03-30 10:48:35 -0700963 const PeerConnectionFactoryInterface::Options& options = factory_->options();
964
Steve Anton75737c02017-11-06 10:37:17 -0800965 // RFC 3264: The numeric value of the session id and version in the
966 // o line MUST be representable with a "64 bit signed integer".
967 // Due to this constraint session id |session_id_| is max limited to
968 // LLONG_MAX.
969 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700970 JsepTransportController::Config config;
971 config.redetermine_role_on_ice_restart =
972 configuration.redetermine_role_on_ice_restart;
973 config.ssl_max_version = factory_->options().ssl_max_version;
974 config.disable_encryption = options.disable_encryption;
975 config.bundle_policy = configuration.bundle_policy;
976 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700977 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
978 // stub.
979 config.crypto_options = configuration.crypto_options.has_value()
980 ? *configuration.crypto_options
981 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700982 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700983 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700984#if defined(ENABLE_EXTERNAL_AUTH)
985 config.enable_external_auth = true;
986#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700987 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700988
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700989 if (configuration.use_media_transport ||
990 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700991 if (!factory_->media_transport_factory()) {
992 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700993 << "PeerConnecton is initialized with use_media_transport = true or "
994 << "use_media_transport_for_data_channels = true "
995 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700996 return false;
997 }
998
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -0800999 config.use_media_transport_for_media = configuration.use_media_transport;
1000 config.use_media_transport_for_data_channels =
1001 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001002 config.media_transport_factory = factory_->media_transport_factory();
1003 }
1004
Zhi Huange830e682018-03-30 10:48:35 -07001005 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001006 signaling_thread(), network_thread(), port_allocator_.get(),
1007 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001008 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001009 this, &PeerConnection::OnTransportControllerConnectionState);
1010 transport_controller_->SignalStandardizedIceConnectionState.connect(
1011 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001012 transport_controller_->SignalConnectionState.connect(
1013 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001014 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001015 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001016 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001017 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001018 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001019 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1020 transport_controller_->SignalDtlsHandshakeError.connect(
1021 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1022
1023 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001024
deadbeefab9b2d12015-10-14 11:33:11 -07001025 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001026 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027
Steve Antonba818672017-11-06 10:21:57 -08001028 configuration_ = configuration;
1029
Steve Anton75737c02017-11-06 10:37:17 -08001030 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1031 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1032 if (!configuration.certificates.empty()) {
1033 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1034 // just picking the first one. The decision should be made based on the DTLS
1035 // handshake. The DTLS negotiations need to know about all certificates.
1036 certificate = configuration.certificates[0];
1037 }
1038
Steve Antond25da372017-11-06 14:50:29 -08001039 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001040
1041 if (options.disable_encryption) {
1042 dtls_enabled_ = false;
1043 } else {
1044 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001045 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001046 // |configuration| can override the default |dtls_enabled_| value.
1047 if (configuration.enable_dtls_srtp) {
1048 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1049 }
1050 }
1051
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001052 if (configuration.use_media_transport_for_data_channels) {
1053 if (configuration.enable_rtp_data_channel) {
1054 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1055 "use_media_transport_for_data_channels are "
1056 "incompatible and cannot both be set to true";
1057 return false;
1058 }
1059 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1060 } else if (configuration.enable_rtp_data_channel) {
1061 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1062 // set. It takes precendence over the disable_sctp_data_channels
1063 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001064 data_channel_type_ = cricket::DCT_RTP;
1065 } else {
1066 // DTLS has to be enabled to use SCTP.
1067 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1068 data_channel_type_ = cricket::DCT_SCTP;
1069 }
1070 }
1071
1072 video_options_.screencast_min_bitrate_kbps =
1073 configuration.screencast_min_bitrate;
1074 audio_options_.combined_audio_video_bwe =
1075 configuration.combined_audio_video_bwe;
1076
1077 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001078 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001079
1080 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001081 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001082
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001083 audio_options_.audio_jitter_buffer_min_delay_ms =
1084 configuration.audio_jitter_buffer_min_delay_ms;
1085
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001086 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1087 configuration.audio_jitter_buffer_enable_rtx_handling;
1088
Steve Anton75737c02017-11-06 10:37:17 -08001089 // Whether the certificate generator/certificate is null or not determines
1090 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1091 // the right instructions by clearing the variables if needed.
1092 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001093 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001094 certificate = nullptr;
1095 } else if (certificate) {
1096 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001097 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001098 }
1099
1100 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1101 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001102 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001103 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1104 this, &PeerConnection::OnCertificateReady);
1105
1106 if (options.disable_encryption) {
1107 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1108 }
1109
1110 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001111 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001112 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001113
Steve Anton4171afb2017-11-20 10:20:22 -08001114 // Add default audio/video transceivers for Plan B SDP.
1115 if (!IsUnifiedPlan()) {
1116 transceivers_.push_back(
1117 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1118 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1119 transceivers_.push_back(
1120 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1121 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1122 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001123 int delay_ms =
1124 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001125 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1126 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127 return true;
1128}
1129
Steve Anton038834f2017-07-14 15:59:59 -07001130RTCError PeerConnection::ValidateConfiguration(
1131 const RTCConfiguration& config) const {
1132 if (config.ice_regather_interval_range &&
1133 config.continual_gathering_policy == GATHER_ONCE) {
1134 return RTCError(RTCErrorType::INVALID_PARAMETER,
1135 "ice_regather_interval_range specified but continual "
1136 "gathering policy is GATHER_ONCE");
1137 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001138 auto result =
1139 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1140 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001141}
1142
Yves Gerey665174f2018-06-19 15:03:05 +02001143rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001144 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1145 "Plan SdpSemantics. Please use GetSenders "
1146 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001147 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148}
1149
Yves Gerey665174f2018-06-19 15:03:05 +02001150rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001151 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1152 "Plan SdpSemantics. Please use GetReceivers "
1153 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001154 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001155}
1156
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001157bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001158 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1159 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001160 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001161 if (IsClosed()) {
1162 return false;
1163 }
deadbeefab9b2d12015-10-14 11:33:11 -07001164 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 return false;
1166 }
deadbeefab9b2d12015-10-14 11:33:11 -07001167
1168 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001169 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1170 observer->SignalAudioTrackAdded.connect(this,
1171 &PeerConnection::OnAudioTrackAdded);
1172 observer->SignalAudioTrackRemoved.connect(
1173 this, &PeerConnection::OnAudioTrackRemoved);
1174 observer->SignalVideoTrackAdded.connect(this,
1175 &PeerConnection::OnVideoTrackAdded);
1176 observer->SignalVideoTrackRemoved.connect(
1177 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001178 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001179
deadbeefab9b2d12015-10-14 11:33:11 -07001180 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001181 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001182 }
1183 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001184 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001185 }
1186
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001187 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001188 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001189 return true;
1190}
1191
1192void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001193 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1194 "Plan SdpSemantics. Please use RemoveTrack "
1195 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001196 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001197 if (!IsClosed()) {
1198 for (const auto& track : local_stream->GetAudioTracks()) {
1199 RemoveAudioTrack(track.get(), local_stream);
1200 }
1201 for (const auto& track : local_stream->GetVideoTracks()) {
1202 RemoveVideoTrack(track.get(), local_stream);
1203 }
deadbeefab9b2d12015-10-14 11:33:11 -07001204 }
deadbeefab9b2d12015-10-14 11:33:11 -07001205 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001206 stream_observers_.erase(
1207 std::remove_if(
1208 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001209 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001210 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001211 }),
1212 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001213
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214 if (IsClosed()) {
1215 return;
1216 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001217 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001218}
1219
Steve Anton2d6c76a2018-01-05 17:10:52 -08001220RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001221 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001222 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001223 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001224 if (!track) {
1225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1226 }
1227 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1228 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1229 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1230 "Track has invalid kind: " + track->kind());
1231 }
Steve Antonf9381f02017-12-14 10:23:57 -08001232 if (IsClosed()) {
1233 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1234 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001235 }
Steve Anton4171afb2017-11-20 10:20:22 -08001236 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001237 LOG_AND_RETURN_ERROR(
1238 RTCErrorType::INVALID_PARAMETER,
1239 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001240 }
Steve Antonf9381f02017-12-14 10:23:57 -08001241 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001242 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1243 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001244 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001245 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001246 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001247 }
1248 return sender_or_error;
1249}
deadbeefe1f9d832016-01-14 15:35:42 -08001250
Steve Antonf9381f02017-12-14 10:23:57 -08001251RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1252PeerConnection::AddTrackPlanB(
1253 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001254 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001255 if (stream_ids.size() > 1u) {
1256 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1257 "AddTrack with more than one stream is not "
1258 "supported with Plan B semantics.");
1259 }
1260 std::vector<std::string> adjusted_stream_ids = stream_ids;
1261 if (adjusted_stream_ids.empty()) {
1262 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1263 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001264 cricket::MediaType media_type =
1265 (track->kind() == MediaStreamTrackInterface::kAudioKind
1266 ? cricket::MEDIA_TYPE_AUDIO
1267 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001268 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001269 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001270 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001271 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001272 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001273 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001274 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001275 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001276 if (sender_info) {
1277 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001278 }
Steve Antonf9381f02017-12-14 10:23:57 -08001279 } else {
1280 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001281 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001282 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001283 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001284 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001285 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001286 if (sender_info) {
1287 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001288 }
deadbeefe1f9d832016-01-14 15:35:42 -08001289 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001290 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001291}
deadbeefe1f9d832016-01-14 15:35:42 -08001292
Steve Antonf9381f02017-12-14 10:23:57 -08001293RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1294PeerConnection::AddTrackUnifiedPlan(
1295 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001296 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001297 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1298 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001299 RTC_LOG(LS_INFO) << "Reusing an existing "
1300 << cricket::MediaTypeToString(transceiver->media_type())
1301 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001302 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001303 transceiver->internal()->set_direction(
1304 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001305 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001306 transceiver->internal()->set_direction(
1307 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001308 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001309 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001310 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 } else {
1312 cricket::MediaType media_type =
1313 (track->kind() == MediaStreamTrackInterface::kAudioKind
1314 ? cricket::MEDIA_TYPE_AUDIO
1315 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001316 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1317 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001318 std::string sender_id = track->id();
1319 // Avoid creating a sender with an existing ID by generating a random ID.
1320 // This can happen if this is the second time AddTrack has created a sender
1321 // for this track.
1322 if (FindSenderById(sender_id)) {
1323 sender_id = rtc::CreateRandomUuid();
1324 }
Florent Castelli892acf02018-10-01 22:47:20 +02001325 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001326 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1327 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001328 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001329 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001330 }
Steve Antonf9381f02017-12-14 10:23:57 -08001331 return transceiver->sender();
1332}
1333
1334rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1335PeerConnection::FindFirstTransceiverForAddedTrack(
1336 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1337 RTC_DCHECK(track);
1338 for (auto transceiver : transceivers_) {
1339 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001340 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001341 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001342 !transceiver->internal()->has_ever_been_used_to_send() &&
1343 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001344 return transceiver;
1345 }
1346 }
1347 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001348}
1349
1350bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1351 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001352 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001353}
1354
Steve Anton24db5732018-07-23 10:27:33 -07001355RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001356 rtc::scoped_refptr<RtpSenderInterface> sender) {
1357 if (!sender) {
1358 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1359 }
deadbeefe1f9d832016-01-14 15:35:42 -08001360 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1362 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001363 }
Steve Antonf9381f02017-12-14 10:23:57 -08001364 if (IsUnifiedPlan()) {
1365 auto transceiver = FindTransceiverBySender(sender);
1366 if (!transceiver || !sender->track()) {
1367 return RTCError::OK();
1368 }
1369 sender->SetTrack(nullptr);
1370 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001371 transceiver->internal()->set_direction(
1372 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001373 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001374 transceiver->internal()->set_direction(
1375 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001376 }
Steve Anton4171afb2017-11-20 10:20:22 -08001377 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001378 bool removed;
1379 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1380 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1381 } else {
1382 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1383 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1384 }
1385 if (!removed) {
1386 LOG_AND_RETURN_ERROR(
1387 RTCErrorType::INVALID_PARAMETER,
1388 "Couldn't find sender " + sender->id() + " to remove.");
1389 }
Steve Anton4171afb2017-11-20 10:20:22 -08001390 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001391 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001392 return RTCError::OK();
1393}
1394
1395rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1396PeerConnection::FindTransceiverBySender(
1397 rtc::scoped_refptr<RtpSenderInterface> sender) {
1398 for (auto transceiver : transceivers_) {
1399 if (transceiver->sender() == sender) {
1400 return transceiver;
1401 }
1402 }
1403 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001404}
1405
Steve Anton9158ef62017-11-27 13:01:52 -08001406RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1407PeerConnection::AddTransceiver(
1408 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1409 return AddTransceiver(track, RtpTransceiverInit());
1410}
1411
1412RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1413PeerConnection::AddTransceiver(
1414 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1415 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001416 RTC_CHECK(IsUnifiedPlan())
1417 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001418 if (!track) {
1419 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1420 }
1421 cricket::MediaType media_type;
1422 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1423 media_type = cricket::MEDIA_TYPE_AUDIO;
1424 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1425 media_type = cricket::MEDIA_TYPE_VIDEO;
1426 } else {
1427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1428 "Track kind is not audio or video");
1429 }
1430 return AddTransceiver(media_type, track, init);
1431}
1432
1433RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1434PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1435 return AddTransceiver(media_type, RtpTransceiverInit());
1436}
1437
1438RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1439PeerConnection::AddTransceiver(cricket::MediaType media_type,
1440 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001441 RTC_CHECK(IsUnifiedPlan())
1442 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001443 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1444 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1445 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1446 "media type is not audio or video");
1447 }
1448 return AddTransceiver(media_type, nullptr, init);
1449}
1450
1451RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1452PeerConnection::AddTransceiver(
1453 cricket::MediaType media_type,
1454 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001455 const RtpTransceiverInit& init,
1456 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001457 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1458 media_type == cricket::MEDIA_TYPE_VIDEO));
1459 if (track) {
1460 RTC_DCHECK_EQ(media_type,
1461 (track->kind() == MediaStreamTrackInterface::kAudioKind
1462 ? cricket::MEDIA_TYPE_AUDIO
1463 : cricket::MEDIA_TYPE_VIDEO));
1464 }
1465
Amit Hilbuchaa584152019-02-06 17:09:52 -08001466 size_t num_rids = absl::c_count_if(init.send_encodings,
1467 [](const RtpEncodingParameters& encoding) {
1468 return !encoding.rid.empty();
1469 });
1470 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001471 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001472 RTCErrorType::INVALID_PARAMETER,
1473 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001474 }
1475
Amit Hilbuchaa584152019-02-06 17:09:52 -08001476 if (absl::c_any_of(init.send_encodings,
1477 [](const RtpEncodingParameters& encoding) {
1478 return encoding.ssrc.has_value();
1479 })) {
1480 LOG_AND_RETURN_ERROR(
1481 RTCErrorType::UNSUPPORTED_PARAMETER,
1482 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001483 }
1484
1485 RtpParameters parameters;
1486 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001487
1488 // Encodings are dropped from the tail if too many are provided.
1489 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1490 parameters.encodings.erase(
1491 parameters.encodings.begin() + kMaxSimulcastStreams,
1492 parameters.encodings.end());
1493 }
1494
1495 // Single RID should be removed.
1496 if (parameters.encodings.size() == 1 &&
1497 !parameters.encodings[0].rid.empty()) {
1498 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1499 parameters.encodings[0].rid.clear();
1500 }
1501
1502 // If RIDs were not provided, they are generated for simulcast scenario.
1503 if (parameters.encodings.size() > 1 && num_rids == 0) {
1504 rtc::UniqueStringGenerator rid_generator;
1505 for (RtpEncodingParameters& encoding : parameters.encodings) {
1506 encoding.rid = rid_generator();
1507 }
1508 }
1509
Florent Castelli892acf02018-10-01 22:47:20 +02001510 if (UnimplementedRtpParameterHasValue(parameters)) {
1511 LOG_AND_RETURN_ERROR(
1512 RTCErrorType::UNSUPPORTED_PARAMETER,
1513 "Attempted to set an unimplemented parameter of RtpParameters.");
1514 }
Steve Anton9158ef62017-11-27 13:01:52 -08001515
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001516 auto result = cricket::CheckRtpParametersValues(parameters);
1517 if (!result.ok()) {
1518 LOG_AND_RETURN_ERROR(result.type(), result.message());
1519 }
1520
Steve Anton3d954a62018-04-02 11:27:23 -07001521 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1522 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001523 // Set the sender ID equal to the track ID if the track is specified unless
1524 // that sender ID is already in use.
1525 std::string sender_id =
1526 (track && !FindSenderById(track->id()) ? track->id()
1527 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001528 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001529 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001530 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1531 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1532 transceiver->internal()->set_direction(init.direction);
1533
Steve Anton22da89f2018-01-25 13:58:07 -08001534 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001535 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001536 }
Steve Antonf9381f02017-12-14 10:23:57 -08001537
1538 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1539}
1540
Steve Anton02ee47c2018-01-10 16:26:06 -08001541rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1542PeerConnection::CreateSender(
1543 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001544 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001545 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001546 const std::vector<std::string>& stream_ids,
1547 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001548 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001549 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1550 RTC_DCHECK(!track ||
1551 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1552 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1553 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001554 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001555 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001556 } else {
1557 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1558 RTC_DCHECK(!track ||
1559 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1560 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001561 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001562 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001563 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001564 bool set_track_succeeded = sender->SetTrack(track);
1565 RTC_DCHECK(set_track_succeeded);
1566 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001567 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001568 return sender;
1569}
1570
1571rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1572PeerConnection::CreateReceiver(cricket::MediaType media_type,
1573 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001574 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1575 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001576 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001577 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001578 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1579 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001580 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001581 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001582 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001583 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001584 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1585 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001586 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001587 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001588 return receiver;
1589}
1590
1591rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1592PeerConnection::CreateAndAddTransceiver(
1593 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1594 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1595 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001596 // Ensure that the new sender does not have an ID that is already in use by
1597 // another sender.
1598 // Allow receiver IDs to conflict since those come from remote SDP (which
1599 // could be invalid, but should not cause a crash).
1600 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001601 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1602 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001603 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001604 transceiver->internal()->SignalNegotiationNeeded.connect(
1605 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001606 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001607}
1608
Steve Anton52d86772018-02-20 15:48:12 -08001609void PeerConnection::OnNegotiationNeeded() {
1610 RTC_DCHECK_RUN_ON(signaling_thread());
1611 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001612 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001613}
1614
deadbeeffac06552015-11-25 11:26:01 -08001615rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001616 const std::string& kind,
1617 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001618 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1619 "Plan SdpSemantics. Please use AddTransceiver "
1620 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001621 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001622 if (IsClosed()) {
1623 return nullptr;
1624 }
Steve Anton4171afb2017-11-20 10:20:22 -08001625
Seth Hampson5b4f0752018-04-02 16:31:36 -07001626 // Internally we need to have one stream with Plan B semantics, so we
1627 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001628 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001629 if (stream_id.empty()) {
1630 stream_ids.push_back(rtc::CreateRandomUuid());
1631 RTC_LOG(LS_INFO)
1632 << "No stream_id specified for sender. Generated stream ID: "
1633 << stream_ids[0];
1634 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001635 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001636 }
1637
Steve Anton4171afb2017-11-20 10:20:22 -08001638 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001639 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001640 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001641 auto* audio_sender = new AudioRtpSender(
1642 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001643 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001644 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001645 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001646 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001647 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001648 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001649 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001650 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001651 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001652 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001653 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001654 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001655 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001656 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001657 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001658 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001659
deadbeefe1f9d832016-01-14 15:35:42 -08001660 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001661}
1662
deadbeef70ab1a12015-09-28 16:53:55 -07001663std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1664 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001665 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001666 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001667 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001668 }
1669 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001670}
1671
Steve Anton4171afb2017-11-20 10:20:22 -08001672std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1673PeerConnection::GetSendersInternal() const {
1674 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1675 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001676 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001677 auto senders = transceiver->internal()->senders();
1678 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1679 }
1680 return all_senders;
1681}
1682
deadbeef70ab1a12015-09-28 16:53:55 -07001683std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1684PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001685 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001686 for (const auto& receiver : GetReceiversInternal()) {
1687 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001688 }
1689 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001690}
1691
Steve Anton4171afb2017-11-20 10:20:22 -08001692std::vector<
1693 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1694PeerConnection::GetReceiversInternal() const {
1695 std::vector<
1696 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1697 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001698 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001699 auto receivers = transceiver->internal()->receivers();
1700 all_receivers.insert(all_receivers.end(), receivers.begin(),
1701 receivers.end());
1702 }
1703 return all_receivers;
1704}
1705
Steve Anton9158ef62017-11-27 13:01:52 -08001706std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1707PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001708 RTC_CHECK(IsUnifiedPlan())
1709 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001710 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001711 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001712 all_transceivers.push_back(transceiver);
1713 }
1714 return all_transceivers;
1715}
1716
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001717bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001718 MediaStreamTrackInterface* track,
1719 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001720 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001721 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001722 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001723 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001724 return false;
1725 }
1726
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001727 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001728 // The StatsCollector is used to tell if a track is valid because it may
1729 // remember tracks that the PeerConnection previously removed.
1730 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001731 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1732 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001733 return false;
1734 }
Steve Antonad182762018-09-05 20:22:40 +00001735 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1736 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001737 return true;
1738}
1739
hbos74e1a4f2016-09-15 23:33:01 -07001740void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001741 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001742 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001743 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001744 stats_collector_->GetStatsReport(callback);
1745}
1746
Henrik Boström1df1bf82018-03-20 13:24:20 +01001747void PeerConnection::GetStats(
1748 rtc::scoped_refptr<RtpSenderInterface> selector,
1749 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1750 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1751 RTC_DCHECK(callback);
1752 RTC_DCHECK(stats_collector_);
1753 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1754 if (selector) {
1755 for (const auto& proxy_transceiver : transceivers_) {
1756 for (const auto& proxy_sender :
1757 proxy_transceiver->internal()->senders()) {
1758 if (proxy_sender == selector) {
1759 internal_sender = proxy_sender->internal();
1760 break;
1761 }
1762 }
1763 if (internal_sender)
1764 break;
1765 }
1766 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001767 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001768 // belong to the PeerConnection (in Plan B, senders can be removed from the
1769 // PeerConnection). This means that "all the stats objects representing the
1770 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1771 // produces an empty stats report.
1772 stats_collector_->GetStatsReport(internal_sender, callback);
1773}
1774
1775void PeerConnection::GetStats(
1776 rtc::scoped_refptr<RtpReceiverInterface> selector,
1777 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1778 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1779 RTC_DCHECK(callback);
1780 RTC_DCHECK(stats_collector_);
1781 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1782 if (selector) {
1783 for (const auto& proxy_transceiver : transceivers_) {
1784 for (const auto& proxy_receiver :
1785 proxy_transceiver->internal()->receivers()) {
1786 if (proxy_receiver == selector) {
1787 internal_receiver = proxy_receiver->internal();
1788 break;
1789 }
1790 }
1791 if (internal_receiver)
1792 break;
1793 }
1794 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001795 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001796 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1797 // the PeerConnection). This means that "all the stats objects representing
1798 // the selector" is an empty set. Invoking GetStatsReport() with a null
1799 // selector produces an empty stats report.
1800 stats_collector_->GetStatsReport(internal_receiver, callback);
1801}
1802
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1804 return signaling_state_;
1805}
1806
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807PeerConnectionInterface::IceConnectionState
1808PeerConnection::ice_connection_state() {
1809 return ice_connection_state_;
1810}
1811
Alex Loiko9289eda2018-11-23 16:18:59 +00001812PeerConnectionInterface::IceConnectionState
1813PeerConnection::standardized_ice_connection_state() {
1814 return standardized_ice_connection_state_;
1815}
1816
Jonas Olsson635474e2018-10-18 15:58:17 +02001817PeerConnectionInterface::PeerConnectionState
1818PeerConnection::peer_connection_state() {
1819 return connection_state_;
1820}
1821
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822PeerConnectionInterface::IceGatheringState
1823PeerConnection::ice_gathering_state() {
1824 return ice_gathering_state_;
1825}
1826
Yves Gerey665174f2018-06-19 15:03:05 +02001827rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001828 const std::string& label,
1829 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001830 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001831 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001832
deadbeefab9b2d12015-10-14 11:33:11 -07001833 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001834
kwibergd1fe2812016-04-27 06:47:29 -07001835 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001836 if (config) {
1837 internal_config.reset(new InternalDataChannelInit(*config));
1838 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001839 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001840 InternalCreateDataChannel(label, internal_config.get()));
1841 if (!channel.get()) {
1842 return nullptr;
1843 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001845 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1846 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001847 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001848 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001849 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001850 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001851 return DataChannelProxy::Create(signaling_thread(), channel.get());
1852}
1853
1854void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001855 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001856 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001857
nisse7ce109a2017-01-31 00:57:56 -08001858 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001859 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001860 return;
1861 }
deadbeefab9b2d12015-10-14 11:33:11 -07001862
Steve Anton8d3444d2017-10-20 15:30:51 -07001863 if (IsClosed()) {
1864 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001865 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001866 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001867 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001868 return;
1869 }
1870
zhihuang1c378ed2017-08-17 14:10:50 -07001871 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001872 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001873 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001874 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001875 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001876 return;
1877 }
1878
Steve Anton22da89f2018-01-25 13:58:07 -08001879 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1880 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1881 if (IsUnifiedPlan()) {
1882 RTCError error = HandleLegacyOfferOptions(options);
1883 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001884 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001885 return;
1886 }
1887 }
1888
zhihuang1c378ed2017-08-17 14:10:50 -07001889 cricket::MediaSessionOptions session_options;
1890 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001891 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892}
1893
Steve Anton22da89f2018-01-25 13:58:07 -08001894RTCError PeerConnection::HandleLegacyOfferOptions(
1895 const RTCOfferAnswerOptions& options) {
1896 RTC_DCHECK(IsUnifiedPlan());
1897
1898 if (options.offer_to_receive_audio == 0) {
1899 RemoveRecvDirectionFromReceivingTransceiversOfType(
1900 cricket::MEDIA_TYPE_AUDIO);
1901 } else if (options.offer_to_receive_audio == 1) {
1902 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1903 } else if (options.offer_to_receive_audio > 1) {
1904 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1905 "offer_to_receive_audio > 1 is not supported.");
1906 }
1907
1908 if (options.offer_to_receive_video == 0) {
1909 RemoveRecvDirectionFromReceivingTransceiversOfType(
1910 cricket::MEDIA_TYPE_VIDEO);
1911 } else if (options.offer_to_receive_video == 1) {
1912 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1913 } else if (options.offer_to_receive_video > 1) {
1914 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1915 "offer_to_receive_video > 1 is not supported.");
1916 }
1917
1918 return RTCError::OK();
1919}
1920
1921void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1922 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001923 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001924 RtpTransceiverDirection new_direction =
1925 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1926 if (new_direction != transceiver->direction()) {
1927 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1928 << " transceiver (MID="
1929 << transceiver->mid().value_or("<not set>") << ") from "
1930 << RtpTransceiverDirectionToString(
1931 transceiver->direction())
1932 << " to "
1933 << RtpTransceiverDirectionToString(new_direction)
1934 << " since CreateOffer specified offer_to_receive=0";
1935 transceiver->internal()->set_direction(new_direction);
1936 }
Steve Anton22da89f2018-01-25 13:58:07 -08001937 }
1938}
1939
1940void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1941 cricket::MediaType media_type) {
1942 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001943 RTC_LOG(LS_INFO)
1944 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1945 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001946 RtpTransceiverInit init;
1947 init.direction = RtpTransceiverDirection::kRecvOnly;
1948 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1949 }
1950}
1951
1952std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1953PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1954 std::vector<
1955 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1956 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001957 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001958 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001959 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1960 receiving_transceivers.push_back(transceiver);
1961 }
1962 }
1963 return receiving_transceivers;
1964}
1965
htaa2a49d92016-03-04 02:51:39 -08001966void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1967 const RTCOfferAnswerOptions& options) {
1968 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001969 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001970 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001971 return;
1972 }
1973
Steve Antondffead82018-02-06 10:31:29 -08001974 if (!(signaling_state_ == kHaveRemoteOffer ||
1975 signaling_state_ == kHaveLocalPrAnswer)) {
1976 std::string error =
1977 "PeerConnection cannot create an answer in a state other than "
1978 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001979 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001980 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001981 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001982 return;
1983 }
1984
Steve Antondffead82018-02-06 10:31:29 -08001985 // The remote description should be set if we're in the right state.
1986 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001987
Steve Anton22da89f2018-01-25 13:58:07 -08001988 if (IsUnifiedPlan()) {
1989 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1990 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1991 "supported with Unified Plan semantics. Use the "
1992 "RtpTransceiver API instead.";
1993 }
1994 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1995 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1996 "supported with Unified Plan semantics. Use the "
1997 "RtpTransceiver API instead.";
1998 }
1999 }
2000
htaa2a49d92016-03-04 02:51:39 -08002001 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002002 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002003
Steve Antond25da372017-11-06 14:50:29 -08002004 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002005}
2006
2007void PeerConnection::SetLocalDescription(
2008 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002009 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002010 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002011
Steve Anton80dd7b52018-02-16 17:08:42 -08002012 // The SetLocalDescription contract is that we take ownership of the session
2013 // description regardless of the outcome, so wrap it in a unique_ptr right
2014 // away. Ideally, SetLocalDescription's signature will be changed to take the
2015 // description as a unique_ptr argument to formalize this agreement.
2016 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2017
nisse7ce109a2017-01-31 00:57:56 -08002018 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002019 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002020 return;
2021 }
Steve Anton8a006912017-12-04 15:25:56 -08002022
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002023 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002024 PostSetSessionDescriptionFailure(
2025 observer,
2026 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002027 return;
2028 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002029
Steve Anton80dd7b52018-02-16 17:08:42 -08002030 // If a session error has occurred the PeerConnection is in a possibly
2031 // inconsistent state so fail right away.
2032 if (session_error() != SessionError::kNone) {
2033 std::string error_message = GetSessionErrorMsg();
2034 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002035 PostSetSessionDescriptionFailure(
2036 observer,
2037 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002038 return;
2039 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002040
Steve Anton80dd7b52018-02-16 17:08:42 -08002041 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2042 if (!error.ok()) {
2043 std::string error_message = GetSetDescriptionErrorMessage(
2044 cricket::CS_LOCAL, desc->GetType(), error);
2045 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002046 PostSetSessionDescriptionFailure(
2047 observer,
2048 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002049 return;
2050 }
2051
2052 // Grab the description type before moving ownership to ApplyLocalDescription,
2053 // which may destroy it before returning.
2054 const SdpType type = desc->GetType();
2055
2056 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002057 // |desc| may be destroyed at this point.
2058
2059 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002060 // If ApplyLocalDescription fails, the PeerConnection could be in an
2061 // inconsistent state, so act conservatively here and set the session error
2062 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2063 SetSessionError(SessionError::kContent, error.message());
2064 std::string error_message =
2065 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2066 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002067 PostSetSessionDescriptionFailure(
2068 observer,
2069 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002070 return;
2071 }
Steve Anton8a006912017-12-04 15:25:56 -08002072 RTC_DCHECK(local_description());
2073
2074 PostSetSessionDescriptionSuccess(observer);
2075
Steve Antonad182762018-09-05 20:22:40 +00002076 // MaybeStartGathering needs to be called after posting
2077 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2078 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002079 transport_controller_->MaybeStartGathering();
2080
Steve Antona3a92c22017-12-07 10:27:41 -08002081 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002082 // TODO(deadbeef): We already had to hop to the network thread for
2083 // MaybeStartGathering...
2084 network_thread()->Invoke<void>(
2085 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2086 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002087 // Make UMA notes about what was agreed to.
2088 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002089 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002090 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002091}
2092
2093RTCError PeerConnection::ApplyLocalDescription(
2094 std::unique_ptr<SessionDescriptionInterface> desc) {
2095 RTC_DCHECK_RUN_ON(signaling_thread());
2096 RTC_DCHECK(desc);
2097
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002098 // Update stats here so that we have the most recent stats for tracks and
2099 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002100 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002101
Steve Antondcc3c022017-12-22 16:02:54 -08002102 // Take a reference to the old local description since it's used below to
2103 // compare against the new local description. When setting the new local
2104 // description, grab ownership of the replaced session description in case it
2105 // is the same as |old_local_description|, to keep it alive for the duration
2106 // of the method.
2107 const SessionDescriptionInterface* old_local_description =
2108 local_description();
2109 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002110 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002111 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002112 replaced_local_description = pending_local_description_
2113 ? std::move(pending_local_description_)
2114 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002115 current_local_description_ = std::move(desc);
2116 pending_local_description_ = nullptr;
2117 current_remote_description_ = std::move(pending_remote_description_);
2118 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002119 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002120 pending_local_description_ = std::move(desc);
2121 }
2122 // The session description to apply now must be accessed by
2123 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002124 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002125
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002126 if (!is_caller_) {
2127 if (remote_description()) {
2128 // Remote description was applied first, so this PC is the callee.
2129 is_caller_ = false;
2130 } else {
2131 // Local description is applied first, so this PC is the caller.
2132 is_caller_ = true;
2133 }
2134 }
2135
Zhi Huange830e682018-03-30 10:48:35 -07002136 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2137 if (!error.ok()) {
2138 return error;
2139 }
2140
Steve Antondcc3c022017-12-22 16:02:54 -08002141 if (IsUnifiedPlan()) {
2142 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002143 cricket::CS_LOCAL, *local_description(), old_local_description,
2144 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002145 if (!error.ok()) {
2146 return error;
2147 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002148 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2149 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002150 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002151 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2152 // Note that code paths that don't set MID won't be able to use
2153 // information about DTLS transports.
2154 if (transceiver->mid()) {
2155 auto dtls_transport =
2156 LookupDtlsTransportByMidInternal(*transceiver->mid());
2157 transceiver->internal()->sender_internal()->set_transport(
2158 dtls_transport);
2159 transceiver->internal()->receiver_internal()->set_transport(
2160 dtls_transport);
2161 }
2162
Steve Antondcc3c022017-12-22 16:02:54 -08002163 const ContentInfo* content =
2164 FindMediaSectionForTransceiver(transceiver, local_description());
2165 if (!content) {
2166 continue;
2167 }
2168 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002169 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2170 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002171 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002172 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2173 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2174 // "recvonly", process the removal of a remote track for the media
2175 // description, given transceiver, removeList, and muteTracks.
2176 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2177 (transceiver->internal()->fired_direction() &&
2178 RtpTransceiverDirectionHasRecv(
2179 *transceiver->internal()->fired_direction()))) {
2180 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2181 &removed_streams);
2182 }
2183 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2184 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002185 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002186 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002187 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002188 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002189 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002190 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002191 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002192 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002193 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002194 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002195 }
2196 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002197 // Media channels will be created only when offer is set. These may use new
2198 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002199 if (type == SdpType::kOffer) {
2200 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2201 // description is applied. Restore back to old description.
2202 RTCError error = CreateChannels(*local_description()->description());
2203 if (!error.ok()) {
2204 return error;
2205 }
2206 }
Steve Antondcc3c022017-12-22 16:02:54 -08002207 // Remove unused channels if MediaContentDescription is rejected.
2208 RemoveUnusedChannels(local_description()->description());
2209 }
Steve Anton8a006912017-12-04 15:25:56 -08002210
Zhi Huange830e682018-03-30 10:48:35 -07002211 error = UpdateSessionState(type, cricket::CS_LOCAL,
2212 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002213 if (!error.ok()) {
2214 return error;
2215 }
Steve Antondcc3c022017-12-22 16:02:54 -08002216
Steve Anton8a006912017-12-04 15:25:56 -08002217 if (remote_description()) {
2218 // Now that we have a local description, we can push down remote candidates.
2219 UseCandidatesInSessionDescription(remote_description());
2220 }
2221
2222 pending_ice_restarts_.clear();
2223 if (session_error() != SessionError::kNone) {
2224 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2225 }
2226
deadbeefab9b2d12015-10-14 11:33:11 -07002227 // If setting the description decided our SSL role, allocate any necessary
2228 // SCTP sids.
2229 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002230 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002231 AllocateSctpSids(role);
2232 }
2233
Steve Antond3679212018-01-17 17:41:02 -08002234 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002235 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002236 const ContentInfo* content =
2237 FindMediaSectionForTransceiver(transceiver, local_description());
2238 if (!content) {
2239 continue;
2240 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002241 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2242 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002243 // 0 is a special value meaning "this sender has no associated send
2244 // stream". Need to call this so the sender won't attempt to configure
2245 // a no longer existing stream and run into DCHECKs in the lower
2246 // layers.
2247 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002248 } else {
2249 // Get the StreamParams from the channel which could generate SSRCs.
2250 const std::vector<StreamParams>& streams = channel->local_streams();
2251 transceiver->internal()->sender_internal()->set_stream_ids(
2252 streams[0].stream_ids());
2253 transceiver->internal()->sender_internal()->SetSsrc(
2254 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002255 }
2256 }
2257 } else {
2258 // Plan B semantics.
2259
Steve Antondcc3c022017-12-22 16:02:54 -08002260 // Update state and SSRC of local MediaStreams and DataChannels based on the
2261 // local session description.
2262 const cricket::ContentInfo* audio_content =
2263 GetFirstAudioContent(local_description()->description());
2264 if (audio_content) {
2265 if (audio_content->rejected) {
2266 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2267 } else {
2268 const cricket::AudioContentDescription* audio_desc =
2269 audio_content->media_description()->as_audio();
2270 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2271 }
deadbeeffaac4972015-11-12 15:33:07 -08002272 }
deadbeefab9b2d12015-10-14 11:33:11 -07002273
Steve Antondcc3c022017-12-22 16:02:54 -08002274 const cricket::ContentInfo* video_content =
2275 GetFirstVideoContent(local_description()->description());
2276 if (video_content) {
2277 if (video_content->rejected) {
2278 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2279 } else {
2280 const cricket::VideoContentDescription* video_desc =
2281 video_content->media_description()->as_video();
2282 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2283 }
deadbeeffaac4972015-11-12 15:33:07 -08002284 }
deadbeefab9b2d12015-10-14 11:33:11 -07002285 }
2286
2287 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002288 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002289 if (data_content) {
2290 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002291 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002292 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002293 cricket::kMediaProtocolRtpPrefix)) {
2294 UpdateLocalRtpDataChannels(data_desc->streams());
2295 }
2296 }
2297
Steve Anton8a006912017-12-04 15:25:56 -08002298 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002299}
2300
Steve Anton06817cd2018-12-18 15:55:30 -08002301// The SDP parser used to populate these values by default for the 'content
2302// name' if an a=mid line was absent.
2303static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2304 switch (media_type) {
2305 case cricket::MEDIA_TYPE_AUDIO:
2306 return cricket::CN_AUDIO;
2307 case cricket::MEDIA_TYPE_VIDEO:
2308 return cricket::CN_VIDEO;
2309 case cricket::MEDIA_TYPE_DATA:
2310 return cricket::CN_DATA;
2311 }
2312 RTC_NOTREACHED();
2313 return "";
2314}
2315
2316void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002317 cricket::SessionDescription* new_remote_description) {
2318 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002319 const cricket::ContentInfos& local_contents =
2320 (local_description() ? local_description()->description()->contents()
2321 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002322 const cricket::ContentInfos& remote_contents =
2323 (remote_description() ? remote_description()->description()->contents()
2324 : cricket::ContentInfos());
2325 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2326 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002327 if (!content.name.empty()) {
2328 continue;
2329 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002330 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002331 absl::string_view source_explanation;
2332 if (IsUnifiedPlan()) {
2333 if (i < local_contents.size()) {
2334 new_mid = local_contents[i].name;
2335 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002336 } else if (i < remote_contents.size()) {
2337 new_mid = remote_contents[i].name;
2338 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002339 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002340 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002341 source_explanation = "generated just now";
2342 }
2343 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002344 new_mid = std::string(
2345 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002346 source_explanation = "to match pre-existing behavior";
2347 }
Steve Antond7180cc2019-02-07 10:44:53 -08002348 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002349 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002350 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002351 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2352 << " is missing an a=mid line. Filling in the value '"
2353 << new_mid << "' " << source_explanation << ".";
2354 }
2355}
2356
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002357void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002358 SetSessionDescriptionObserver* observer,
2359 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002360 SetRemoteDescription(
2361 std::unique_ptr<SessionDescriptionInterface>(desc),
2362 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2363 new SetRemoteDescriptionObserverAdapter(this, observer)));
2364}
2365
2366void PeerConnection::SetRemoteDescription(
2367 std::unique_ptr<SessionDescriptionInterface> desc,
2368 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002369 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002370
nisse7ce109a2017-01-31 00:57:56 -08002371 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002372 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002373 return;
2374 }
Steve Anton8a006912017-12-04 15:25:56 -08002375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002376 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002377 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002378 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379 return;
2380 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002381
Steve Anton80dd7b52018-02-16 17:08:42 -08002382 // If a session error has occurred the PeerConnection is in a possibly
2383 // inconsistent state so fail right away.
2384 if (session_error() != SessionError::kNone) {
2385 std::string error_message = GetSessionErrorMsg();
2386 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2387 observer->OnSetRemoteDescriptionComplete(
2388 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2389 return;
2390 }
Steve Anton71439a62018-02-15 11:53:06 -08002391
Steve Antonba42e992018-04-09 14:10:01 -07002392 if (desc->GetType() == SdpType::kOffer) {
2393 // Report to UMA the format of the received offer.
2394 ReportSdpFormatReceived(*desc);
2395 }
2396
Steve Anton06817cd2018-12-18 15:55:30 -08002397 // Handle remote descriptions missing a=mid lines for interop with legacy end
2398 // points.
2399 FillInMissingRemoteMids(desc->description());
2400
Steve Anton80dd7b52018-02-16 17:08:42 -08002401 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002402 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002403 std::string error_message = GetSetDescriptionErrorMessage(
2404 cricket::CS_REMOTE, desc->GetType(), error);
2405 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002406 observer->OnSetRemoteDescriptionComplete(
2407 RTCError(error.type(), std::move(error_message)));
2408 return;
2409 }
Steve Anton71439a62018-02-15 11:53:06 -08002410
Steve Anton80dd7b52018-02-16 17:08:42 -08002411 // Grab the description type before moving ownership to
2412 // ApplyRemoteDescription, which may destroy it before returning.
2413 const SdpType type = desc->GetType();
2414
2415 error = ApplyRemoteDescription(std::move(desc));
2416 // |desc| may be destroyed at this point.
2417
2418 if (!error.ok()) {
2419 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2420 // inconsistent state, so act conservatively here and set the session error
2421 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2422 SetSessionError(SessionError::kContent, error.message());
2423 std::string error_message =
2424 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2425 RTC_LOG(LS_ERROR) << error_message;
2426 observer->OnSetRemoteDescriptionComplete(
2427 RTCError(error.type(), std::move(error_message)));
2428 return;
2429 }
2430 RTC_DCHECK(remote_description());
2431
2432 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002433 // TODO(deadbeef): We already had to hop to the network thread for
2434 // MaybeStartGathering...
2435 network_thread()->Invoke<void>(
2436 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2437 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002438 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002439 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002440 }
2441
2442 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002443 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002444}
2445
2446RTCError PeerConnection::ApplyRemoteDescription(
2447 std::unique_ptr<SessionDescriptionInterface> desc) {
2448 RTC_DCHECK_RUN_ON(signaling_thread());
2449 RTC_DCHECK(desc);
2450
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451 // Update stats here so that we have the most recent stats for tracks and
2452 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002453 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002454
Steve Antondcc3c022017-12-22 16:02:54 -08002455 // Take a reference to the old remote description since it's used below to
2456 // compare against the new remote description. When setting the new remote
2457 // description, grab ownership of the replaced session description in case it
2458 // is the same as |old_remote_description|, to keep it alive for the duration
2459 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002460 const SessionDescriptionInterface* old_remote_description =
2461 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002462 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002463 SdpType type = desc->GetType();
2464 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002465 replaced_remote_description = pending_remote_description_
2466 ? std::move(pending_remote_description_)
2467 : std::move(current_remote_description_);
2468 current_remote_description_ = std::move(desc);
2469 pending_remote_description_ = nullptr;
2470 current_local_description_ = std::move(pending_local_description_);
2471 } else {
2472 replaced_remote_description = std::move(pending_remote_description_);
2473 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002474 }
Steve Anton8a006912017-12-04 15:25:56 -08002475 // The session description to apply now must be accessed by
2476 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002477 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478
Zhi Huange830e682018-03-30 10:48:35 -07002479 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2480 if (!error.ok()) {
2481 return error;
2482 }
Steve Anton8a006912017-12-04 15:25:56 -08002483 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002484 if (IsUnifiedPlan()) {
2485 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002486 cricket::CS_REMOTE, *remote_description(), local_description(),
2487 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002488 if (!error.ok()) {
2489 return error;
2490 }
Steve Antondcc3c022017-12-22 16:02:54 -08002491 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002492 // Media channels will be created only when offer is set. These may use new
2493 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002494 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002495 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002496 // description is applied. Restore back to old description.
2497 RTCError error = CreateChannels(*remote_description()->description());
2498 if (!error.ok()) {
2499 return error;
2500 }
2501 }
Steve Antondcc3c022017-12-22 16:02:54 -08002502 // Remove unused channels if MediaContentDescription is rejected.
2503 RemoveUnusedChannels(remote_description()->description());
2504 }
Steve Anton8a006912017-12-04 15:25:56 -08002505
Zhi Huange830e682018-03-30 10:48:35 -07002506 // NOTE: Candidates allocation will be initiated only when
2507 // SetLocalDescription is called.
2508 error = UpdateSessionState(type, cricket::CS_REMOTE,
2509 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002510 if (!error.ok()) {
2511 return error;
2512 }
2513
2514 if (local_description() &&
2515 !UseCandidatesInSessionDescription(remote_description())) {
2516 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2517 }
2518
2519 if (old_remote_description) {
2520 for (const cricket::ContentInfo& content :
2521 old_remote_description->description()->contents()) {
2522 // Check if this new SessionDescription contains new ICE ufrag and
2523 // password that indicates the remote peer requests an ICE restart.
2524 // TODO(deadbeef): When we start storing both the current and pending
2525 // remote description, this should reset pending_ice_restarts and compare
2526 // against the current description.
2527 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2528 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002529 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002530 pending_ice_restarts_.insert(content.name);
2531 }
2532 } else {
2533 // We retain all received candidates only if ICE is not restarted.
2534 // When ICE is restarted, all previous candidates belong to an old
2535 // generation and should not be kept.
2536 // TODO(deadbeef): This goes against the W3C spec which says the remote
2537 // description should only contain candidates from the last set remote
2538 // description plus any candidates added since then. We should remove
2539 // this once we're sure it won't break anything.
2540 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2541 old_remote_description, content.name, mutable_remote_description());
2542 }
2543 }
2544 }
2545
2546 if (session_error() != SessionError::kNone) {
2547 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2548 }
2549
2550 // Set the the ICE connection state to connecting since the connection may
2551 // become writable with peer reflexive candidates before any remote candidate
2552 // is signaled.
2553 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2554 // is to have a new signal the indicates a change in checking state from the
2555 // transport and expose a new checking() member from transport that can be
2556 // read to determine the current checking state. The existing SignalConnecting
2557 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002558 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002559 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002560 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2561 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2562 }
2563
deadbeefab9b2d12015-10-14 11:33:11 -07002564 // If setting the description decided our SSL role, allocate any necessary
2565 // SCTP sids.
2566 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002567 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002568 AllocateSctpSids(role);
2569 }
2570
Steve Antondcc3c022017-12-22 16:02:54 -08002571 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002572 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002573 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002574 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002575 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002576 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002577 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002578 const ContentInfo* content =
2579 FindMediaSectionForTransceiver(transceiver, remote_description());
2580 if (!content) {
2581 continue;
2582 }
2583 const MediaContentDescription* media_desc = content->media_description();
2584 RtpTransceiverDirection local_direction =
2585 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002586 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2587 // RTCSessionDescription: Set the associated remote streams given
2588 // transceiver.[[Receiver]], msids, addList, and removeList".
2589 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2590 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2591 std::vector<std::string> stream_ids;
2592 if (!media_desc->streams().empty()) {
2593 // The remote description has signaled the stream IDs.
2594 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002595 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002596 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2597 << " (" << GetStreamIdsString(stream_ids) << ").";
2598 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2599 stream_ids, &added_streams,
2600 &removed_streams);
2601 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2602 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2603 // and transceiver's current direction is neither sendrecv nor recvonly,
2604 // process the addition of a remote track for the media description.
2605 if (!transceiver->fired_direction() ||
2606 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2607 RTC_LOG(LS_INFO)
2608 << "Processing the addition of a remote track for MID="
2609 << content->name << ".";
2610 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002611 }
Steve Antondcc3c022017-12-22 16:02:54 -08002612 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002613 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002614 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2615 // removal of a remote track for the media description, given transceiver,
2616 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002617 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002618 (transceiver->fired_direction() &&
2619 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2620 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2621 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002622 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002623 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002624 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002625 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002626 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002627 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002628 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002629 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002630 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002631 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2632 if (transceiver->mid()) {
2633 auto dtls_transport =
2634 LookupDtlsTransportByMidInternal(*transceiver->mid());
2635 transceiver->internal()->sender_internal()->set_transport(
2636 dtls_transport);
2637 transceiver->internal()->receiver_internal()->set_transport(
2638 dtls_transport);
2639 }
Steve Antondcc3c022017-12-22 16:02:54 -08002640 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002641 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002642 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002643 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002644 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2645 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002646 transceiver->Stop();
2647 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002648 if (!content->rejected &&
2649 RtpTransceiverDirectionHasRecv(local_direction)) {
2650 // Set ssrc to 0 in the case of an unsignalled ssrc.
2651 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002652 if (!media_desc->streams().empty() &&
2653 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002654 ssrc = media_desc->streams()[0].first_ssrc();
2655 }
2656 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002657 }
Steve Antondcc3c022017-12-22 16:02:54 -08002658 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002659 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002660 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002661 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002662 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002663 observer->OnTrack(transceiver);
2664 observer->OnAddTrack(transceiver->receiver(),
2665 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002666 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002667 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002668 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002669 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002670 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002671 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002672 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002673 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002674 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002675 }
Steve Antondcc3c022017-12-22 16:02:54 -08002676 }
2677
Henrik Boströmfdb92012017-11-09 19:55:44 +01002678 const cricket::ContentInfo* audio_content =
2679 GetFirstAudioContent(remote_description()->description());
2680 const cricket::ContentInfo* video_content =
2681 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002682 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002683 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002684 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002685 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002686 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002687 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002688
2689 // Check if the descriptions include streams, just in case the peer supports
2690 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002691 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002692 (audio_desc && !audio_desc->streams().empty()) ||
2693 (video_desc && !video_desc->streams().empty())) {
2694 remote_peer_supports_msid_ = true;
2695 }
deadbeefab9b2d12015-10-14 11:33:11 -07002696
2697 // We wait to signal new streams until we finish processing the description,
2698 // since only at that point will new streams have all their tracks.
2699 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2700
Steve Antondcc3c022017-12-22 16:02:54 -08002701 if (!IsUnifiedPlan()) {
2702 // TODO(steveanton): When removing RTP senders/receivers in response to a
2703 // rejected media section, there is some cleanup logic that expects the
2704 // voice/ video channel to still be set. But in this method the voice/video
2705 // channel would have been destroyed by the SetRemoteDescription caller
2706 // above so the cleanup that relies on them fails to run. The RemoveSenders
2707 // calls should be moved to right before the DestroyChannel calls to fix
2708 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002709
Steve Antondcc3c022017-12-22 16:02:54 -08002710 // Find all audio rtp streams and create corresponding remote AudioTracks
2711 // and MediaStreams.
2712 if (audio_content) {
2713 if (audio_content->rejected) {
2714 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2715 } else {
2716 bool default_audio_track_needed =
2717 !remote_peer_supports_msid_ &&
2718 RtpTransceiverDirectionHasSend(audio_desc->direction());
2719 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2720 default_audio_track_needed, audio_desc->type(),
2721 new_streams);
2722 }
deadbeeffaac4972015-11-12 15:33:07 -08002723 }
deadbeefab9b2d12015-10-14 11:33:11 -07002724
Steve Antondcc3c022017-12-22 16:02:54 -08002725 // Find all video rtp streams and create corresponding remote VideoTracks
2726 // and MediaStreams.
2727 if (video_content) {
2728 if (video_content->rejected) {
2729 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2730 } else {
2731 bool default_video_track_needed =
2732 !remote_peer_supports_msid_ &&
2733 RtpTransceiverDirectionHasSend(video_desc->direction());
2734 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2735 default_video_track_needed, video_desc->type(),
2736 new_streams);
2737 }
deadbeeffaac4972015-11-12 15:33:07 -08002738 }
deadbeefab9b2d12015-10-14 11:33:11 -07002739
Steve Antondcc3c022017-12-22 16:02:54 -08002740 // Update the DataChannels with the information from the remote peer.
2741 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002742 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002743 cricket::kMediaProtocolRtpPrefix)) {
2744 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2745 }
deadbeefab9b2d12015-10-14 11:33:11 -07002746 }
deadbeefab9b2d12015-10-14 11:33:11 -07002747
Steve Antondcc3c022017-12-22 16:02:54 -08002748 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002749 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002750 for (size_t i = 0; i < new_streams->count(); ++i) {
2751 MediaStreamInterface* new_stream = new_streams->at(i);
2752 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002753 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002754 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2755 }
deadbeefab9b2d12015-10-14 11:33:11 -07002756
Steve Antondcc3c022017-12-22 16:02:54 -08002757 UpdateEndedRemoteMediaStreams();
2758 }
deadbeefab9b2d12015-10-14 11:33:11 -07002759
Steve Anton8a006912017-12-04 15:25:56 -08002760 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002761}
2762
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002763void PeerConnection::SetAssociatedRemoteStreams(
2764 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2765 const std::vector<std::string>& stream_ids,
2766 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2767 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2768 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2769 for (const std::string& stream_id : stream_ids) {
2770 rtc::scoped_refptr<MediaStreamInterface> stream =
2771 remote_streams_->find(stream_id);
2772 if (!stream) {
2773 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2774 MediaStream::Create(stream_id));
2775 remote_streams_->AddStream(stream);
2776 added_streams->push_back(stream);
2777 }
2778 media_streams.push_back(stream);
2779 }
2780 // Special case: "a=msid" missing, use random stream ID.
2781 if (media_streams.empty() &&
2782 !(remote_description()->description()->msid_signaling() &
2783 cricket::kMsidSignalingMediaSection)) {
2784 if (!missing_msid_default_stream_) {
2785 missing_msid_default_stream_ = MediaStreamProxy::Create(
2786 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2787 added_streams->push_back(missing_msid_default_stream_);
2788 }
2789 media_streams.push_back(missing_msid_default_stream_);
2790 }
2791 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2792 receiver->streams();
2793 // SetStreams() will add/remove the receiver's track to/from the streams. This
2794 // differs from the spec - the spec uses an "addList" and "removeList" to
2795 // update the stream-track relationships in a later step. We do this earlier,
2796 // changing the order of things, but the end-result is the same.
2797 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2798 // instead. https://crbug.com/webrtc/9480
2799 receiver->SetStreams(media_streams);
2800 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2801}
2802
Steve Anton0f5400a2018-07-17 14:25:36 -07002803void PeerConnection::ProcessRemovalOfRemoteTrack(
2804 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2805 transceiver,
2806 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2807 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2808 RTC_DCHECK(transceiver->mid());
2809 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2810 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002811 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002812 transceiver->internal()->receiver_internal()->streams();
2813 // This will remove the remote track from the streams.
2814 transceiver->internal()->receiver_internal()->set_stream_ids({});
2815 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002816 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2817}
2818
2819void PeerConnection::RemoveRemoteStreamsIfEmpty(
2820 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2821 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2822 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2823 // streams, see if the stream was removed by checking if this was the last
2824 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002825 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002826 if (remote_stream->GetAudioTracks().empty() &&
2827 remote_stream->GetVideoTracks().empty()) {
2828 remote_streams_->RemoveStream(remote_stream);
2829 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002830 }
2831 }
2832}
2833
Steve Antondcc3c022017-12-22 16:02:54 -08002834RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2835 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002836 const SessionDescriptionInterface& new_session,
2837 const SessionDescriptionInterface* old_local_description,
2838 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002839 RTC_DCHECK(IsUnifiedPlan());
2840
Steve Anton7464fca2018-01-19 11:10:37 -08002841 const cricket::ContentGroup* bundle_group = nullptr;
2842 if (new_session.GetType() == SdpType::kOffer) {
2843 auto bundle_group_or_error =
2844 GetEarlyBundleGroup(*new_session.description());
2845 if (!bundle_group_or_error.ok()) {
2846 return bundle_group_or_error.MoveError();
2847 }
2848 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002849 }
Steve Antondcc3c022017-12-22 16:02:54 -08002850
Steve Antondcc3c022017-12-22 16:02:54 -08002851 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002852 for (size_t i = 0; i < new_contents.size(); ++i) {
2853 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002854 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002855 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002856 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2857 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002858 const cricket::ContentInfo* old_local_content = nullptr;
2859 if (old_local_description &&
2860 i < old_local_description->description()->contents().size()) {
2861 old_local_content =
2862 &old_local_description->description()->contents()[i];
2863 }
2864 const cricket::ContentInfo* old_remote_content = nullptr;
2865 if (old_remote_description &&
2866 i < old_remote_description->description()->contents().size()) {
2867 old_remote_content =
2868 &old_remote_description->description()->contents()[i];
2869 }
Steve Antondcc3c022017-12-22 16:02:54 -08002870 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002871 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2872 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002873 if (!transceiver_or_error.ok()) {
2874 return transceiver_or_error.MoveError();
2875 }
2876 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002877 RTCError error =
2878 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2879 if (!error.ok()) {
2880 return error;
2881 }
2882 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002883 if (GetDataMid() && new_content.name != *GetDataMid()) {
2884 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002885 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2886 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002887 continue;
2888 }
2889 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2890 if (!error.ok()) {
2891 return error;
2892 }
Steve Antondcc3c022017-12-22 16:02:54 -08002893 } else {
2894 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2895 "Unknown section type.");
2896 }
2897 }
2898
2899 return RTCError::OK();
2900}
2901
2902RTCError PeerConnection::UpdateTransceiverChannel(
2903 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2904 transceiver,
2905 const cricket::ContentInfo& content,
2906 const cricket::ContentGroup* bundle_group) {
2907 RTC_DCHECK(IsUnifiedPlan());
2908 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002909 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002910 if (content.rejected) {
2911 if (channel) {
2912 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002913 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002914 }
2915 } else {
2916 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002917 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002918 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002919 } else {
Steve Anton69470252018-02-09 11:43:08 -08002920 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002921 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002922 }
2923 if (!channel) {
2924 LOG_AND_RETURN_ERROR(
2925 RTCErrorType::INTERNAL_ERROR,
2926 "Failed to create channel for mid=" + content.name);
2927 }
2928 transceiver->internal()->SetChannel(channel);
2929 }
2930 }
2931 return RTCError::OK();
2932}
2933
Steve Antonfa2260d2017-12-28 16:38:23 -08002934RTCError PeerConnection::UpdateDataChannel(
2935 cricket::ContentSource source,
2936 const cricket::ContentInfo& content,
2937 const cricket::ContentGroup* bundle_group) {
2938 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002939 // If data channels are disabled, ignore this media section. CreateAnswer
2940 // will take care of rejecting it.
2941 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002942 }
2943 if (content.rejected) {
2944 DestroyDataChannel();
2945 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002946 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002947 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002948 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2949 "Failed to create data channel.");
2950 }
2951 }
2952 if (source == cricket::CS_REMOTE) {
2953 const MediaContentDescription* data_desc = content.media_description();
2954 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2955 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2956 }
2957 }
2958 }
2959 return RTCError::OK();
2960}
2961
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002962// This method will extract any send encodings that were sent by the remote
2963// connection. This is currently only relevant for Simulcast scenario (where
2964// the number of layers may be communicated by the server).
2965static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2966 const MediaContentDescription& desc) {
2967 if (!desc.HasSimulcast()) {
2968 return {};
2969 }
2970 std::vector<RtpEncodingParameters> result;
2971 const SimulcastDescription& simulcast = desc.simulcast_description();
2972
2973 // This is a remote description, the parameters we are after should appear
2974 // as receive streams.
2975 for (const auto& alternatives : simulcast.receive_layers()) {
2976 RTC_DCHECK(!alternatives.empty());
2977 // There is currently no way to specify or choose from alternatives.
2978 // We will always use the first alternative, which is the most preferred.
2979 const SimulcastLayer& layer = alternatives[0];
2980 RtpEncodingParameters parameters;
2981 parameters.rid = layer.rid;
2982 parameters.active = !layer.is_paused;
2983 result.push_back(parameters);
2984 }
2985
2986 return result;
2987}
2988
2989static RTCError UpdateSimulcastLayerStatusInSender(
2990 const std::vector<SimulcastLayer>& layers,
2991 RtpSenderInterface* sender) {
2992 RTC_DCHECK(sender);
2993 RtpParameters parameters = sender->GetParameters();
2994
2995 // The simulcast envelope cannot be changed, only the status of the streams.
2996 // So we will iterate over the send encodings rather than the layers.
2997 for (RtpEncodingParameters& encoding : parameters.encodings) {
2998 auto iter = std::find_if(layers.begin(), layers.end(),
2999 [&encoding](const SimulcastLayer& layer) {
3000 return layer.rid == encoding.rid;
3001 });
3002 // A layer that cannot be found may have been removed by the remote party.
3003 encoding.active = iter != layers.end() && !iter->is_paused;
3004 }
3005
3006 return sender->SetParameters(parameters);
3007}
3008
3009static RTCError DisableSimulcastInSender(RtpSenderInterface* sender) {
3010 RTC_DCHECK(sender);
3011 RtpParameters parameters = sender->GetParameters();
3012 if (parameters.encodings.empty()) {
3013 return RTCError::OK();
3014 }
3015
3016 bool first_layer_status = parameters.encodings[0].active;
3017 for (RtpEncodingParameters& encoding : parameters.encodings) {
3018 // TODO(bugs.webrtc.org/10251): Active does not really disable the layer.
3019 // The user might enable it at a later point in time even though it was
3020 // rejected.
3021 encoding.active = false;
3022 }
3023 parameters.encodings[0].active = first_layer_status;
3024
3025 return sender->SetParameters(parameters);
3026}
3027
Steve Antondcc3c022017-12-22 16:02:54 -08003028RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3029PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003030 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003031 size_t mline_index,
3032 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003033 const ContentInfo* old_local_content,
3034 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003035 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003036 // If this is an offer then the m= section might be recycled. If the m=
3037 // section is being recycled (defined as: rejected in the current local or
3038 // remote description and not rejected in new description), dissociate the
3039 // currently associated RtpTransceiver by setting its mid property to null,
3040 // and discard the mapping between the transceiver and its m= section index.
3041 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3042 old_remote_content)) {
3043 // We want to dissociate the transceiver that has the rejected mid.
3044 const std::string& old_mid =
3045 (old_local_content && old_local_content->rejected)
3046 ? old_local_content->name
3047 : old_remote_content->name;
3048 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003049 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003050 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3051 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003052 old_transceiver->internal()->set_mid(absl::nullopt);
3053 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003054 }
3055 }
3056 const MediaContentDescription* media_desc = content.media_description();
3057 auto transceiver = GetAssociatedTransceiver(content.name);
3058 if (source == cricket::CS_LOCAL) {
3059 // Find the RtpTransceiver that corresponds to this m= section, using the
3060 // mapping between transceivers and m= section indices established when
3061 // creating the offer.
3062 if (!transceiver) {
3063 transceiver = GetTransceiverByMLineIndex(mline_index);
3064 }
3065 if (!transceiver) {
3066 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3067 "Unknown transceiver");
3068 }
3069 } else {
3070 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3071 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3072 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003073 // When simulcast is requested, a transceiver cannot be associated because
3074 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003075 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003076 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3077 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003078 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3079 }
3080 // If no RtpTransceiver was found in the previous step, create one with a
3081 // recvonly direction.
3082 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003083 RTC_LOG(LS_INFO) << "Adding "
3084 << cricket::MediaTypeToString(media_desc->type())
3085 << " transceiver for MID=" << content.name
3086 << " at i=" << mline_index
3087 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003088 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003089 std::vector<RtpEncodingParameters> send_encodings =
3090 GetSendEncodingsFromRemoteDescription(*media_desc);
3091 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3092 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003093 std::string receiver_id;
3094 if (!media_desc->streams().empty()) {
3095 receiver_id = media_desc->streams()[0].id;
3096 } else {
3097 receiver_id = rtc::CreateRandomUuid();
3098 }
3099 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003100 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003101 transceiver->internal()->set_direction(
3102 RtpTransceiverDirection::kRecvOnly);
3103 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003104
3105 // Check if the offer indicated simulcast but the answer rejected it.
3106 // This can happen when simulcast is not supported on the remote party.
3107 // This check can be simplified to comparing the number of send encodings,
3108 // but that might break legacy implementation in which simulcast is not
3109 // signaled in the remote description.
3110 if (old_local_content && old_local_content->media_description() &&
3111 old_local_content->media_description()->HasSimulcast() &&
3112 !media_desc->HasSimulcast()) {
3113 RTCError error =
3114 DisableSimulcastInSender(transceiver->internal()->sender());
3115 if (!error.ok()) {
3116 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3117 return std::move(error);
3118 }
3119 }
Steve Antondcc3c022017-12-22 16:02:54 -08003120 }
3121 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003122 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003123 LOG_AND_RETURN_ERROR(
3124 RTCErrorType::INVALID_PARAMETER,
3125 "Transceiver type does not match media description type.");
3126 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003127 if (media_desc->HasSimulcast()) {
3128 std::vector<SimulcastLayer> layers =
3129 source == cricket::CS_LOCAL
3130 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3131 : media_desc->simulcast_description()
3132 .receive_layers()
3133 .GetAllLayers();
3134 RTCError error = UpdateSimulcastLayerStatusInSender(
3135 layers, transceiver->internal()->sender());
3136 if (!error.ok()) {
3137 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3138 return std::move(error);
3139 }
3140 }
Steve Antondcc3c022017-12-22 16:02:54 -08003141 // Associate the found or created RtpTransceiver with the m= section by
3142 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3143 // section, and establish a mapping between the transceiver and the index of
3144 // the m= section.
3145 transceiver->internal()->set_mid(content.name);
3146 transceiver->internal()->set_mline_index(mline_index);
3147 return std::move(transceiver);
3148}
3149
3150rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3151PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3152 RTC_DCHECK(IsUnifiedPlan());
3153 for (auto transceiver : transceivers_) {
3154 if (transceiver->mid() == mid) {
3155 return transceiver;
3156 }
3157 }
3158 return nullptr;
3159}
3160
3161rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3162PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3163 RTC_DCHECK(IsUnifiedPlan());
3164 for (auto transceiver : transceivers_) {
3165 if (transceiver->internal()->mline_index() == mline_index) {
3166 return transceiver;
3167 }
3168 }
3169 return nullptr;
3170}
3171
3172rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3173PeerConnection::FindAvailableTransceiverToReceive(
3174 cricket::MediaType media_type) const {
3175 RTC_DCHECK(IsUnifiedPlan());
3176 // From JSEP section 5.10 (Applying a Remote Description):
3177 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3178 // the same type that were added to the PeerConnection by addTrack and are not
3179 // associated with any m= section and are not stopped, find the first such
3180 // RtpTransceiver.
3181 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003182 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003183 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3184 !transceiver->stopped()) {
3185 return transceiver;
3186 }
3187 }
3188 return nullptr;
3189}
3190
Steve Antoned10bd92017-12-05 10:52:59 -08003191const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3192 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3193 transceiver,
3194 const SessionDescriptionInterface* sdesc) const {
3195 RTC_DCHECK(transceiver);
3196 RTC_DCHECK(sdesc);
3197 if (IsUnifiedPlan()) {
3198 if (!transceiver->internal()->mid()) {
3199 // This transceiver is not associated with a media section yet.
3200 return nullptr;
3201 }
3202 return sdesc->description()->GetContentByName(
3203 *transceiver->internal()->mid());
3204 } else {
3205 // Plan B only allows at most one audio and one video section, so use the
3206 // first media section of that type.
3207 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003208 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003209 }
3210}
3211
deadbeef46c73892016-11-16 19:42:04 -08003212PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3213 return configuration_;
3214}
3215
deadbeef293e9262017-01-11 12:28:30 -08003216bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3217 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003218 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003219 if (IsClosed()) {
3220 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3221 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3222 }
3223
Qingsi Wanga2d60672018-04-11 16:57:45 -07003224 // According to JSEP, after setLocalDescription, changing the candidate pool
3225 // size is not allowed, and changing the set of ICE servers will not result
3226 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003227 if (local_description() && configuration.ice_candidate_pool_size !=
3228 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003229 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3230 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003231 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003232 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003233
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003234 if (local_description() &&
3235 configuration.use_media_transport != configuration_.use_media_transport) {
3236 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3237 "SetLocalDescription.";
3238 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3239 }
3240
3241 if (remote_description() &&
3242 configuration.use_media_transport != configuration_.use_media_transport) {
3243 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3244 "SetRemoteDescription.";
3245 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3246 }
3247
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003248 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003249 configuration.use_media_transport_for_data_channels !=
3250 configuration_.use_media_transport_for_data_channels) {
3251 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3252 "after calling SetLocalDescription.";
3253 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3254 }
3255
3256 if (remote_description() &&
3257 configuration.use_media_transport_for_data_channels !=
3258 configuration_.use_media_transport_for_data_channels) {
3259 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3260 "after calling SetRemoteDescription.";
3261 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3262 }
3263
3264 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003265 configuration.crypto_options != configuration_.crypto_options) {
3266 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3267 "SetLocalDescription.";
3268 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3269 }
3270
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003271 if (configuration.use_media_transport_for_data_channels ||
3272 configuration.use_media_transport) {
3273 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3274 << "Media transport requires MaxBundle policy.";
3275 }
3276
deadbeef293e9262017-01-11 12:28:30 -08003277 // The simplest (and most future-compatible) way to tell if the config was
3278 // modified in an invalid way is to copy each property we do support
3279 // modifying, then use operator==. There are far more properties we don't
3280 // support modifying than those we do, and more could be added.
3281 RTCConfiguration modified_config = configuration_;
3282 modified_config.servers = configuration.servers;
3283 modified_config.type = configuration.type;
3284 modified_config.ice_candidate_pool_size =
3285 configuration.ice_candidate_pool_size;
3286 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003287 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003288 modified_config.ice_check_interval_strong_connectivity =
3289 configuration.ice_check_interval_strong_connectivity;
3290 modified_config.ice_check_interval_weak_connectivity =
3291 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003292 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3293 modified_config.ice_unwritable_min_checks =
3294 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003295 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003296 modified_config.stun_candidate_keepalive_interval =
3297 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003298 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003299 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003300 modified_config.active_reset_srtp_params =
3301 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003302 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003303 modified_config.use_media_transport_for_data_channels =
3304 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003305 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003306 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003307 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3308 }
3309
Steve Anton038834f2017-07-14 15:59:59 -07003310 // Validate the modified configuration.
3311 RTCError validate_error = ValidateConfiguration(modified_config);
3312 if (!validate_error.ok()) {
3313 return SafeSetError(std::move(validate_error), error);
3314 }
3315
deadbeef293e9262017-01-11 12:28:30 -08003316 // Note that this isn't possible through chromium, since it's an unsigned
3317 // short in WebIDL.
3318 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003319 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003320 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3321 }
3322
3323 // Parse ICE servers before hopping to network thread.
3324 cricket::ServerAddresses stun_servers;
3325 std::vector<cricket::RelayServerConfig> turn_servers;
3326 RTCErrorType parse_error =
3327 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3328 if (parse_error != RTCErrorType::NONE) {
3329 return SafeSetError(parse_error, error);
3330 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003331 // Note if STUN or TURN servers were supplied.
3332 if (!stun_servers.empty()) {
3333 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3334 }
3335 if (!turn_servers.empty()) {
3336 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3337 }
deadbeef293e9262017-01-11 12:28:30 -08003338
3339 // In theory this shouldn't fail.
3340 if (!network_thread()->Invoke<bool>(
3341 RTC_FROM_HERE,
3342 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3343 stun_servers, turn_servers, modified_config.type,
3344 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003345 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003346 modified_config.turn_customizer,
3347 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003348 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003349 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3350 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003351
deadbeefd1a38b52016-12-10 13:15:33 -08003352 // As described in JSEP, calling setConfiguration with new ICE servers or
3353 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3354 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003355 if (modified_config.servers != configuration_.servers ||
3356 modified_config.type != configuration_.type ||
3357 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003358 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003359 }
skvladd1f5fda2017-02-03 16:54:05 -08003360
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003361 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003362 transport_controller_->SetMediaTransportSettings(
3363 modified_config.use_media_transport,
3364 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003365
Zhi Huangb57e1692018-06-12 11:41:11 -07003366 if (configuration_.active_reset_srtp_params !=
3367 modified_config.active_reset_srtp_params) {
3368 transport_controller_->SetActiveResetSrtpParams(
3369 modified_config.active_reset_srtp_params);
3370 }
3371
deadbeef293e9262017-01-11 12:28:30 -08003372 configuration_ = modified_config;
3373 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003374}
3375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003376bool PeerConnection::AddIceCandidate(
3377 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003378 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003379 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003380 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003381 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003382 return false;
3383 }
Steve Antond25da372017-11-06 14:50:29 -08003384
3385 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003386 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003387 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003388 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003389 return false;
3390 }
3391
3392 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003393 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003394 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003395 return false;
3396 }
3397
3398 bool valid = false;
3399 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3400 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003401 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003402 return false;
3403 }
3404
3405 // Add this candidate to the remote session description.
3406 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003407 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003408 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003409 return false;
3410 }
3411
3412 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003413 bool result = UseCandidate(ice_candidate);
3414 if (result) {
3415 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3416 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3417 } else {
3418 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3419 }
3420 return result;
Steve Antond25da372017-11-06 14:50:29 -08003421 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003422 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003423 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003424 return true;
3425 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003426}
3427
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003428bool PeerConnection::RemoveIceCandidates(
3429 const std::vector<cricket::Candidate>& candidates) {
3430 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003431 if (IsClosed()) {
3432 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3433 return false;
3434 }
3435
Steve Antond25da372017-11-06 14:50:29 -08003436 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003437 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3438 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003439 return false;
3440 }
3441
3442 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003443 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003444 return false;
3445 }
3446
3447 size_t number_removed =
3448 mutable_remote_description()->RemoveCandidates(candidates);
3449 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003450 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003451 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003452 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003453 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003454 }
3455
3456 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003457 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3458 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003459 RTC_LOG(LS_ERROR)
3460 << "RemoveIceCandidates: Error when removing remote candidates: "
3461 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003462 }
3463 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003464}
3465
Niels Möller0c4f7be2018-05-07 14:01:37 +02003466RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003467 if (!worker_thread()->IsCurrent()) {
3468 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003469 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003470 }
3471
Niels Möller0c4f7be2018-05-07 14:01:37 +02003472 const bool has_min = bitrate.min_bitrate_bps.has_value();
3473 const bool has_start = bitrate.start_bitrate_bps.has_value();
3474 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003475 if (has_min && *bitrate.min_bitrate_bps < 0) {
3476 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3477 "min_bitrate_bps <= 0");
3478 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003479 if (has_start) {
3480 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003482 "start_bitrate_bps < min_bitrate_bps");
3483 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003484 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3485 "curent_bitrate_bps < 0");
3486 }
3487 }
3488 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003489 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003490 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003491 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003492 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3494 "max_bitrate_bps < min_bitrate_bps");
3495 } else if (*bitrate.max_bitrate_bps < 0) {
3496 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3497 "max_bitrate_bps < 0");
3498 }
3499 }
3500
zstein4b979802017-06-02 14:37:37 -07003501 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003502 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003503
3504 return RTCError::OK();
3505}
3506
Alex Narest78609d52017-10-20 10:37:47 +02003507void PeerConnection::SetBitrateAllocationStrategy(
3508 std::unique_ptr<rtc::BitrateAllocationStrategy>
3509 bitrate_allocation_strategy) {
3510 rtc::Thread* worker_thread = factory_->worker_thread();
3511 if (!worker_thread->IsCurrent()) {
3512 rtc::BitrateAllocationStrategy* strategy_raw =
3513 bitrate_allocation_strategy.release();
3514 auto functor = [this, strategy_raw]() {
3515 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003516 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003517 };
3518 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3519 return;
3520 }
3521 RTC_DCHECK(call_.get());
3522 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3523}
3524
henrika5f6bf242017-11-01 11:06:56 +01003525void PeerConnection::SetAudioPlayout(bool playout) {
3526 if (!worker_thread()->IsCurrent()) {
3527 worker_thread()->Invoke<void>(
3528 RTC_FROM_HERE,
3529 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3530 return;
3531 }
3532 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003533 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003534 audio_state->SetPlayout(playout);
3535}
3536
3537void PeerConnection::SetAudioRecording(bool recording) {
3538 if (!worker_thread()->IsCurrent()) {
3539 worker_thread()->Invoke<void>(
3540 RTC_FROM_HERE,
3541 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3542 return;
3543 }
3544 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003545 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003546 audio_state->SetRecording(recording);
3547}
3548
Steve Anton8c0f7a72017-10-03 10:03:10 -07003549std::unique_ptr<rtc::SSLCertificate>
3550PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003551 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3552 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003553 return nullptr;
3554 }
Steve Antonf25303e2018-10-16 15:23:31 -07003555 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003556}
3557
Zhi Huang70b820f2018-01-27 14:16:15 -08003558std::unique_ptr<rtc::SSLCertChain>
3559PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003560 auto audio_transceiver = GetFirstAudioTransceiver();
3561 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003562 return nullptr;
3563 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003564 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003565 audio_transceiver->internal()->channel()->transport_name());
3566}
3567
3568rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3569PeerConnection::GetFirstAudioTransceiver() const {
3570 for (auto transceiver : transceivers_) {
3571 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3572 return transceiver;
3573 }
3574 }
3575 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003576}
3577
ivoc14d5dbe2016-07-04 07:06:55 -07003578bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3579 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003580 // TODO(eladalon): It would be better to not allow negative values into PC.
3581 const size_t max_size = (max_size_bytes < 0)
3582 ? RtcEventLog::kUnlimitedOutput
3583 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003584 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3585 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3586 output_period_ms = 5000;
3587 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003588 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003589 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003590 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003591}
3592
Bjorn Tereliusde939432017-11-20 17:38:14 +01003593bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3594 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003595 // TODO(eladalon): In C++14, this can be done with a lambda.
3596 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003597 bool operator()() {
3598 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3599 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003600 PeerConnection* const pc;
3601 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003602 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003603 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003604 return worker_thread()->Invoke<bool>(
3605 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003606}
3607
3608void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003609 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003610 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3611}
3612
Harald Alvestrandad88c882018-11-28 16:47:46 +01003613rtc::scoped_refptr<DtlsTransportInterface>
3614PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3615 return transport_controller_->LookupDtlsTransportByMid(mid);
3616}
3617
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003618rtc::scoped_refptr<DtlsTransport>
3619PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3620 return transport_controller_->LookupDtlsTransportByMid(mid);
3621}
3622
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003623const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003624 return pending_local_description_ ? pending_local_description_.get()
3625 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003626}
3627
3628const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003629 return pending_remote_description_ ? pending_remote_description_.get()
3630 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003631}
3632
deadbeeffe4a8a42016-12-20 17:56:17 -08003633const SessionDescriptionInterface* PeerConnection::current_local_description()
3634 const {
Steve Anton75737c02017-11-06 10:37:17 -08003635 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003636}
3637
3638const SessionDescriptionInterface* PeerConnection::current_remote_description()
3639 const {
Steve Anton75737c02017-11-06 10:37:17 -08003640 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003641}
3642
3643const SessionDescriptionInterface* PeerConnection::pending_local_description()
3644 const {
Steve Anton75737c02017-11-06 10:37:17 -08003645 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003646}
3647
3648const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3649 const {
Steve Anton75737c02017-11-06 10:37:17 -08003650 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003651}
3652
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003653void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003654 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003655 // Update stats here so that we have the most recent stats for tracks and
3656 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003657 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003658
Steve Anton75737c02017-11-06 10:37:17 -08003659 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003660 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003661
Mirko Bonadei739baf02019-01-27 17:29:42 +01003662 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003663 transceiver->Stop();
3664 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003665
3666 // Ensure that all asynchronous stats requests are completed before destroying
3667 // the transport controller below.
3668 if (stats_collector_) {
3669 stats_collector_->WaitForPendingRequest();
3670 }
3671
3672 // Don't destroy BaseChannels until after stats has been cleaned up so that
3673 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003674 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003675
Qingsi Wang93a84392018-01-30 17:13:09 -08003676 // The event log is used in the transport controller, which must be outlived
3677 // by the former. CreateOffer by the peer connection is implemented
3678 // asynchronously and if the peer connection is closed without resetting the
3679 // WebRTC session description factory, the session description factory would
3680 // call the transport controller.
3681 webrtc_session_desc_factory_.reset();
3682 transport_controller_.reset();
3683
deadbeef42a42632017-03-10 15:18:00 -08003684 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003685 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3686 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003687
Steve Anton978b8762017-09-29 12:15:02 -07003688 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003689 call_.reset();
3690 // The event log must outlive call (and any other object that uses it).
3691 event_log_.reset();
3692 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003693 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003694 // The .h file says that observer can be discarded after close() returns.
3695 // Make sure this is true.
3696 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003697}
3698
Steve Antonad182762018-09-05 20:22:40 +00003699void PeerConnection::OnMessage(rtc::Message* msg) {
3700 switch (msg->message_id) {
3701 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3702 SetSessionDescriptionMsg* param =
3703 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3704 param->observer->OnSuccess();
3705 delete param;
3706 break;
3707 }
3708 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3709 SetSessionDescriptionMsg* param =
3710 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3711 param->observer->OnFailure(std::move(param->error));
3712 delete param;
3713 break;
3714 }
3715 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3716 CreateSessionDescriptionMsg* param =
3717 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3718 param->observer->OnFailure(std::move(param->error));
3719 delete param;
3720 break;
3721 }
3722 case MSG_GETSTATS: {
3723 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3724 StatsReports reports;
3725 stats_->GetStats(param->track, &reports);
3726 param->observer->OnComplete(reports);
3727 delete param;
3728 break;
3729 }
3730 case MSG_FREE_DATACHANNELS: {
3731 sctp_data_channels_to_free_.clear();
3732 break;
3733 }
3734 case MSG_REPORT_USAGE_PATTERN: {
3735 ReportUsagePattern();
3736 break;
3737 }
3738 default:
3739 RTC_NOTREACHED() << "Not implemented";
3740 break;
3741 }
3742}
3743
Steve Antonafb0bb72018-02-20 11:35:37 -08003744cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3745 RTC_DCHECK(!IsUnifiedPlan());
3746 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3747 GetAudioTransceiver()->internal()->channel());
3748 if (voice_channel) {
3749 return voice_channel->media_channel();
3750 } else {
3751 return nullptr;
3752 }
3753}
3754
3755cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3756 RTC_DCHECK(!IsUnifiedPlan());
3757 auto* video_channel = static_cast<cricket::VideoChannel*>(
3758 GetVideoTransceiver()->internal()->channel());
3759 if (video_channel) {
3760 return video_channel->media_channel();
3761 } else {
3762 return nullptr;
3763 }
3764}
3765
Steve Anton4171afb2017-11-20 10:20:22 -08003766void PeerConnection::CreateAudioReceiver(
3767 MediaStreamInterface* stream,
3768 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003769 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3770 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003771 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3772 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003773 auto* audio_receiver = new AudioRtpReceiver(
3774 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003775 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003776 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3777 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3778 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003779 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003780 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003781 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003782}
3783
Steve Anton4171afb2017-11-20 10:20:22 -08003784void PeerConnection::CreateVideoReceiver(
3785 MediaStreamInterface* stream,
3786 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003787 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3788 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003789 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3790 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003791 auto* video_receiver = new VideoRtpReceiver(
3792 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003793 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003794 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3795 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3796 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003797 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003798 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003799 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003800}
3801
deadbeef70ab1a12015-09-28 16:53:55 -07003802// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3803// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003804rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003805 const RtpSenderInfo& remote_sender_info) {
3806 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3807 if (!receiver) {
3808 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3809 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003810 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003811 }
Steve Anton4171afb2017-11-20 10:20:22 -08003812 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3813 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3814 } else {
3815 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3816 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003817 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003818}
3819
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003820void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3821 MediaStreamInterface* stream) {
3822 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003823 RTC_DCHECK(track);
3824 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003825 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003826 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003827 // We already have a sender for this track, so just change the stream_id
3828 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003829 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003830 return;
3831 }
3832
3833 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003834 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003835 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003836 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003837 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003838 // If the sender has already been configured in SDP, we call SetSsrc,
3839 // which will connect the sender to the underlying transport. This can
3840 // occur if a local session description that contains the ID of the sender
3841 // is set before AddStream is called. It can also occur if the local
3842 // session description is not changed and RemoveStream is called, and
3843 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003844 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003845 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003846 if (sender_info) {
3847 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003848 }
3849}
3850
3851// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3852// indefinitely, when we have unified plan SDP.
3853void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3854 MediaStreamInterface* stream) {
3855 RTC_DCHECK(!IsClosed());
3856 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003857 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003858 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3859 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003860 return;
3861 }
Steve Anton4171afb2017-11-20 10:20:22 -08003862 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003863}
3864
3865void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3866 MediaStreamInterface* stream) {
3867 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003868 RTC_DCHECK(track);
3869 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003870 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003871 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003872 // We already have a sender for this track, so just change the stream_id
3873 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003874 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003875 return;
3876 }
3877
3878 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003879 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003880 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003881 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003882 GetVideoTransceiver()->internal()->AddSender(new_sender);
3883 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003884 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003885 if (sender_info) {
3886 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003887 }
3888}
3889
3890void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3891 MediaStreamInterface* stream) {
3892 RTC_DCHECK(!IsClosed());
3893 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003894 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003895 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3896 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003897 return;
3898 }
Steve Anton4171afb2017-11-20 10:20:22 -08003899 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003900}
3901
Steve Antonba818672017-11-06 10:21:57 -08003902void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003903 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003904 if (ice_connection_state_ == new_state) {
3905 return;
3906 }
3907
deadbeefcbecd352015-09-23 11:50:27 -07003908 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003909 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003910 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003911 return;
3912 }
Steve Antonba818672017-11-06 10:21:57 -08003913
Mirko Bonadei675513b2017-11-09 11:09:25 +01003914 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3915 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003916 RTC_DCHECK(ice_connection_state_ !=
3917 PeerConnectionInterface::kIceConnectionClosed);
3918
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003919 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003920 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003921}
3922
Alex Loiko9289eda2018-11-23 16:18:59 +00003923void PeerConnection::SetStandardizedIceConnectionState(
3924 PeerConnectionInterface::IceConnectionState new_state) {
3925 RTC_DCHECK(signaling_thread()->IsCurrent());
3926 if (standardized_ice_connection_state_ == new_state)
3927 return;
3928 if (IsClosed())
3929 return;
3930 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003931 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003932}
3933
Jonas Olsson635474e2018-10-18 15:58:17 +02003934void PeerConnection::SetConnectionState(
3935 PeerConnectionInterface::PeerConnectionState new_state) {
3936 RTC_DCHECK(signaling_thread()->IsCurrent());
3937 if (connection_state_ == new_state)
3938 return;
3939 if (IsClosed())
3940 return;
3941 connection_state_ = new_state;
3942 Observer()->OnConnectionChange(new_state);
3943}
3944
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003945void PeerConnection::OnIceGatheringChange(
3946 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003947 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003948 if (IsClosed()) {
3949 return;
3950 }
3951 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003952 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003953}
3954
jbauch81bf7b02017-03-25 08:31:12 -07003955void PeerConnection::OnIceCandidate(
3956 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003957 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003958 if (IsClosed()) {
3959 return;
3960 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003961 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003962 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3963 candidate->candidate().address().IsPrivateIP()) {
3964 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3965 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003966 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003967}
3968
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003969void PeerConnection::OnIceCandidatesRemoved(
3970 const std::vector<cricket::Candidate>& candidates) {
3971 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003972 if (IsClosed()) {
3973 return;
3974 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003975 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003976}
3977
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003978void PeerConnection::ChangeSignalingState(
3979 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003980 RTC_DCHECK(signaling_thread()->IsCurrent());
3981 if (signaling_state_ == signaling_state) {
3982 return;
3983 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003984 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3985 << GetSignalingStateString(signaling_state_)
3986 << " New state: "
3987 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003988 signaling_state_ = signaling_state;
3989 if (signaling_state == kClosed) {
3990 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003991 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003992 standardized_ice_connection_state_ =
3993 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003994 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3995 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003996 if (ice_gathering_state_ != kIceGatheringComplete) {
3997 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003998 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003999 }
4000 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004001 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004002}
4003
deadbeefeb459812015-12-15 19:24:43 -08004004void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4005 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004006 if (IsClosed()) {
4007 return;
4008 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004009 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004010 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004011}
4012
deadbeefeb459812015-12-15 19:24:43 -08004013void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4014 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004015 if (IsClosed()) {
4016 return;
4017 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004018 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004019 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004020}
4021
4022void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4023 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004024 if (IsClosed()) {
4025 return;
4026 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004027 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004028 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004029}
4030
4031void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4032 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004033 if (IsClosed()) {
4034 return;
4035 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004036 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004037 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004038}
4039
Henrik Boström31638672017-11-23 17:48:32 +01004040void PeerConnection::PostSetSessionDescriptionSuccess(
4041 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004042 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4043 signaling_thread()->Post(RTC_FROM_HERE, this,
4044 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004045}
4046
deadbeefab9b2d12015-10-14 11:33:11 -07004047void PeerConnection::PostSetSessionDescriptionFailure(
4048 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004049 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004050 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004051 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4052 msg->error = std::move(error);
4053 signaling_thread()->Post(RTC_FROM_HERE, this,
4054 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004055}
4056
4057void PeerConnection::PostCreateSessionDescriptionFailure(
4058 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004059 RTCError error) {
4060 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004061 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4062 msg->error = std::move(error);
4063 signaling_thread()->Post(RTC_FROM_HERE, this,
4064 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004065}
4066
zhihuang1c378ed2017-08-17 14:10:50 -07004067void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004068 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004069 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004070 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004071
Steve Antondcc3c022017-12-22 16:02:54 -08004072 if (IsUnifiedPlan()) {
4073 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4074 } else {
4075 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4076 }
4077
Steve Antonfa2260d2017-12-28 16:38:23 -08004078 // Intentionally unset the data channel type for RTP data channel with the
4079 // second condition. Otherwise the RTP data channels would be successfully
4080 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4081 // when building with chromium. We want to leave RTP data channels broken, so
4082 // people won't try to use them.
4083 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4084 session_options->data_channel_type = data_channel_type();
4085 }
4086
Steve Antondcc3c022017-12-22 16:02:54 -08004087 // Apply ICE restart flag and renomination flag.
4088 for (auto& options : session_options->media_description_options) {
4089 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4090 options.transport_options.enable_ice_renomination =
4091 configuration_.enable_ice_renomination;
4092 }
4093
4094 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004095 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004096 session_options->pooled_ice_credentials =
4097 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4098 RTC_FROM_HERE,
4099 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4100 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004101 session_options->offer_extmap_allow_mixed =
4102 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004103}
4104
4105void PeerConnection::GetOptionsForPlanBOffer(
4106 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4107 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004108 // Figure out transceiver directional preferences.
4109 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4110 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4111
4112 // By default, generate sendrecv/recvonly m= sections.
4113 bool recv_audio = true;
4114 bool recv_video = true;
4115
4116 // By default, only offer a new m= section if we have media to send with it.
4117 bool offer_new_audio_description = send_audio;
4118 bool offer_new_video_description = send_video;
4119 bool offer_new_data_description = HasDataChannels();
4120
4121 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004122 if (offer_answer_options.offer_to_receive_audio !=
4123 RTCOfferAnswerOptions::kUndefined) {
4124 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004125 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004126 offer_new_audio_description ||
4127 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004128 }
Steve Antondcc3c022017-12-22 16:02:54 -08004129 if (offer_answer_options.offer_to_receive_video !=
4130 RTCOfferAnswerOptions::kUndefined) {
4131 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004132 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004133 offer_new_video_description ||
4134 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004135 }
4136
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004137 absl::optional<size_t> audio_index;
4138 absl::optional<size_t> video_index;
4139 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004140 // If a current description exists, generate m= sections in the same order,
4141 // using the first audio/video/data section that appears and rejecting
4142 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004143 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004144 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004145 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004146 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4147 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4148 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004149 }
4150
zhihuang1c378ed2017-08-17 14:10:50 -07004151 // Add audio/video/data m= sections to the end if needed.
4152 if (!audio_index && offer_new_audio_description) {
4153 session_options->media_description_options.push_back(
4154 cricket::MediaDescriptionOptions(
4155 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004156 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4157 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004158 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004159 }
zhihuang1c378ed2017-08-17 14:10:50 -07004160 if (!video_index && offer_new_video_description) {
4161 session_options->media_description_options.push_back(
4162 cricket::MediaDescriptionOptions(
4163 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004164 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4165 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004166 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004167 }
zhihuang1c378ed2017-08-17 14:10:50 -07004168 if (!data_index && offer_new_data_description) {
4169 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004170 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004171 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004172 }
4173
4174 cricket::MediaDescriptionOptions* audio_media_description_options =
4175 !audio_index ? nullptr
4176 : &session_options->media_description_options[*audio_index];
4177 cricket::MediaDescriptionOptions* video_media_description_options =
4178 !video_index ? nullptr
4179 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004180
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004181 AddPlanBRtpSenderOptions(GetSendersInternal(),
4182 audio_media_description_options,
4183 video_media_description_options,
4184 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004185}
4186
Steve Antondcc3c022017-12-22 16:02:54 -08004187static cricket::MediaDescriptionOptions
4188GetMediaDescriptionOptionsForTransceiver(
4189 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4190 transceiver,
4191 const std::string& mid) {
4192 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004193 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004194 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004195 // This behavior is specified in JSEP. The gist is that:
4196 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4197 // sendrecv.
4198 // 2. If the MSID is included, then it must be included in any subsequent
4199 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004200 if (transceiver->stopped() ||
4201 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4202 !transceiver->internal()->has_ever_been_used_to_send())) {
4203 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004204 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004205
4206 cricket::SenderOptions sender_options;
4207 sender_options.track_id = transceiver->sender()->id();
4208 sender_options.stream_ids = transceiver->sender()->stream_ids();
4209
4210 // The following sets up RIDs and Simulcast.
4211 // RIDs are included if Simulcast is requested or if any RID was specified.
4212 RtpParameters send_parameters = transceiver->sender()->GetParameters();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004213 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4214 send_parameters.encodings.end(),
4215 [](const RtpEncodingParameters& encoding) {
4216 return !encoding.rid.empty();
4217 });
4218
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004219 std::vector<RidDescription> send_rids;
4220 SimulcastLayerList send_layers;
4221 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4222 if (encoding.rid.empty()) {
4223 continue;
4224 }
4225 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4226 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4227 }
4228
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004229 if (has_rids) {
4230 sender_options.rids = send_rids;
4231 }
4232
4233 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004234 // When RIDs are configured, we must set num_sim_layers to 0 to.
4235 // Otherwise, num_sim_layers must be 1 because either there is no
4236 // simulcast, or simulcast is acheived by munging the SDP.
4237 sender_options.num_sim_layers = has_rids ? 0 : 1;
4238 media_description_options.sender_options.push_back(sender_options);
4239
Steve Antondcc3c022017-12-22 16:02:54 -08004240 return media_description_options;
4241}
4242
Steve Anton5c72e712018-12-10 14:25:30 -08004243// Returns the ContentInfo at mline index |i|, or null if none exists.
4244static const ContentInfo* GetContentByIndex(
4245 const SessionDescriptionInterface* sdesc,
4246 size_t i) {
4247 if (!sdesc) {
4248 return nullptr;
4249 }
4250 const ContentInfos& contents = sdesc->description()->contents();
4251 return (i < contents.size() ? &contents[i] : nullptr);
4252}
4253
Steve Antondcc3c022017-12-22 16:02:54 -08004254void PeerConnection::GetOptionsForUnifiedPlanOffer(
4255 const RTCOfferAnswerOptions& offer_answer_options,
4256 cricket::MediaSessionOptions* session_options) {
4257 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4258 // Offers) and 5.2.2 (Subsequent Offers).
4259 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4260 const ContentInfos& local_contents =
4261 (local_description() ? local_description()->description()->contents()
4262 : ContentInfos());
4263 const ContentInfos& remote_contents =
4264 (remote_description() ? remote_description()->description()->contents()
4265 : ContentInfos());
4266 // The mline indices that can be recycled. New transceivers should reuse these
4267 // slots first.
4268 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004269 // First, go through each media section that exists in either the local or
4270 // remote description and generate a media section in this offer for the
4271 // associated transceiver. If a media section can be recycled, generate a
4272 // default, rejected media section here that can be later overwritten.
4273 for (size_t i = 0;
4274 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4275 // Either |local_content| or |remote_content| is non-null.
4276 const ContentInfo* local_content =
4277 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004278 const ContentInfo* current_local_content =
4279 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004280 const ContentInfo* remote_content =
4281 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004282 const ContentInfo* current_remote_content =
4283 GetContentByIndex(current_remote_description(), i);
4284 bool had_been_rejected =
4285 (current_local_content && current_local_content->rejected) ||
4286 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004287 const std::string& mid =
4288 (local_content ? local_content->name : remote_content->name);
4289 cricket::MediaType media_type =
4290 (local_content ? local_content->media_description()->type()
4291 : remote_content->media_description()->type());
4292 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4293 media_type == cricket::MEDIA_TYPE_VIDEO) {
4294 auto transceiver = GetAssociatedTransceiver(mid);
4295 RTC_CHECK(transceiver);
4296 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004297 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004298 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004299 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004300 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4301 RtpTransceiverDirection::kInactive,
4302 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004303 recycleable_mline_indices.push(i);
4304 } else {
4305 session_options->media_description_options.push_back(
4306 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4307 // CreateOffer shouldn't really cause any state changes in
4308 // PeerConnection, but we need a way to match new transceivers to new
4309 // media sections in SetLocalDescription and JSEP specifies this is done
4310 // by recording the index of the media section generated for the
4311 // transceiver in the offer.
4312 transceiver->internal()->set_mline_index(i);
4313 }
4314 } else {
4315 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004316 RTC_CHECK(GetDataMid());
4317 if (had_been_rejected || mid != *GetDataMid()) {
4318 session_options->media_description_options.push_back(
4319 GetMediaDescriptionOptionsForRejectedData(mid));
4320 } else {
4321 session_options->media_description_options.push_back(
4322 GetMediaDescriptionOptionsForActiveData(mid));
4323 }
Steve Antondcc3c022017-12-22 16:02:54 -08004324 }
4325 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004326
Steve Antondcc3c022017-12-22 16:02:54 -08004327 // Next, look for transceivers that are newly added (that is, are not stopped
4328 // and not associated). Reuse media sections marked as recyclable first,
4329 // otherwise append to the end of the offer. New media sections should be
4330 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004331 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004332 if (transceiver->mid() || transceiver->stopped()) {
4333 continue;
4334 }
4335 size_t mline_index;
4336 if (!recycleable_mline_indices.empty()) {
4337 mline_index = recycleable_mline_indices.front();
4338 recycleable_mline_indices.pop();
4339 session_options->media_description_options[mline_index] =
4340 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004341 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004342 } else {
4343 mline_index = session_options->media_description_options.size();
4344 session_options->media_description_options.push_back(
4345 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004346 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004347 }
4348 // See comment above for why CreateOffer changes the transceiver's state.
4349 transceiver->internal()->set_mline_index(mline_index);
4350 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004351 // Lastly, add a m-section if we have local data channels and an m section
4352 // does not already exist.
4353 if (!GetDataMid() && HasDataChannels()) {
4354 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004355 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004356 }
Steve Antondcc3c022017-12-22 16:02:54 -08004357}
4358
4359void PeerConnection::GetOptionsForAnswer(
4360 const RTCOfferAnswerOptions& offer_answer_options,
4361 cricket::MediaSessionOptions* session_options) {
4362 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4363
4364 if (IsUnifiedPlan()) {
4365 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4366 } else {
4367 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4368 }
4369
Steve Antonfa2260d2017-12-28 16:38:23 -08004370 // Intentionally unset the data channel type for RTP data channel. Otherwise
4371 // the RTP data channels would be successfully negotiated by default and the
4372 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4373 // We want to leave RTP data channels broken, so people won't try to use them.
4374 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4375 session_options->data_channel_type = data_channel_type();
4376 }
4377
Steve Antondcc3c022017-12-22 16:02:54 -08004378 // Apply ICE renomination flag.
4379 for (auto& options : session_options->media_description_options) {
4380 options.transport_options.enable_ice_renomination =
4381 configuration_.enable_ice_renomination;
4382 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004383
4384 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004385 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004386 session_options->pooled_ice_credentials =
4387 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4388 RTC_FROM_HERE,
4389 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4390 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004391}
4392
Steve Antondcc3c022017-12-22 16:02:54 -08004393void PeerConnection::GetOptionsForPlanBAnswer(
4394 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004395 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004396 // Figure out transceiver directional preferences.
4397 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4398 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4399
4400 // By default, generate sendrecv/recvonly m= sections. The direction is also
4401 // restricted by the direction in the offer.
4402 bool recv_audio = true;
4403 bool recv_video = true;
4404
4405 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004406 if (offer_answer_options.offer_to_receive_audio !=
4407 RTCOfferAnswerOptions::kUndefined) {
4408 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004409 }
Steve Antondcc3c022017-12-22 16:02:54 -08004410 if (offer_answer_options.offer_to_receive_video !=
4411 RTCOfferAnswerOptions::kUndefined) {
4412 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004413 }
4414
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004415 absl::optional<size_t> audio_index;
4416 absl::optional<size_t> video_index;
4417 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004418
4419 // Generate m= sections that match those in the offer.
4420 // Note that mediasession.cc will handle intersection our preferred
4421 // direction with the offered direction.
4422 GenerateMediaDescriptionOptions(
4423 remote_description(),
4424 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4425 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4426 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004427
4428 cricket::MediaDescriptionOptions* audio_media_description_options =
4429 !audio_index ? nullptr
4430 : &session_options->media_description_options[*audio_index];
4431 cricket::MediaDescriptionOptions* video_media_description_options =
4432 !video_index ? nullptr
4433 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004434
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004435 AddPlanBRtpSenderOptions(GetSendersInternal(),
4436 audio_media_description_options,
4437 video_media_description_options,
4438 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004439}
zhihuangaf388472016-11-02 16:49:48 -07004440
Steve Antondcc3c022017-12-22 16:02:54 -08004441void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4442 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4443 cricket::MediaSessionOptions* session_options) {
4444 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4445 // Answers) and 5.3.2 (Subsequent Answers).
4446 RTC_DCHECK(remote_description());
4447 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4448 for (const ContentInfo& content :
4449 remote_description()->description()->contents()) {
4450 cricket::MediaType media_type = content.media_description()->type();
4451 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4452 media_type == cricket::MEDIA_TYPE_VIDEO) {
4453 auto transceiver = GetAssociatedTransceiver(content.name);
4454 RTC_CHECK(transceiver);
4455 session_options->media_description_options.push_back(
4456 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4457 } else {
4458 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004459 // Reject all data sections if data channels are disabled.
4460 // Reject a data section if it has already been rejected.
4461 // Reject all data sections except for the first one.
4462 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4463 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004464 session_options->media_description_options.push_back(
4465 GetMediaDescriptionOptionsForRejectedData(content.name));
4466 } else {
4467 session_options->media_description_options.push_back(
4468 GetMediaDescriptionOptionsForActiveData(content.name));
4469 }
Steve Antondcc3c022017-12-22 16:02:54 -08004470 }
4471 }
htaa2a49d92016-03-04 02:51:39 -08004472}
4473
zhihuang1c378ed2017-08-17 14:10:50 -07004474void PeerConnection::GenerateMediaDescriptionOptions(
4475 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004476 RtpTransceiverDirection audio_direction,
4477 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004478 absl::optional<size_t>* audio_index,
4479 absl::optional<size_t>* video_index,
4480 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004481 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004482 for (const cricket::ContentInfo& content :
4483 session_desc->description()->contents()) {
4484 if (IsAudioContent(&content)) {
4485 // If we already have an audio m= section, reject this extra one.
4486 if (*audio_index) {
4487 session_options->media_description_options.push_back(
4488 cricket::MediaDescriptionOptions(
4489 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004490 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004491 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004492 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004493 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004494 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4495 content.name, audio_direction,
4496 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004497 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004498 }
4499 } else if (IsVideoContent(&content)) {
4500 // If we already have an video m= section, reject this extra one.
4501 if (*video_index) {
4502 session_options->media_description_options.push_back(
4503 cricket::MediaDescriptionOptions(
4504 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004505 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004506 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004507 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004508 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004509 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4510 content.name, video_direction,
4511 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004512 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004513 }
4514 } else {
4515 RTC_DCHECK(IsDataContent(&content));
4516 // If we already have an data m= section, reject this extra one.
4517 if (*data_index) {
4518 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004519 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004520 } else {
4521 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004522 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004523 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004524 }
4525 }
htaa2a49d92016-03-04 02:51:39 -08004526 }
deadbeefab9b2d12015-10-14 11:33:11 -07004527}
4528
Steve Antonfa2260d2017-12-28 16:38:23 -08004529cricket::MediaDescriptionOptions
4530PeerConnection::GetMediaDescriptionOptionsForActiveData(
4531 const std::string& mid) const {
4532 // Direction for data sections is meaningless, but legacy endpoints might
4533 // expect sendrecv.
4534 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4535 RtpTransceiverDirection::kSendRecv,
4536 /*stopped=*/false);
4537 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4538 return options;
4539}
4540
4541cricket::MediaDescriptionOptions
4542PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4543 const std::string& mid) const {
4544 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4545 RtpTransceiverDirection::kInactive,
4546 /*stopped=*/true);
4547 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4548 return options;
4549}
4550
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004551absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004552 switch (data_channel_type_) {
4553 case cricket::DCT_RTP:
4554 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004555 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004556 }
4557 return rtp_data_channel_->content_name();
4558 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004559 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004560 case cricket::DCT_MEDIA_TRANSPORT:
4561 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004562 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004563 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004564 }
4565}
4566
Steve Anton4171afb2017-11-20 10:20:22 -08004567void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4568 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4569 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004570 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004571}
4572
Steve Anton4171afb2017-11-20 10:20:22 -08004573void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004574 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004575 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004576 cricket::MediaType media_type,
4577 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004578 RTC_DCHECK(!IsUnifiedPlan());
4579
Steve Anton4171afb2017-11-20 10:20:22 -08004580 std::vector<RtpSenderInfo>* current_senders =
4581 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004582
Steve Anton4171afb2017-11-20 10:20:22 -08004583 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004584 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004585 for (auto sender_it = current_senders->begin();
4586 sender_it != current_senders->end();
4587 /* incremented manually */) {
4588 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004589 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004590 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004591 std::string params_stream_id;
4592 if (params) {
4593 params_stream_id =
4594 (!params->first_stream_id().empty() ? params->first_stream_id()
4595 : kDefaultStreamId);
4596 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004597 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004598 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004599 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004600 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004601 sender_exists) {
4602 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004603 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004604 OnRemoteSenderRemoved(info, media_type);
4605 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004606 }
4607 }
4608
Steve Anton4171afb2017-11-20 10:20:22 -08004609 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004610 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004611 if (!params.has_ssrcs()) {
4612 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4613 // sender, this means it is coming from a Unified Plan endpoint,so we just
4614 // create a default.
4615 default_sender_needed = true;
4616 break;
4617 }
4618
Seth Hampson845e8782018-03-02 11:34:10 -08004619 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004620 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004621 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4622 // not supported in Plan B, we just take the first here and create the
4623 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004624 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004625 (!params.first_stream_id().empty() ? params.first_stream_id()
4626 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004627 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004628 uint32_t ssrc = params.first_ssrc();
4629
4630 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004631 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004632 if (!stream) {
4633 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004634 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004635 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004636 remote_streams_->AddStream(stream);
4637 new_streams->AddStream(stream);
4638 }
4639
Steve Anton4171afb2017-11-20 10:20:22 -08004640 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004641 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004642 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004643 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004644 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004645 }
4646 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004647
Steve Anton4171afb2017-11-20 10:20:22 -08004648 // Add default sender if necessary.
4649 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004650 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004651 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004652 if (!default_stream) {
4653 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004654 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004655 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004656 remote_streams_->AddStream(default_stream);
4657 new_streams->AddStream(default_stream);
4658 }
Steve Anton4171afb2017-11-20 10:20:22 -08004659 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4660 ? kDefaultAudioSenderId
4661 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004662 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004663 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004664 if (!default_sender_info) {
4665 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004666 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004667 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004668 }
4669 }
deadbeefab9b2d12015-10-14 11:33:11 -07004670}
4671
Steve Anton4171afb2017-11-20 10:20:22 -08004672void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4673 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004674 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4675 << " receiver for track_id=" << sender_info.sender_id
4676 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004677
Steve Anton3d954a62018-04-02 11:27:23 -07004678 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004679 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004680 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004681 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004682 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004683 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004684 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004685 }
4686}
4687
Steve Anton4171afb2017-11-20 10:20:22 -08004688void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4689 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004690 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4691 << " receiver for track_id=" << sender_info.sender_id
4692 << " and stream_id=" << sender_info.stream_id;
4693
Seth Hampson845e8782018-03-02 11:34:10 -08004694 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004695
Henrik Boström933d8b02017-10-10 10:05:16 -07004696 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004697 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004698 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4699 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004700 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004701 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004702 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004703 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004704 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004705 }
4706 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004707 // Stopping or destroying a VideoRtpReceiver will end the
4708 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004709 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004710 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004711 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004712 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004713 // There's no guarantee the track is still available, e.g. the track may
4714 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004715 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004716 }
4717 } else {
nisseede5da42017-01-12 05:15:36 -08004718 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004719 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004720 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004721 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004722 }
deadbeefab9b2d12015-10-14 11:33:11 -07004723}
4724
4725void PeerConnection::UpdateEndedRemoteMediaStreams() {
4726 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4727 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4728 MediaStreamInterface* stream = remote_streams_->at(i);
4729 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4730 streams_to_remove.push_back(stream);
4731 }
4732 }
4733
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004734 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004735 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004736 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004737 }
4738}
4739
Steve Anton4171afb2017-11-20 10:20:22 -08004740void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004741 const std::vector<cricket::StreamParams>& streams,
4742 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004743 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004744
Seth Hampson845e8782018-03-02 11:34:10 -08004745 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004746 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004747 for (auto sender_it = current_senders->begin();
4748 sender_it != current_senders->end();
4749 /* incremented manually */) {
4750 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004751 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004752 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4753 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004754 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004755 OnLocalSenderRemoved(info, media_type);
4756 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004757 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004758 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004759 }
4760 }
4761
Steve Anton4171afb2017-11-20 10:20:22 -08004762 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004763 for (const cricket::StreamParams& params : streams) {
4764 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004765 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004766 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004767 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004768 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004769 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004770 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004771 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004772 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004773 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004774 }
4775 }
4776}
4777
Steve Anton4171afb2017-11-20 10:20:22 -08004778void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4779 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004780 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004781 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004782 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004783 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4784 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004785 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004786 return;
4787 }
4788
deadbeeffac06552015-11-25 11:26:01 -08004789 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004790 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004791 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004792 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004793 }
deadbeeffac06552015-11-25 11:26:01 -08004794
Seth Hampson5b4f0752018-04-02 16:31:36 -07004795 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004796 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004797}
4798
Steve Anton4171afb2017-11-20 10:20:22 -08004799void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4800 cricket::MediaType media_type) {
4801 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004802 if (!sender) {
4803 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004804 // SessionDescriptions has been renegotiated.
4805 return;
4806 }
deadbeeffac06552015-11-25 11:26:01 -08004807
4808 // A sender has been removed from the SessionDescription but it's still
4809 // associated with the PeerConnection. This only occurs if the SDP doesn't
4810 // match with the calls to CreateSender, AddStream and RemoveStream.
4811 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004812 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004813 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004814 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004815 }
deadbeeffac06552015-11-25 11:26:01 -08004816
Steve Anton4171afb2017-11-20 10:20:22 -08004817 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004818}
4819
4820void PeerConnection::UpdateLocalRtpDataChannels(
4821 const cricket::StreamParamsVec& streams) {
4822 std::vector<std::string> existing_channels;
4823
4824 // Find new and active data channels.
4825 for (const cricket::StreamParams& params : streams) {
4826 // |it->sync_label| is actually the data channel label. The reason is that
4827 // we use the same naming of data channels as we do for
4828 // MediaStreams and Tracks.
4829 // For MediaStreams, the sync_label is the MediaStream label and the
4830 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004831 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004832 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004833 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004834 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004835 continue;
4836 }
4837 // Set the SSRC the data channel should use for sending.
4838 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4839 existing_channels.push_back(data_channel_it->first);
4840 }
4841
4842 UpdateClosingRtpDataChannels(existing_channels, true);
4843}
4844
4845void PeerConnection::UpdateRemoteRtpDataChannels(
4846 const cricket::StreamParamsVec& streams) {
4847 std::vector<std::string> existing_channels;
4848
4849 // Find new and active data channels.
4850 for (const cricket::StreamParams& params : streams) {
4851 // The data channel label is either the mslabel or the SSRC if the mslabel
4852 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004853 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004854 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004855 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004856 auto data_channel_it = rtp_data_channels_.find(label);
4857 if (data_channel_it == rtp_data_channels_.end()) {
4858 // This is a new data channel.
4859 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4860 } else {
4861 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4862 }
4863 existing_channels.push_back(label);
4864 }
4865
4866 UpdateClosingRtpDataChannels(existing_channels, false);
4867}
4868
4869void PeerConnection::UpdateClosingRtpDataChannels(
4870 const std::vector<std::string>& active_channels,
4871 bool is_local_update) {
4872 auto it = rtp_data_channels_.begin();
4873 while (it != rtp_data_channels_.end()) {
4874 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004875 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004876 ++it;
4877 continue;
4878 }
4879
4880 if (is_local_update) {
4881 data_channel->SetSendSsrc(0);
4882 } else {
4883 data_channel->RemotePeerRequestClose();
4884 }
4885
4886 if (data_channel->state() == DataChannel::kClosed) {
4887 rtp_data_channels_.erase(it);
4888 it = rtp_data_channels_.begin();
4889 } else {
4890 ++it;
4891 }
4892 }
4893}
4894
4895void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4896 uint32_t remote_ssrc) {
4897 rtc::scoped_refptr<DataChannel> channel(
4898 InternalCreateDataChannel(label, nullptr));
4899 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004900 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004901 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004902 return;
4903 }
4904 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004905 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4906 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004907 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004908}
4909
4910rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4911 const std::string& label,
4912 const InternalDataChannelInit* config) {
4913 if (IsClosed()) {
4914 return nullptr;
4915 }
Steve Anton75737c02017-11-06 10:37:17 -08004916 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004917 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004918 << "InternalCreateDataChannel: Data is not supported in this call.";
4919 return nullptr;
4920 }
4921 InternalDataChannelInit new_config =
4922 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004923 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004924 if (new_config.id < 0) {
4925 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004926 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004927 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004928 RTC_LOG(LS_ERROR)
4929 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004930 return nullptr;
4931 }
4932 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004933 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004934 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004935 return nullptr;
4936 }
4937 }
4938
Steve Anton75737c02017-11-06 10:37:17 -08004939 rtc::scoped_refptr<DataChannel> channel(
4940 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004941 if (!channel) {
4942 sid_allocator_.ReleaseSid(new_config.id);
4943 return nullptr;
4944 }
4945
4946 if (channel->data_channel_type() == cricket::DCT_RTP) {
4947 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004948 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4949 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004950 return nullptr;
4951 }
4952 rtp_data_channels_[channel->label()] = channel;
4953 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004954 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004955 sctp_data_channels_.push_back(channel);
4956 channel->SignalClosed.connect(this,
4957 &PeerConnection::OnSctpDataChannelClosed);
4958 }
4959
Steve Anton2d8609c2018-01-23 16:38:46 -08004960 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004961 return channel;
4962}
4963
4964bool PeerConnection::HasDataChannels() const {
4965 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4966}
4967
4968void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4969 for (const auto& channel : sctp_data_channels_) {
4970 if (channel->id() < 0) {
4971 int sid;
4972 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004973 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004974 continue;
4975 }
4976 channel->SetSctpSid(sid);
4977 }
4978 }
4979}
4980
4981void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004982 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004983 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4984 ++it) {
4985 if (it->get() == channel) {
4986 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004987 // After the closing procedure is done, it's safe to use this ID for
4988 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004989 sid_allocator_.ReleaseSid(channel->id());
4990 }
deadbeefbd292462015-12-14 18:15:29 -08004991 // Since this method is triggered by a signal from the DataChannel,
4992 // we can't free it directly here; we need to free it asynchronously.
4993 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004994 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004995 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4996 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004997 return;
4998 }
4999 }
5000}
5001
deadbeefab9b2d12015-10-14 11:33:11 -07005002void PeerConnection::OnDataChannelDestroyed() {
5003 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5004 // DataChannel may callback to us and try to modify the list.
5005 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5006 temp_rtp_dcs.swap(rtp_data_channels_);
5007 for (const auto& kv : temp_rtp_dcs) {
5008 kv.second->OnTransportChannelDestroyed();
5009 }
5010
5011 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5012 temp_sctp_dcs.swap(sctp_data_channels_);
5013 for (const auto& channel : temp_sctp_dcs) {
5014 channel->OnTransportChannelDestroyed();
5015 }
5016}
5017
5018void PeerConnection::OnDataChannelOpenMessage(
5019 const std::string& label,
5020 const InternalDataChannelInit& config) {
5021 rtc::scoped_refptr<DataChannel> channel(
5022 InternalCreateDataChannel(label, &config));
5023 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005024 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005025 return;
5026 }
5027
deadbeefa601f5c2016-06-06 14:27:39 -07005028 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5029 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005030 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005031 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005032}
5033
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005034bool PeerConnection::HandleOpenMessage_s(
5035 const cricket::ReceiveDataParams& params,
5036 const rtc::CopyOnWriteBuffer& buffer) {
5037 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5038 // Received OPEN message; parse and signal that a new data channel should
5039 // be created.
5040 std::string label;
5041 InternalDataChannelInit config;
5042 config.id = params.ssrc;
5043 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5044 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5045 << params.ssrc;
5046 return true;
5047 }
5048 config.open_handshake_role = InternalDataChannelInit::kAcker;
5049 OnDataChannelOpenMessage(label, config);
5050 return true;
5051 }
5052 return false;
5053}
5054
Steve Anton4171afb2017-11-20 10:20:22 -08005055rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5056PeerConnection::GetAudioTransceiver() const {
5057 // This method only works with Plan B SDP, where there is a single
5058 // audio/video transceiver.
5059 RTC_DCHECK(!IsUnifiedPlan());
5060 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005061 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005062 return transceiver;
5063 }
5064 }
5065 RTC_NOTREACHED();
5066 return nullptr;
5067}
5068
5069rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5070PeerConnection::GetVideoTransceiver() const {
5071 // This method only works with Plan B SDP, where there is a single
5072 // audio/video transceiver.
5073 RTC_DCHECK(!IsUnifiedPlan());
5074 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005075 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005076 return transceiver;
5077 }
5078 }
5079 RTC_NOTREACHED();
5080 return nullptr;
5081}
5082
5083// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5084// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005085bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005086 switch (type) {
5087 case cricket::MEDIA_TYPE_AUDIO:
5088 return !GetAudioTransceiver()->internal()->senders().empty();
5089 case cricket::MEDIA_TYPE_VIDEO:
5090 return !GetVideoTransceiver()->internal()->senders().empty();
5091 case cricket::MEDIA_TYPE_DATA:
5092 return false;
5093 }
5094 RTC_NOTREACHED();
5095 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005096}
5097
Steve Anton4171afb2017-11-20 10:20:22 -08005098rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5099PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005100 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005101 for (auto sender : transceiver->internal()->senders()) {
5102 if (sender->track() == track) {
5103 return sender;
5104 }
5105 }
5106 }
5107 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005108}
5109
Steve Anton4171afb2017-11-20 10:20:22 -08005110rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5111PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005112 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005113 for (auto sender : transceiver->internal()->senders()) {
5114 if (sender->id() == sender_id) {
5115 return sender;
5116 }
5117 }
5118 }
5119 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005120}
5121
Steve Anton4171afb2017-11-20 10:20:22 -08005122rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5123PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005124 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005125 for (auto receiver : transceiver->internal()->receivers()) {
5126 if (receiver->id() == receiver_id) {
5127 return receiver;
5128 }
5129 }
5130 }
5131 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005132}
5133
Steve Anton4171afb2017-11-20 10:20:22 -08005134std::vector<PeerConnection::RtpSenderInfo>*
5135PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5136 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5137 media_type == cricket::MEDIA_TYPE_VIDEO);
5138 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5139 ? &remote_audio_sender_infos_
5140 : &remote_video_sender_infos_;
5141}
5142
5143std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005144 cricket::MediaType media_type) {
5145 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5146 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005147 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5148 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005149}
5150
Steve Anton4171afb2017-11-20 10:20:22 -08005151const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5152 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005153 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005154 const std::string sender_id) const {
5155 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005156 if (sender_info.stream_id == stream_id &&
5157 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005158 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005159 }
5160 }
5161 return nullptr;
5162}
5163
5164DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5165 for (const auto& channel : sctp_data_channels_) {
5166 if (channel->id() == sid) {
5167 return channel;
5168 }
5169 }
5170 return nullptr;
5171}
5172
deadbeef91dd5672016-05-18 16:55:30 -07005173bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005174 const cricket::ServerAddresses& stun_servers,
5175 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005176 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005177 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005178 // To handle both internal and externally created port allocator, we will
5179 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005180 port_allocator_flags_ = port_allocator_->flags();
5181 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5182 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5183 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005184 // If the disable-IPv6 flag was specified, we'll not override it
5185 // by experiment.
5186 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005187 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005188 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5189 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005190 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005191 }
5192
zhihuangb09b3f92017-03-07 14:40:51 -08005193 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005194 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005195 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005196 }
5197
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005198 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005199 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005200 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005201 }
5202
honghaiz60347052016-05-31 18:29:12 -07005203 if (configuration.candidate_network_policy ==
5204 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005205 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005206 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005207 }
5208
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005209 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005210 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005211 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5212 }
5213
Qingsi Wanga2d60672018-04-11 16:57:45 -07005214 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005215 // No step delay is used while allocating ports.
5216 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5217 port_allocator_->set_candidate_filter(
5218 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005219 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005220
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005221 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005222 for (auto& turn_server : turn_servers_copy) {
5223 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005224 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005225 // Call this last since it may create pooled allocator sessions using the
5226 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005227 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005228 stun_servers, std::move(turn_servers_copy),
5229 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5230 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005231 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005232 return true;
5233}
5234
deadbeef91dd5672016-05-18 16:55:30 -07005235bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005236 const cricket::ServerAddresses& stun_servers,
5237 const std::vector<cricket::RelayServerConfig>& turn_servers,
5238 IceTransportsType type,
5239 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005240 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005241 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005242 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005243 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005244 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005245 // According to JSEP, after setLocalDescription, changing the candidate pool
5246 // size is not allowed, and changing the set of ICE servers will not result
5247 // in new candidates being gathered.
5248 if (local_description()) {
5249 port_allocator_->FreezeCandidatePool();
5250 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005251 // Add the custom tls turn servers if they exist.
5252 auto turn_servers_copy = turn_servers;
5253 for (auto& turn_server : turn_servers_copy) {
5254 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5255 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005256 // Call this last since it may create pooled allocator sessions using the
5257 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005258 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005259 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5260 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005261}
5262
Steve Antonba818672017-11-06 10:21:57 -08005263cricket::ChannelManager* PeerConnection::channel_manager() const {
5264 return factory_->channel_manager();
5265}
5266
Elad Alon99c3fe52017-10-13 16:29:40 +02005267bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005268 std::unique_ptr<RtcEventLogOutput> output,
5269 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005270 if (!event_log_) {
5271 return false;
5272 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005273 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005274}
5275
5276void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005277 if (event_log_) {
5278 event_log_->StopLogging();
5279 }
ivoc14d5dbe2016-07-04 07:06:55 -07005280}
nisseeaabdf62017-05-05 02:23:02 -07005281
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005282cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005283 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005284 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005285 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005286 if (channel && channel->content_name() == content_name) {
5287 return channel;
5288 }
Steve Anton75737c02017-11-06 10:37:17 -08005289 }
5290 if (rtp_data_channel() &&
5291 rtp_data_channel()->content_name() == content_name) {
5292 return rtp_data_channel();
5293 }
5294 return nullptr;
5295}
5296
5297bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005298 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005299 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005300 RTC_LOG(LS_INFO)
5301 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005302 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005303 return false;
5304 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005305 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005306 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005307 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005308 return false;
5309 }
5310
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005311 absl::optional<rtc::SSLRole> dtls_role;
5312 if (sctp_mid_) {
5313 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5314 } else if (is_caller_) {
5315 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5316 }
Zhi Huange830e682018-03-30 10:48:35 -07005317 if (dtls_role) {
5318 *role = *dtls_role;
5319 return true;
5320 }
5321 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005322}
5323
5324bool PeerConnection::GetSslRole(const std::string& content_name,
5325 rtc::SSLRole* role) {
5326 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005327 RTC_LOG(LS_INFO)
5328 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005329 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005330 return false;
5331 }
5332
Zhi Huange830e682018-03-30 10:48:35 -07005333 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5334 if (dtls_role) {
5335 *role = *dtls_role;
5336 return true;
5337 }
5338 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005339}
5340
Steve Antonf8470812017-12-04 10:46:21 -08005341void PeerConnection::SetSessionError(SessionError error,
5342 const std::string& error_desc) {
5343 RTC_DCHECK_RUN_ON(signaling_thread());
5344 if (error != session_error_) {
5345 session_error_ = error;
5346 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005347 }
5348}
5349
Zhi Huange830e682018-03-30 10:48:35 -07005350RTCError PeerConnection::UpdateSessionState(
5351 SdpType type,
5352 cricket::ContentSource source,
5353 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005354 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005355
5356 // If there's already a pending error then no state transition should happen.
5357 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005358 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005359
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005360 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005361 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005362 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005363 }
5364
5365 // Update the signaling state according to the specified state machine (see
5366 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005367 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005368 ChangeSignalingState(source == cricket::CS_LOCAL
5369 ? PeerConnectionInterface::kHaveLocalOffer
5370 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005371 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005372 ChangeSignalingState(source == cricket::CS_LOCAL
5373 ? PeerConnectionInterface::kHaveLocalPrAnswer
5374 : PeerConnectionInterface::kHaveRemotePrAnswer);
5375 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005376 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005377 ChangeSignalingState(PeerConnectionInterface::kStable);
5378 }
5379
5380 // Update internal objects according to the session description's media
5381 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005382 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005383 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005384 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005385 }
5386
Steve Anton8a006912017-12-04 15:25:56 -08005387 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005388}
5389
Steve Anton8a006912017-12-04 15:25:56 -08005390RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005391 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005392 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005393 const SessionDescriptionInterface* sdesc =
5394 (source == cricket::CS_LOCAL ? local_description()
5395 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005396 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005397
5398 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005399 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005400 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005401 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005402 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005403 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005404 continue;
5405 }
5406 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005407 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005408 if (!content_desc) {
5409 continue;
5410 }
5411 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005412 bool success = (source == cricket::CS_LOCAL)
5413 ? channel->SetLocalContent(content_desc, type, &error)
5414 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005415 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005416 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005417 }
5418 }
5419
5420 // If using the RtpDataChannel, push down the new SDP section for it too.
5421 if (rtp_data_channel_) {
5422 const ContentInfo* data_content =
5423 cricket::GetFirstDataContent(sdesc->description());
5424 if (data_content && !data_content->rejected) {
5425 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005426 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005427 if (data_desc) {
5428 std::string error;
5429 bool success =
5430 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005431 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005432 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005433 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005434 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005435 }
Steve Anton75737c02017-11-06 10:37:17 -08005436 }
5437 }
5438 }
Steve Antoned10bd92017-12-05 10:52:59 -08005439
Steve Anton75737c02017-11-06 10:37:17 -08005440 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5441 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5442 if (sctp_transport_ && local_description() && remote_description() &&
5443 cricket::GetFirstDataContent(local_description()->description()) &&
5444 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005445 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005446 RTC_FROM_HERE,
5447 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005448 if (!success) {
5449 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5450 "Failed to push down SCTP parameters.");
5451 }
Steve Anton75737c02017-11-06 10:37:17 -08005452 }
Steve Antoned10bd92017-12-05 10:52:59 -08005453
Steve Anton8a006912017-12-04 15:25:56 -08005454 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005455}
5456
5457bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5458 RTC_DCHECK(network_thread()->IsCurrent());
5459 RTC_DCHECK(local_description());
5460 RTC_DCHECK(remote_description());
5461 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5462 // When we support "max-message-size", that would also be pushed down here.
5463 return sctp_transport_->Start(
5464 GetSctpPort(local_description()->description()),
5465 GetSctpPort(remote_description()->description()));
5466}
5467
Steve Anton8a006912017-12-04 15:25:56 -08005468RTCError PeerConnection::PushdownTransportDescription(
5469 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005470 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005471 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005472
Zhi Huange830e682018-03-30 10:48:35 -07005473 if (source == cricket::CS_LOCAL) {
5474 const SessionDescriptionInterface* sdesc = local_description();
5475 RTC_DCHECK(sdesc);
5476 return transport_controller_->SetLocalDescription(type,
5477 sdesc->description());
5478 } else {
5479 const SessionDescriptionInterface* sdesc = remote_description();
5480 RTC_DCHECK(sdesc);
5481 return transport_controller_->SetRemoteDescription(type,
5482 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005483 }
Steve Anton75737c02017-11-06 10:37:17 -08005484}
5485
5486bool PeerConnection::GetTransportDescription(
5487 const SessionDescription* description,
5488 const std::string& content_name,
5489 cricket::TransportDescription* tdesc) {
5490 if (!description || !tdesc) {
5491 return false;
5492 }
5493 const TransportInfo* transport_info =
5494 description->GetTransportInfoByName(content_name);
5495 if (!transport_info) {
5496 return false;
5497 }
5498 *tdesc = transport_info->description;
5499 return true;
5500}
5501
Steve Anton75737c02017-11-06 10:37:17 -08005502cricket::IceConfig PeerConnection::ParseIceConfig(
5503 const PeerConnectionInterface::RTCConfiguration& config) const {
5504 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005505 switch (config.continual_gathering_policy) {
5506 case PeerConnectionInterface::GATHER_ONCE:
5507 gathering_policy = cricket::GATHER_ONCE;
5508 break;
5509 case PeerConnectionInterface::GATHER_CONTINUALLY:
5510 gathering_policy = cricket::GATHER_CONTINUALLY;
5511 break;
5512 default:
5513 RTC_NOTREACHED();
5514 gathering_policy = cricket::GATHER_ONCE;
5515 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005516
Steve Anton75737c02017-11-06 10:37:17 -08005517 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005518 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5519 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005520 ice_config.prioritize_most_likely_candidate_pairs =
5521 config.prioritize_most_likely_ice_candidate_pairs;
5522 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005523 RTCConfigurationToIceConfigOptionalInt(
5524 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005525 ice_config.continual_gathering_policy = gathering_policy;
5526 ice_config.presume_writable_when_fully_relayed =
5527 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005528 ice_config.ice_check_interval_strong_connectivity =
5529 config.ice_check_interval_strong_connectivity;
5530 ice_config.ice_check_interval_weak_connectivity =
5531 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005532 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005533 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5534 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005535 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005536 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005537 ice_config.regather_all_networks_interval_range =
5538 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005539 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005540 return ice_config;
5541}
5542
Steve Antona41959e2018-11-28 11:15:33 -08005543static absl::string_view GetTrackIdBySsrc(
5544 const SessionDescriptionInterface* session_description,
5545 uint32_t ssrc) {
5546 if (!session_description) {
5547 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005548 }
Steve Antona41959e2018-11-28 11:15:33 -08005549 for (const cricket::ContentInfo& content :
5550 session_description->description()->contents()) {
5551 const cricket::MediaContentDescription& media =
5552 *content.media_description();
5553 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5554 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5555 const cricket::StreamParams* stream_params =
5556 cricket::GetStreamBySsrc(media.streams(), ssrc);
5557 if (stream_params) {
5558 return stream_params->id;
5559 }
5560 }
5561 }
5562 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005563}
5564
Steve Antona41959e2018-11-28 11:15:33 -08005565absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5566 return GetTrackIdBySsrc(local_description(), ssrc);
5567}
5568
5569absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5570 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005571}
5572
5573bool PeerConnection::SendData(const cricket::SendDataParams& params,
5574 const rtc::CopyOnWriteBuffer& payload,
5575 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005576 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5577 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5578 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005579 return false;
5580 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005581 if (media_transport_) {
5582 SendDataParams send_params;
5583 send_params.type = ToWebrtcDataMessageType(params.type);
5584 send_params.ordered = params.ordered;
5585 if (params.max_rtx_count >= 0) {
5586 send_params.max_rtx_count = params.max_rtx_count;
5587 } else if (params.max_rtx_ms >= 0) {
5588 send_params.max_rtx_ms = params.max_rtx_ms;
5589 }
5590 return media_transport_->SendData(params.sid, send_params, payload).ok();
5591 }
Steve Anton75737c02017-11-06 10:37:17 -08005592 return rtp_data_channel_
5593 ? rtp_data_channel_->SendData(params, payload, result)
5594 : network_thread()->Invoke<bool>(
5595 RTC_FROM_HERE,
5596 Bind(&cricket::SctpTransportInternal::SendData,
5597 sctp_transport_.get(), params, payload, result));
5598}
5599
5600bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005601 RTC_DCHECK_RUN_ON(signaling_thread());
5602 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005603 // Don't log an error here, because DataChannels are expected to call
5604 // ConnectDataChannel in this state. It's the only way to initially tell
5605 // whether or not the underlying transport is ready.
5606 return false;
5607 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005608 if (media_transport_) {
5609 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5610 &DataChannel::OnChannelReady);
5611 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5612 &DataChannel::OnDataReceived);
5613 SignalMediaTransportChannelClosing_s.connect(
5614 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5615 SignalMediaTransportChannelClosed_s.connect(
5616 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5617 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005618 rtp_data_channel_->SignalReadyToSendData.connect(
5619 webrtc_data_channel, &DataChannel::OnChannelReady);
5620 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5621 &DataChannel::OnDataReceived);
5622 } else {
5623 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5624 &DataChannel::OnChannelReady);
5625 SignalSctpDataReceived.connect(webrtc_data_channel,
5626 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005627 SignalSctpClosingProcedureStartedRemotely.connect(
5628 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5629 SignalSctpClosingProcedureComplete.connect(
5630 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005631 }
5632 return true;
5633}
5634
5635void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005636 RTC_DCHECK_RUN_ON(signaling_thread());
5637 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005638 RTC_LOG(LS_ERROR)
5639 << "DisconnectDataChannel called when rtp_data_channel_ and "
5640 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005641 return;
5642 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005643 if (media_transport_) {
5644 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5645 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5646 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5647 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5648 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005649 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5650 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5651 } else {
5652 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5653 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005654 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5655 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005656 }
5657}
5658
5659void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005660 if (media_transport_) {
5661 // No-op. Media transport does not need to add streams.
5662 return;
5663 }
Steve Anton75737c02017-11-06 10:37:17 -08005664 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005665 RTC_LOG(LS_ERROR)
5666 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005667 return;
5668 }
5669 network_thread()->Invoke<void>(
5670 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5671 sctp_transport_.get(), sid));
5672}
5673
5674void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005675 if (media_transport_) {
5676 media_transport_->CloseChannel(sid);
5677 return;
5678 }
Steve Anton75737c02017-11-06 10:37:17 -08005679 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005680 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005681 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005682 return;
5683 }
5684 network_thread()->Invoke<void>(
5685 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5686 sctp_transport_.get(), sid));
5687}
5688
5689bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005690 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005691 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005692 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005693 sctp_ready_to_send_data_;
5694}
5695
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005696void PeerConnection::OnDataReceived(int channel_id,
5697 DataMessageType type,
5698 const rtc::CopyOnWriteBuffer& buffer) {
5699 cricket::ReceiveDataParams params;
5700 params.sid = channel_id;
5701 params.type = ToCricketDataMessageType(type);
5702 media_transport_invoker_->AsyncInvoke<void>(
5703 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5704 RTC_DCHECK_RUN_ON(signaling_thread());
5705 if (!HandleOpenMessage_s(params, buffer)) {
5706 SignalMediaTransportReceivedData_s(params, buffer);
5707 }
5708 });
5709}
5710
5711void PeerConnection::OnChannelClosing(int channel_id) {
5712 media_transport_invoker_->AsyncInvoke<void>(
5713 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5714 RTC_DCHECK_RUN_ON(signaling_thread());
5715 SignalMediaTransportChannelClosing_s(channel_id);
5716 });
5717}
5718
5719void PeerConnection::OnChannelClosed(int channel_id) {
5720 media_transport_invoker_->AsyncInvoke<void>(
5721 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5722 RTC_DCHECK_RUN_ON(signaling_thread());
5723 SignalMediaTransportChannelClosed_s(channel_id);
5724 });
5725}
5726
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005727absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005728 if (sctp_mid_ && transport_controller_) {
5729 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5730 if (dtls_transport) {
5731 return dtls_transport->transport_name();
5732 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005733 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005734 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005735 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005736}
5737
Qingsi Wang72a43a12018-02-20 16:03:18 -08005738cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5739 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005740 network_thread()->Invoke<void>(
5741 RTC_FROM_HERE,
5742 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5743 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005744 return candidate_states_list;
5745}
5746
Steve Anton5dfde182018-02-06 10:34:40 -08005747std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5748 const {
5749 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005750 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005751 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005752 if (channel) {
5753 transport_names_by_mid[channel->content_name()] =
5754 channel->transport_name();
5755 }
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
Steve Anton5dfde182018-02-06 10:34:40 -08005757 if (rtp_data_channel_) {
5758 transport_names_by_mid[rtp_data_channel_->content_name()] =
5759 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
5761 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005762 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005763 RTC_DCHECK(transport_name);
5764 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
Steve Anton5dfde182018-02-06 10:34:40 -08005766 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005767}
5768
Steve Anton5dfde182018-02-06 10:34:40 -08005769std::map<std::string, cricket::TransportStats>
5770PeerConnection::GetTransportStatsByNames(
5771 const std::set<std::string>& transport_names) {
5772 if (!network_thread()->IsCurrent()) {
5773 return network_thread()
5774 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5775 RTC_FROM_HERE,
5776 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005777 }
Steve Anton5dfde182018-02-06 10:34:40 -08005778 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5779 for (const std::string& transport_name : transport_names) {
5780 cricket::TransportStats transport_stats;
5781 bool success =
5782 transport_controller_->GetStats(transport_name, &transport_stats);
5783 if (success) {
5784 transport_stats_by_name[transport_name] = std::move(transport_stats);
5785 } else {
5786 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5787 << transport_name;
5788 }
5789 }
5790 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005791}
5792
5793bool PeerConnection::GetLocalCertificate(
5794 const std::string& transport_name,
5795 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005796 if (!certificate) {
5797 return false;
5798 }
5799 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5800 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005801}
5802
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005803std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005804 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005805 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005806}
5807
5808cricket::DataChannelType PeerConnection::data_channel_type() const {
5809 return data_channel_type_;
5810}
5811
5812bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5813 return pending_ice_restarts_.find(content_name) !=
5814 pending_ice_restarts_.end();
5815}
5816
Steve Anton75737c02017-11-06 10:37:17 -08005817bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5818 return transport_controller_->NeedsIceRestart(content_name);
5819}
5820
5821void PeerConnection::OnCertificateReady(
5822 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5823 transport_controller_->SetLocalCertificate(certificate);
5824}
5825
5826void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005827 SetSessionError(SessionError::kTransport,
5828 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005829}
5830
Alex Loiko9289eda2018-11-23 16:18:59 +00005831void PeerConnection::OnTransportControllerConnectionState(
5832 cricket::IceConnectionState state) {
5833 switch (state) {
5834 case cricket::kIceConnectionConnecting:
5835 // If the current state is Connected or Completed, then there were
5836 // writable channels but now there are not, so the next state must
5837 // be Disconnected.
5838 // kIceConnectionConnecting is currently used as the default,
5839 // un-connected state by the TransportController, so its only use is
5840 // detecting disconnections.
5841 if (ice_connection_state_ ==
5842 PeerConnectionInterface::kIceConnectionConnected ||
5843 ice_connection_state_ ==
5844 PeerConnectionInterface::kIceConnectionCompleted) {
5845 SetIceConnectionState(
5846 PeerConnectionInterface::kIceConnectionDisconnected);
5847 }
5848 break;
5849 case cricket::kIceConnectionFailed:
5850 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5851 break;
5852 case cricket::kIceConnectionConnected:
5853 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5854 "all transports are writable.";
5855 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5856 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5857 break;
5858 case cricket::kIceConnectionCompleted:
5859 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5860 "all transports are complete.";
5861 if (ice_connection_state_ !=
5862 PeerConnectionInterface::kIceConnectionConnected) {
5863 // If jumping directly from "checking" to "connected",
5864 // signal "connected" first.
5865 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5866 }
5867 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5868 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5869 ReportTransportStats();
5870 break;
5871 default:
5872 RTC_NOTREACHED();
5873 }
5874}
5875
Steve Anton75737c02017-11-06 10:37:17 -08005876void PeerConnection::OnTransportControllerCandidatesGathered(
5877 const std::string& transport_name,
5878 const cricket::Candidates& candidates) {
5879 RTC_DCHECK(signaling_thread()->IsCurrent());
5880 int sdp_mline_index;
5881 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005882 RTC_LOG(LS_ERROR)
5883 << "OnTransportControllerCandidatesGathered: content name "
5884 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005885 return;
5886 }
5887
5888 for (cricket::Candidates::const_iterator citer = candidates.begin();
5889 citer != candidates.end(); ++citer) {
5890 // Use transport_name as the candidate media id.
5891 std::unique_ptr<JsepIceCandidate> candidate(
5892 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5893 if (local_description()) {
5894 mutable_local_description()->AddCandidate(candidate.get());
5895 }
5896 OnIceCandidate(std::move(candidate));
5897 }
5898}
5899
5900void PeerConnection::OnTransportControllerCandidatesRemoved(
5901 const std::vector<cricket::Candidate>& candidates) {
5902 RTC_DCHECK(signaling_thread()->IsCurrent());
5903 // Sanity check.
5904 for (const cricket::Candidate& candidate : candidates) {
5905 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005906 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005907 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005908 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005909 return;
5910 }
5911 }
5912
5913 if (local_description()) {
5914 mutable_local_description()->RemoveCandidates(candidates);
5915 }
5916 OnIceCandidatesRemoved(candidates);
5917}
5918
5919void PeerConnection::OnTransportControllerDtlsHandshakeError(
5920 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005921 RTC_HISTOGRAM_ENUMERATION(
5922 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5923 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005924}
5925
Steve Antoned10bd92017-12-05 10:52:59 -08005926void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005927 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005928 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005929 if (channel && !channel->enabled()) {
5930 channel->Enable(true);
5931 }
Steve Anton75737c02017-11-06 10:37:17 -08005932 }
5933
Steve Anton4171afb2017-11-20 10:20:22 -08005934 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005935 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005936 }
Steve Anton75737c02017-11-06 10:37:17 -08005937}
5938
5939// Returns the media index for a local ice candidate given the content name.
5940bool PeerConnection::GetLocalCandidateMediaIndex(
5941 const std::string& content_name,
5942 int* sdp_mline_index) {
5943 if (!local_description() || !sdp_mline_index) {
5944 return false;
5945 }
5946
5947 bool content_found = false;
5948 const ContentInfos& contents = local_description()->description()->contents();
5949 for (size_t index = 0; index < contents.size(); ++index) {
5950 if (contents[index].name == content_name) {
5951 *sdp_mline_index = static_cast<int>(index);
5952 content_found = true;
5953 break;
5954 }
5955 }
5956 return content_found;
5957}
5958
5959bool PeerConnection::UseCandidatesInSessionDescription(
5960 const SessionDescriptionInterface* remote_desc) {
5961 if (!remote_desc) {
5962 return true;
5963 }
5964 bool ret = true;
5965
5966 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5967 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5968 for (size_t n = 0; n < candidates->count(); ++n) {
5969 const IceCandidateInterface* candidate = candidates->at(n);
5970 bool valid = false;
5971 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5972 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005973 RTC_LOG(LS_INFO)
5974 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005975 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005976 }
5977 continue;
5978 }
5979 ret = UseCandidate(candidate);
5980 if (!ret) {
5981 break;
5982 }
5983 }
5984 }
5985 return ret;
5986}
5987
5988bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5989 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5990 size_t remote_content_size =
5991 remote_description()->description()->contents().size();
5992 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005993 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005994 return false;
5995 }
5996
5997 cricket::ContentInfo content =
5998 remote_description()->description()->contents()[mediacontent_index];
5999 std::vector<cricket::Candidate> candidates;
6000 candidates.push_back(candidate->candidate());
6001 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006002 RTCError error =
6003 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006004 if (error.ok()) {
6005 // Candidates successfully submitted for checking.
6006 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6007 ice_connection_state_ ==
6008 PeerConnectionInterface::kIceConnectionDisconnected) {
6009 // If state is New, then the session has just gotten its first remote ICE
6010 // candidates, so go to Checking.
6011 // If state is Disconnected, the session is re-using old candidates or
6012 // receiving additional ones, so go to Checking.
6013 // If state is Connected, stay Connected.
6014 // TODO(bemasc): If state is Connected, and the new candidates are for a
6015 // newly added transport, then the state actually _should_ move to
6016 // checking. Add a way to distinguish that case.
6017 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6018 }
6019 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006020 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006021 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006022 }
6023 return true;
6024}
6025
6026void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006027 // Destroy video channel first since it may have a pointer to the
6028 // voice channel.
6029 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006030 if (!video_info || video_info->rejected) {
6031 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006032 }
6033
Steve Anton6fec8802017-12-04 10:37:29 -08006034 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6035 if (!audio_info || audio_info->rejected) {
6036 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006037 }
6038
6039 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6040 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006041 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006042 }
6043}
6044
Steve Antondcc3c022017-12-22 16:02:54 -08006045RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6046 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006047 const cricket::ContentGroup* bundle_group = nullptr;
6048 if (configuration_.bundle_policy ==
6049 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006050 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006051 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006052 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6053 "max-bundle configured but session description "
6054 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006055 }
6056 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006057 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006058}
6059
6060RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006061 // Creating the media channels. Transports should already have been created
6062 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006063 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006064 if (voice && !voice->rejected &&
6065 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006066 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006067 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006068 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6069 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006070 }
6071 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6072 }
6073
Steve Antondcc3c022017-12-22 16:02:54 -08006074 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006075 if (video && !video->rejected &&
6076 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006077 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006078 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006079 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6080 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006081 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006082 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006083 }
6084
Steve Antondcc3c022017-12-22 16:02:54 -08006085 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006086 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006087 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006088 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006089 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6090 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006091 }
6092 }
6093
Steve Anton8a006912017-12-04 15:25:56 -08006094 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006095}
6096
Steve Anton4171afb2017-11-20 10:20:22 -08006097// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006098cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006099 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006100 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006101 MediaTransportInterface* media_transport = nullptr;
6102 if (configuration_.use_media_transport) {
6103 media_transport = GetMediaTransport(mid);
6104 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006105
Steve Anton75737c02017-11-06 10:37:17 -08006106 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006107 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006108 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006109 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006110 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006111 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006112 }
Steve Anton75737c02017-11-06 10:37:17 -08006113 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6114 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006115 voice_channel->SignalSentPacket.connect(this,
6116 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006117 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006118
Steve Antoneda6ccd2017-12-04 10:21:55 -08006119 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006120}
6121
Steve Anton4171afb2017-11-20 10:20:22 -08006122// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006123cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006124 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006125 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006126 MediaTransportInterface* media_transport = nullptr;
6127 if (configuration_.use_media_transport) {
6128 media_transport = GetMediaTransport(mid);
6129 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006130
Steve Anton75737c02017-11-06 10:37:17 -08006131 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006132 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006133 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006134 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006135 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006136 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006137 }
Steve Anton75737c02017-11-06 10:37:17 -08006138 video_channel->SignalDtlsSrtpSetupFailure.connect(
6139 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006140 video_channel->SignalSentPacket.connect(this,
6141 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006142 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006143
Steve Antoneda6ccd2017-12-04 10:21:55 -08006144 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006145}
6146
Zhi Huange830e682018-03-30 10:48:35 -07006147bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006148 switch (data_channel_type_) {
6149 case cricket::DCT_MEDIA_TRANSPORT:
6150 if (network_thread()->Invoke<bool>(
6151 RTC_FROM_HERE,
6152 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6153 this, mid))) {
6154 for (const auto& channel : sctp_data_channels_) {
6155 channel->OnTransportChannelCreated();
6156 }
6157 return true;
6158 }
Steve Anton75737c02017-11-06 10:37:17 -08006159 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006160 case cricket::DCT_SCTP:
6161 if (!sctp_factory_) {
6162 RTC_LOG(LS_ERROR)
6163 << "Trying to create SCTP transport, but didn't compile with "
6164 "SCTP support (HAVE_SCTP)";
6165 return false;
6166 }
6167 if (!network_thread()->Invoke<bool>(
6168 RTC_FROM_HERE,
6169 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6170 return false;
6171 }
6172 for (const auto& channel : sctp_data_channels_) {
6173 channel->OnTransportChannelCreated();
6174 }
6175 return true;
6176 case cricket::DCT_RTP:
6177 default:
6178 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6179 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6180 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006181 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006182 if (!rtp_data_channel_) {
6183 return false;
6184 }
6185 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6186 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6187 rtp_data_channel_->SignalSentPacket.connect(
6188 this, &PeerConnection::OnSentPacket_w);
6189 rtp_data_channel_->SetRtpTransport(rtp_transport);
6190 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006191 }
6192
Steve Anton75737c02017-11-06 10:37:17 -08006193 return true;
6194}
6195
6196Call::Stats PeerConnection::GetCallStats() {
6197 if (!worker_thread()->IsCurrent()) {
6198 return worker_thread()->Invoke<Call::Stats>(
6199 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6200 }
6201 if (call_) {
6202 return call_->GetStats();
6203 } else {
6204 return Call::Stats();
6205 }
6206}
6207
Zhi Huange830e682018-03-30 10:48:35 -07006208bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006209 RTC_DCHECK(network_thread()->IsCurrent());
6210 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006211 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006212 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006213 RTC_DCHECK(dtls_transport);
6214 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006215 RTC_DCHECK(sctp_transport_);
6216 sctp_invoker_.reset(new rtc::AsyncInvoker());
6217 sctp_transport_->SignalReadyToSendData.connect(
6218 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6219 sctp_transport_->SignalDataReceived.connect(
6220 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006221 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6222 // another thread. Would be nice if there was a helper class similar to
6223 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6224 // code.
6225 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6226 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6227 sctp_transport_->SignalClosingProcedureComplete.connect(
6228 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006229 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006230 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006231 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006232}
6233
6234void PeerConnection::DestroySctpTransport_n() {
6235 RTC_DCHECK(network_thread()->IsCurrent());
6236 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006237 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006238 sctp_invoker_.reset(nullptr);
6239 sctp_ready_to_send_data_ = false;
6240}
6241
6242void PeerConnection::OnSctpTransportReadyToSendData_n() {
6243 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6244 RTC_DCHECK(network_thread()->IsCurrent());
6245 // Note: Cannot use rtc::Bind here because it will grab a reference to
6246 // PeerConnection and potentially cause PeerConnection to live longer than
6247 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6248 // be destroyed before PeerConnection is destroyed, and at that point all
6249 // pending tasks will be cleared.
6250 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6251 OnSctpTransportReadyToSendData_s(true);
6252 });
6253}
6254
6255void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6256 RTC_DCHECK(signaling_thread()->IsCurrent());
6257 sctp_ready_to_send_data_ = ready;
6258 SignalSctpReadyToSendData(ready);
6259}
6260
6261void PeerConnection::OnSctpTransportDataReceived_n(
6262 const cricket::ReceiveDataParams& params,
6263 const rtc::CopyOnWriteBuffer& payload) {
6264 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6265 RTC_DCHECK(network_thread()->IsCurrent());
6266 // Note: Cannot use rtc::Bind here because it will grab a reference to
6267 // PeerConnection and potentially cause PeerConnection to live longer than
6268 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6269 // be destroyed before PeerConnection is destroyed, and at that point all
6270 // pending tasks will be cleared.
6271 sctp_invoker_->AsyncInvoke<void>(
6272 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6273 OnSctpTransportDataReceived_s(params, payload);
6274 });
6275}
6276
6277void PeerConnection::OnSctpTransportDataReceived_s(
6278 const cricket::ReceiveDataParams& params,
6279 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006280 RTC_DCHECK_RUN_ON(signaling_thread());
6281 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006282 SignalSctpDataReceived(params, payload);
6283 }
6284}
6285
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006286void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006287 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6288 RTC_DCHECK(network_thread()->IsCurrent());
6289 sctp_invoker_->AsyncInvoke<void>(
6290 RTC_FROM_HERE, signaling_thread(),
6291 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006292 &SignalSctpClosingProcedureStartedRemotely, sid));
6293}
6294
6295void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6296 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6297 RTC_DCHECK(network_thread()->IsCurrent());
6298 sctp_invoker_->AsyncInvoke<void>(
6299 RTC_FROM_HERE, signaling_thread(),
6300 rtc::Bind(&sigslot::signal1<int>::operator(),
6301 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006302}
6303
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006304bool PeerConnection::SetupMediaTransportForDataChannels_n(
6305 const std::string& mid) {
6306 media_transport_ = transport_controller_->GetMediaTransport(mid);
6307 if (!media_transport_) {
6308 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6309 return false;
6310 }
6311
6312 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6313 media_transport_->SetDataSink(this);
6314 media_transport_data_mid_ = mid;
6315 transport_controller_->SignalMediaTransportStateChanged.connect(
6316 this, &PeerConnection::OnMediaTransportStateChanged_n);
6317 // Check the initial state right away, in case transport is already writable.
6318 OnMediaTransportStateChanged_n();
6319 return true;
6320}
6321
6322void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6323 if (!media_transport_) {
6324 return;
6325 }
6326 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6327 media_transport_data_mid_.reset();
6328 media_transport_->SetDataSink(nullptr);
6329 media_transport_invoker_ = nullptr;
6330 media_transport_ = nullptr;
6331}
6332
6333void PeerConnection::OnMediaTransportStateChanged_n() {
6334 if (!media_transport_data_mid_ ||
6335 transport_controller_->GetMediaTransportState(
6336 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6337 return;
6338 }
6339 media_transport_invoker_->AsyncInvoke<void>(
6340 RTC_FROM_HERE, signaling_thread(), [this] {
6341 RTC_DCHECK_RUN_ON(signaling_thread());
6342 media_transport_ready_to_send_data_ = true;
6343 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6344 });
6345}
6346
Steve Anton75737c02017-11-06 10:37:17 -08006347// Returns false if bundle is enabled and rtcp_mux is disabled.
6348bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6349 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6350 if (!bundle_enabled)
6351 return true;
6352
6353 const cricket::ContentGroup* bundle_group =
6354 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6355 RTC_DCHECK(bundle_group != NULL);
6356
6357 const cricket::ContentInfos& contents = desc->contents();
6358 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6359 citer != contents.end(); ++citer) {
6360 const cricket::ContentInfo* content = (&*citer);
6361 RTC_DCHECK(content != NULL);
6362 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006363 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006364 if (!HasRtcpMuxEnabled(content))
6365 return false;
6366 }
6367 }
6368 // RTCP-MUX is enabled in all the contents.
6369 return true;
6370}
6371
6372bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006373 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006374}
6375
Steve Anton06817cd2018-12-18 15:55:30 -08006376static RTCError ValidateMids(const cricket::SessionDescription& description) {
6377 std::set<std::string> mids;
6378 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006379 if (content.name.empty()) {
6380 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6381 "A media section is missing a MID attribute.");
6382 }
Steve Anton06817cd2018-12-18 15:55:30 -08006383 if (!mids.insert(content.name).second) {
6384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6385 "Duplicate a=mid value '" + content.name + "'.");
6386 }
6387 }
6388 return RTCError::OK();
6389}
6390
Steve Anton8a006912017-12-04 15:25:56 -08006391RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006392 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006393 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006394 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006395 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006396 }
6397
6398 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006399 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006400 }
6401
Steve Anton3828c062017-12-06 10:34:51 -08006402 SdpType type = sdesc->GetType();
6403 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6404 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006405 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006406 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006407 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006408 }
6409
Steve Anton06817cd2018-12-18 15:55:30 -08006410 RTCError error = ValidateMids(*sdesc->description());
6411 if (!error.ok()) {
6412 return error;
6413 }
6414
Steve Anton75737c02017-11-06 10:37:17 -08006415 // Verify crypto settings.
6416 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006417 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6418 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006419 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006420 if (!crypto_error.ok()) {
6421 return crypto_error;
6422 }
Steve Anton75737c02017-11-06 10:37:17 -08006423 }
6424
6425 // Verify ice-ufrag and ice-pwd.
6426 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6428 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006429 }
6430
6431 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006432 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6433 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006434 }
6435
6436 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6437 // m-lines that do not rtcp-mux enabled.
6438
6439 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006440 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006441 // With an answer we want to compare the new answer session description with
6442 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006443 const cricket::SessionDescription* offer_desc =
6444 (source == cricket::CS_LOCAL) ? remote_description()->description()
6445 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006446 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6447 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6448 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006449 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6450 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006451 }
6452 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006453 // The re-offers should respect the order of m= sections in current
6454 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006455 // With a re-offer, either the current local or current remote descriptions
6456 // could be the most up to date, so we would like to check against both of
6457 // them if they exist. It could be the case that one of them has a 0 port
6458 // for a media section, but the other does not. This is important to check
6459 // against in the case that we are recycling an m= section.
6460 const cricket::SessionDescription* current_desc = nullptr;
6461 const cricket::SessionDescription* secondary_current_desc = nullptr;
6462 if (local_description()) {
6463 current_desc = local_description()->description();
6464 if (remote_description()) {
6465 secondary_current_desc = remote_description()->description();
6466 }
6467 } else if (remote_description()) {
6468 current_desc = remote_description()->description();
6469 }
Steve Anton75737c02017-11-06 10:37:17 -08006470 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006471 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6472 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006473 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6474 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006475 }
6476 }
6477
Steve Antonba42e992018-04-09 14:10:01 -07006478 if (IsUnifiedPlan()) {
6479 // Ensure that each audio and video media section has at most one
6480 // "StreamParams". This will return an error if receiving a session
6481 // description from a "Plan B" endpoint which adds multiple tracks of the
6482 // same type. With Unified Plan, there can only be at most one track per
6483 // media section.
6484 for (const ContentInfo& content : sdesc->description()->contents()) {
6485 const MediaContentDescription& desc = *content.description;
6486 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6487 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6488 desc.streams().size() > 1u) {
6489 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6490 "Media section has more than one track specified "
6491 "with a=ssrc lines which is not supported with "
6492 "Unified Plan.");
6493 }
6494 }
6495 }
6496
Steve Anton8a006912017-12-04 15:25:56 -08006497 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006498}
6499
Steve Anton3828c062017-12-06 10:34:51 -08006500bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006501 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006502 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006503 return (state == PeerConnectionInterface::kStable) ||
6504 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006505 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006506 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006507 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6508 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6509 }
6510}
6511
Steve Anton3828c062017-12-06 10:34:51 -08006512bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006513 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006514 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006515 return (state == PeerConnectionInterface::kStable) ||
6516 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006517 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006518 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006519 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6520 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6521 }
6522}
6523
Steve Antonf8470812017-12-04 10:46:21 -08006524const char* PeerConnection::SessionErrorToString(SessionError error) const {
6525 switch (error) {
6526 case SessionError::kNone:
6527 return "ERROR_NONE";
6528 case SessionError::kContent:
6529 return "ERROR_CONTENT";
6530 case SessionError::kTransport:
6531 return "ERROR_TRANSPORT";
6532 }
6533 RTC_NOTREACHED();
6534 return "";
6535}
6536
Steve Anton75737c02017-11-06 10:37:17 -08006537std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006538 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006539 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6540 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006541 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006542}
6543
Steve Anton8e20f172018-03-06 10:55:04 -08006544void PeerConnection::ReportSdpFormatReceived(
6545 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006546 int num_audio_mlines = 0;
6547 int num_video_mlines = 0;
6548 int num_audio_tracks = 0;
6549 int num_video_tracks = 0;
6550 for (const ContentInfo& content : remote_offer.description()->contents()) {
6551 cricket::MediaType media_type = content.media_description()->type();
6552 int num_tracks = std::max(
6553 1, static_cast<int>(content.media_description()->streams().size()));
6554 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6555 num_audio_mlines += 1;
6556 num_audio_tracks += num_tracks;
6557 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6558 num_video_mlines += 1;
6559 num_video_tracks += num_tracks;
6560 }
6561 }
6562 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6563 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6564 format = kSdpFormatReceivedComplexUnifiedPlan;
6565 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6566 format = kSdpFormatReceivedComplexPlanB;
6567 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6568 format = kSdpFormatReceivedSimple;
6569 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006570 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6571 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006572}
6573
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006574void PeerConnection::NoteUsageEvent(UsageEvent event) {
6575 RTC_DCHECK_RUN_ON(signaling_thread());
6576 usage_event_accumulator_ |= static_cast<int>(event);
6577}
6578
6579void PeerConnection::ReportUsagePattern() const {
6580 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006581 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6582 usage_event_accumulator_,
6583 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006584 const int bad_bits =
6585 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6586 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6587 const int good_bits =
6588 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6589 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6590 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6591 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6592 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006593 // If called after close(), we can't report, because observer may have
6594 // been deallocated, and therefore pointer is null. Write to log instead.
6595 if (observer_) {
6596 Observer()->OnInterestingUsage(usage_event_accumulator_);
6597 } else {
6598 RTC_LOG(LS_INFO) << "Interesting usage signature "
6599 << usage_event_accumulator_
6600 << " observed after observer shutdown";
6601 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006602 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006603}
6604
Steve Anton0ffaaa22018-02-23 10:31:30 -08006605void PeerConnection::ReportNegotiatedSdpSemantics(
6606 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006607 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006608 switch (answer.description()->msid_signaling()) {
6609 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006610 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006611 break;
6612 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006613 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006614 break;
6615 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006616 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006617 break;
6618 case cricket::kMsidSignalingMediaSection |
6619 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006620 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006621 break;
6622 default:
6623 RTC_NOTREACHED();
6624 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006625 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6626 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006627}
6628
Steve Anton75737c02017-11-06 10:37:17 -08006629// We need to check the local/remote description for the Transport instead of
6630// the session, because a new Transport added during renegotiation may have
6631// them unset while the session has them set from the previous negotiation.
6632// Not doing so may trigger the auto generation of transport description and
6633// mess up DTLS identity information, ICE credential, etc.
6634bool PeerConnection::ReadyToUseRemoteCandidate(
6635 const IceCandidateInterface* candidate,
6636 const SessionDescriptionInterface* remote_desc,
6637 bool* valid) {
6638 *valid = true;
6639
6640 const SessionDescriptionInterface* current_remote_desc =
6641 remote_desc ? remote_desc : remote_description();
6642
6643 if (!current_remote_desc) {
6644 return false;
6645 }
6646
6647 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6648 size_t remote_content_size =
6649 current_remote_desc->description()->contents().size();
6650 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006651 RTC_LOG(LS_ERROR)
6652 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6653 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006654
6655 *valid = false;
6656 return false;
6657 }
6658
6659 cricket::ContentInfo content =
6660 current_remote_desc->description()->contents()[mediacontent_index];
6661
6662 const std::string transport_name = GetTransportName(content.name);
6663 if (transport_name.empty()) {
6664 return false;
6665 }
Zhi Huange830e682018-03-30 10:48:35 -07006666 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006667}
6668
6669bool PeerConnection::SrtpRequired() const {
6670 return dtls_enabled_ ||
6671 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6672}
6673
6674void PeerConnection::OnTransportControllerGatheringState(
6675 cricket::IceGatheringState state) {
6676 RTC_DCHECK(signaling_thread()->IsCurrent());
6677 if (state == cricket::kIceGatheringGathering) {
6678 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6679 } else if (state == cricket::kIceGatheringComplete) {
6680 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6681 }
6682}
6683
6684void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006685 std::map<std::string, std::set<cricket::MediaType>>
6686 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006687 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006688 if (transceiver->internal()->channel()) {
6689 const std::string& transport_name =
6690 transceiver->internal()->channel()->transport_name();
6691 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006692 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006693 }
Steve Anton75737c02017-11-06 10:37:17 -08006694 }
6695 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006696 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6697 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006698 }
Zhi Huange830e682018-03-30 10:48:35 -07006699
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006700 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006701 if (transport_name) {
6702 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006703 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006704 }
Zhi Huange830e682018-03-30 10:48:35 -07006705
Steve Antonc7b964c2018-02-01 14:39:45 -08006706 for (const auto& entry : media_types_by_transport_name) {
6707 const std::string& transport_name = entry.first;
6708 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006709 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006710 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006711 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006712 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006713 }
6714 }
6715}
6716// Walk through the ConnectionInfos to gather best connection usage
6717// for IPv4 and IPv6.
6718void PeerConnection::ReportBestConnectionState(
6719 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006720 for (const cricket::TransportChannelStats& channel_stats :
6721 stats.channel_stats) {
6722 for (const cricket::ConnectionInfo& connection_info :
6723 channel_stats.connection_infos) {
6724 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006725 continue;
6726 }
6727
Steve Antonc7b964c2018-02-01 14:39:45 -08006728 const cricket::Candidate& local = connection_info.local_candidate;
6729 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006730
6731 // Increment the counter for IceCandidatePairType.
6732 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6733 (local.type() == RELAY_PORT_TYPE &&
6734 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006735 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6736 GetIceCandidatePairCounter(local, remote),
6737 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006738 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006739 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6740 GetIceCandidatePairCounter(local, remote),
6741 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006742 } else {
6743 RTC_CHECK(0);
6744 }
Steve Anton75737c02017-11-06 10:37:17 -08006745
6746 // Increment the counter for IP type.
6747 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006748 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6749 kBestConnections_IPv4,
6750 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006751 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006752 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6753 kBestConnections_IPv6,
6754 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006755 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006756 RTC_CHECK(!local.address().hostname().empty() &&
6757 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006758 }
6759
6760 return;
6761 }
6762 }
6763}
6764
6765void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006766 const cricket::TransportStats& stats,
6767 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006768 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6769 return;
6770 }
6771
6772 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6773 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6774 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6775 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6776 return;
6777 }
6778
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006779 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6780 for (cricket::MediaType media_type : media_types) {
6781 switch (media_type) {
6782 case cricket::MEDIA_TYPE_AUDIO:
6783 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6784 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6785 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6786 break;
6787 case cricket::MEDIA_TYPE_VIDEO:
6788 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6789 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6790 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6791 break;
6792 case cricket::MEDIA_TYPE_DATA:
6793 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6794 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6795 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6796 break;
6797 default:
6798 RTC_NOTREACHED();
6799 continue;
6800 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006801 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006802 }
6803
6804 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6805 for (cricket::MediaType media_type : media_types) {
6806 switch (media_type) {
6807 case cricket::MEDIA_TYPE_AUDIO:
6808 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6809 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6810 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6811 break;
6812 case cricket::MEDIA_TYPE_VIDEO:
6813 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6814 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6815 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6816 break;
6817 case cricket::MEDIA_TYPE_DATA:
6818 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6819 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6820 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6821 break;
6822 default:
6823 RTC_NOTREACHED();
6824 continue;
6825 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006826 }
Steve Anton75737c02017-11-06 10:37:17 -08006827 }
6828}
6829
6830void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6831 RTC_DCHECK(worker_thread()->IsCurrent());
6832 RTC_DCHECK(call_);
6833 call_->OnSentPacket(sent_packet);
6834}
6835
6836const std::string PeerConnection::GetTransportName(
6837 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006838 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006839 if (channel) {
6840 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006841 }
Steve Anton6fec8802017-12-04 10:37:29 -08006842 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006843 RTC_DCHECK(sctp_mid_);
6844 if (content_name == *sctp_mid_) {
6845 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006846 }
6847 }
6848 // Return an empty string if failed to retrieve the transport name.
6849 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006850}
6851
Steve Anton6fec8802017-12-04 10:37:29 -08006852void PeerConnection::DestroyTransceiverChannel(
6853 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6854 transceiver) {
6855 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006856
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006857 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006858 if (channel) {
6859 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006860 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006861 }
6862}
6863
6864void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006865 if (rtp_data_channel_) {
6866 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006867 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006868 rtp_data_channel_ = nullptr;
6869 }
6870
6871 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6872 // grab a reference to this PeerConnection. If this is called from the
6873 // PeerConnection destructor, the RefCountedObject vtable will have already
6874 // been destroyed (since it is a subclass of PeerConnection) and using
6875 // rtc::Bind will cause "Pure virtual function called" error to appear.
6876
6877 if (sctp_transport_) {
6878 OnDataChannelDestroyed();
6879 network_thread()->Invoke<void>(RTC_FROM_HERE,
6880 [this] { DestroySctpTransport_n(); });
6881 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006882
6883 if (media_transport_) {
6884 OnDataChannelDestroyed();
6885 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6886 RTC_DCHECK_RUN_ON(network_thread());
6887 TeardownMediaTransportForDataChannels_n();
6888 });
6889 }
Steve Anton6fec8802017-12-04 10:37:29 -08006890}
6891
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006892void PeerConnection::DestroyChannelInterface(
6893 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006894 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006895 switch (channel->media_type()) {
6896 case cricket::MEDIA_TYPE_AUDIO:
6897 channel_manager()->DestroyVoiceChannel(
6898 static_cast<cricket::VoiceChannel*>(channel));
6899 break;
6900 case cricket::MEDIA_TYPE_VIDEO:
6901 channel_manager()->DestroyVideoChannel(
6902 static_cast<cricket::VideoChannel*>(channel));
6903 break;
6904 case cricket::MEDIA_TYPE_DATA:
6905 channel_manager()->DestroyRtpDataChannel(
6906 static_cast<cricket::RtpDataChannel*>(channel));
6907 break;
6908 default:
6909 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6910 break;
6911 }
Zhi Huange830e682018-03-30 10:48:35 -07006912}
Steve Anton6fec8802017-12-04 10:37:29 -08006913
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006914bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006915 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006916 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006917 cricket::DtlsTransportInternal* dtls_transport,
6918 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006919 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006920 auto base_channel = GetChannel(mid);
6921 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006922 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006923 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006924 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006925 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006926 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006927
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006928 if (configuration_.use_media_transport) {
6929 // Only pass media transport to call object if media transport is used
6930 // for media (and not data channel).
6931 call_->MediaTransportChange(media_transport);
6932 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006933
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006934 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006935}
6936
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006937PeerConnectionObserver* PeerConnection::Observer() const {
6938 // In earlier production code, the pointer was not cleared on close,
6939 // which might have led to undefined behavior if the observer was not
6940 // deallocated, or strange crashes if it was.
6941 // We use CHECK in order to catch such behavior if it exists.
6942 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6943 RTC_CHECK(observer_);
6944 return observer_;
6945}
6946
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006947CryptoOptions PeerConnection::GetCryptoOptions() {
6948 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6949 // after it has been removed.
6950 return configuration_.crypto_options.has_value()
6951 ? *configuration_.crypto_options
6952 : factory_->options().crypto_options;
6953}
6954
Harald Alvestrand89061872018-01-02 14:08:34 +01006955void PeerConnection::ClearStatsCache() {
6956 if (stats_collector_) {
6957 stats_collector_->ClearCachedStatsReport();
6958 }
6959}
6960
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006961void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006962 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6963 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006964}
6965
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006966} // namespace webrtc