blob: 385c3d09ebc0cd5f1f258bcfb646e3f4a3fee71a [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)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100836 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700837 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700838 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700839 remote_streams_(StreamCollection::Create()),
840 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841
842PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100843 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800844 RTC_DCHECK_RUN_ON(signaling_thread());
845
Steve Anton8af21862017-12-15 11:20:13 -0800846 // Need to stop transceivers before destroying the stats collector because
847 // AudioRtpSender has a reference to the StatsCollector it will update when
848 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100849 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800850 transceiver->Stop();
851 }
Steve Anton4171afb2017-11-20 10:20:22 -0800852
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700853 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800854 if (stats_collector_) {
855 stats_collector_->WaitForPendingRequest();
856 stats_collector_ = nullptr;
857 }
Steve Anton75737c02017-11-06 10:37:17 -0800858
Steve Anton8af21862017-12-15 11:20:13 -0800859 // Don't destroy BaseChannels until after stats has been cleaned up so that
860 // the last stats request can still read from the channels.
861 DestroyAllChannels();
862
Mirko Bonadei675513b2017-11-09 11:09:25 +0100863 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800864
865 webrtc_session_desc_factory_.reset();
866 sctp_invoker_.reset();
867 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800868 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800869 transport_controller_.reset();
870
deadbeef91dd5672016-05-18 16:55:30 -0700871 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700872 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700873 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700874 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700875 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100876 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700877 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800878 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700879 event_log_.reset();
880 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000881}
882
Steve Anton8af21862017-12-15 11:20:13 -0800883void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800884 // Destroy video channels first since they may have a pointer to a voice
885 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100886 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800887 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800888 DestroyTransceiverChannel(transceiver);
889 }
890 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100891 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800892 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800893 DestroyTransceiverChannel(transceiver);
894 }
895 }
896 DestroyDataChannel();
897}
898
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000900 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700901 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100902 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +0100903 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700904
905 RTCError config_error = ValidateConfiguration(configuration);
906 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700908 return false;
909 }
910
Benjamin Wrightcab58882018-05-02 15:12:47 -0700911 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100912 RTC_LOG(LS_ERROR)
913 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100914 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800915 return false;
916 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200917
Benjamin Wrightcab58882018-05-02 15:12:47 -0700918 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800919 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100920 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100921 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800922 return false;
923 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700924
Benjamin Wrightcab58882018-05-02 15:12:47 -0700925 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700926 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700927 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700928 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800929
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200930 cricket::ServerAddresses stun_servers;
931 std::vector<cricket::RelayServerConfig> turn_servers;
932
933 RTCErrorType parse_error =
934 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
935 if (parse_error != RTCErrorType::NONE) {
936 return false;
937 }
938
deadbeef91dd5672016-05-18 16:55:30 -0700939 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700940 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700941 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200942 RTC_FROM_HERE,
943 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
944 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 return false;
946 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200947 // If initialization was successful, note if STUN or TURN servers
948 // were supplied.
949 if (!stun_servers.empty()) {
950 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
951 }
952 if (!turn_servers.empty()) {
953 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
954 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700956 // Send information about IPv4/IPv6 status.
957 PeerConnectionAddressFamilyCounter address_family;
958 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
959 address_family = kPeerConnection_IPv6;
960 } else {
961 address_family = kPeerConnection_IPv4;
962 }
963 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
964 kPeerConnectionAddressFamilyCounter_Max);
965
Zhi Huange830e682018-03-30 10:48:35 -0700966 const PeerConnectionFactoryInterface::Options& options = factory_->options();
967
Steve Anton75737c02017-11-06 10:37:17 -0800968 // RFC 3264: The numeric value of the session id and version in the
969 // o line MUST be representable with a "64 bit signed integer".
970 // Due to this constraint session id |session_id_| is max limited to
971 // LLONG_MAX.
972 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700973 JsepTransportController::Config config;
974 config.redetermine_role_on_ice_restart =
975 configuration.redetermine_role_on_ice_restart;
976 config.ssl_max_version = factory_->options().ssl_max_version;
977 config.disable_encryption = options.disable_encryption;
978 config.bundle_policy = configuration.bundle_policy;
979 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700980 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
981 // stub.
982 config.crypto_options = configuration.crypto_options.has_value()
983 ? *configuration.crypto_options
984 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700985 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +0100986 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -0700987#if defined(ENABLE_EXTERNAL_AUTH)
988 config.enable_external_auth = true;
989#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700990 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700991
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700992 if (configuration.use_media_transport ||
993 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700994 if (!factory_->media_transport_factory()) {
995 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700996 << "PeerConnecton is initialized with use_media_transport = true or "
997 << "use_media_transport_for_data_channels = true "
998 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700999 return false;
1000 }
1001
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001002 config.use_media_transport_for_media = configuration.use_media_transport;
1003 config.use_media_transport_for_data_channels =
1004 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001005 config.media_transport_factory = factory_->media_transport_factory();
1006 }
1007
Zhi Huange830e682018-03-30 10:48:35 -07001008 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001009 signaling_thread(), network_thread(), port_allocator_.get(),
1010 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001011 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001012 this, &PeerConnection::OnTransportControllerConnectionState);
1013 transport_controller_->SignalStandardizedIceConnectionState.connect(
1014 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001015 transport_controller_->SignalConnectionState.connect(
1016 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001017 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001018 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001019 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001020 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001021 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001022 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1023 transport_controller_->SignalDtlsHandshakeError.connect(
1024 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1025
1026 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001027
deadbeefab9b2d12015-10-14 11:33:11 -07001028 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001029 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030
Steve Antonba818672017-11-06 10:21:57 -08001031 configuration_ = configuration;
1032
Steve Anton75737c02017-11-06 10:37:17 -08001033 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1034 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1035 if (!configuration.certificates.empty()) {
1036 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1037 // just picking the first one. The decision should be made based on the DTLS
1038 // handshake. The DTLS negotiations need to know about all certificates.
1039 certificate = configuration.certificates[0];
1040 }
1041
Steve Antond25da372017-11-06 14:50:29 -08001042 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001043
1044 if (options.disable_encryption) {
1045 dtls_enabled_ = false;
1046 } else {
1047 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001048 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001049 // |configuration| can override the default |dtls_enabled_| value.
1050 if (configuration.enable_dtls_srtp) {
1051 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1052 }
1053 }
1054
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001055 if (configuration.use_media_transport_for_data_channels) {
1056 if (configuration.enable_rtp_data_channel) {
1057 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1058 "use_media_transport_for_data_channels are "
1059 "incompatible and cannot both be set to true";
1060 return false;
1061 }
1062 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1063 } else if (configuration.enable_rtp_data_channel) {
1064 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1065 // set. It takes precendence over the disable_sctp_data_channels
1066 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001067 data_channel_type_ = cricket::DCT_RTP;
1068 } else {
1069 // DTLS has to be enabled to use SCTP.
1070 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1071 data_channel_type_ = cricket::DCT_SCTP;
1072 }
1073 }
1074
1075 video_options_.screencast_min_bitrate_kbps =
1076 configuration.screencast_min_bitrate;
1077 audio_options_.combined_audio_video_bwe =
1078 configuration.combined_audio_video_bwe;
1079
1080 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001081 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001082
1083 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001084 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001085
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001086 audio_options_.audio_jitter_buffer_min_delay_ms =
1087 configuration.audio_jitter_buffer_min_delay_ms;
1088
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001089 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1090 configuration.audio_jitter_buffer_enable_rtx_handling;
1091
Steve Anton75737c02017-11-06 10:37:17 -08001092 // Whether the certificate generator/certificate is null or not determines
1093 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1094 // the right instructions by clearing the variables if needed.
1095 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001096 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001097 certificate = nullptr;
1098 } else if (certificate) {
1099 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001100 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001101 }
1102
1103 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1104 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001105 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001106 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1107 this, &PeerConnection::OnCertificateReady);
1108
1109 if (options.disable_encryption) {
1110 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1111 }
1112
1113 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001114 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001115 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001116
Steve Anton4171afb2017-11-20 10:20:22 -08001117 // Add default audio/video transceivers for Plan B SDP.
1118 if (!IsUnifiedPlan()) {
1119 transceivers_.push_back(
1120 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1121 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1122 transceivers_.push_back(
1123 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1124 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1125 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001126 int delay_ms =
1127 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001128 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1129 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 return true;
1131}
1132
Steve Anton038834f2017-07-14 15:59:59 -07001133RTCError PeerConnection::ValidateConfiguration(
1134 const RTCConfiguration& config) const {
1135 if (config.ice_regather_interval_range &&
1136 config.continual_gathering_policy == GATHER_ONCE) {
1137 return RTCError(RTCErrorType::INVALID_PARAMETER,
1138 "ice_regather_interval_range specified but continual "
1139 "gathering policy is GATHER_ONCE");
1140 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001141 auto result =
1142 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1143 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001144}
1145
Yves Gerey665174f2018-06-19 15:03:05 +02001146rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001147 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1148 "Plan SdpSemantics. Please use GetSenders "
1149 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001150 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001151}
1152
Yves Gerey665174f2018-06-19 15:03:05 +02001153rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001154 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1155 "Plan SdpSemantics. Please use GetReceivers "
1156 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001157 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158}
1159
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001160bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001161 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001162 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1163 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001164 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 if (IsClosed()) {
1166 return false;
1167 }
deadbeefab9b2d12015-10-14 11:33:11 -07001168 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169 return false;
1170 }
deadbeefab9b2d12015-10-14 11:33:11 -07001171
1172 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001173 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1174 observer->SignalAudioTrackAdded.connect(this,
1175 &PeerConnection::OnAudioTrackAdded);
1176 observer->SignalAudioTrackRemoved.connect(
1177 this, &PeerConnection::OnAudioTrackRemoved);
1178 observer->SignalVideoTrackAdded.connect(this,
1179 &PeerConnection::OnVideoTrackAdded);
1180 observer->SignalVideoTrackRemoved.connect(
1181 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001182 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001183
deadbeefab9b2d12015-10-14 11:33:11 -07001184 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001185 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001186 }
1187 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001188 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001189 }
1190
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001191 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001192 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193 return true;
1194}
1195
1196void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001197 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001198 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1199 "Plan SdpSemantics. Please use RemoveTrack "
1200 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001201 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001202 if (!IsClosed()) {
1203 for (const auto& track : local_stream->GetAudioTracks()) {
1204 RemoveAudioTrack(track.get(), local_stream);
1205 }
1206 for (const auto& track : local_stream->GetVideoTracks()) {
1207 RemoveVideoTrack(track.get(), local_stream);
1208 }
deadbeefab9b2d12015-10-14 11:33:11 -07001209 }
deadbeefab9b2d12015-10-14 11:33:11 -07001210 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001211 stream_observers_.erase(
1212 std::remove_if(
1213 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001214 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001215 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001216 }),
1217 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001219 if (IsClosed()) {
1220 return;
1221 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001222 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223}
1224
Steve Anton2d6c76a2018-01-05 17:10:52 -08001225RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001226 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001227 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001228 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001229 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001230 if (!track) {
1231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1232 }
1233 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1234 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1235 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1236 "Track has invalid kind: " + track->kind());
1237 }
Steve Antonf9381f02017-12-14 10:23:57 -08001238 if (IsClosed()) {
1239 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1240 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001241 }
Steve Anton4171afb2017-11-20 10:20:22 -08001242 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001243 LOG_AND_RETURN_ERROR(
1244 RTCErrorType::INVALID_PARAMETER,
1245 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001246 }
Steve Antonf9381f02017-12-14 10:23:57 -08001247 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001248 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1249 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001250 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001251 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001252 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001253 }
1254 return sender_or_error;
1255}
deadbeefe1f9d832016-01-14 15:35:42 -08001256
Steve Antonf9381f02017-12-14 10:23:57 -08001257RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1258PeerConnection::AddTrackPlanB(
1259 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001260 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001261 if (stream_ids.size() > 1u) {
1262 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1263 "AddTrack with more than one stream is not "
1264 "supported with Plan B semantics.");
1265 }
1266 std::vector<std::string> adjusted_stream_ids = stream_ids;
1267 if (adjusted_stream_ids.empty()) {
1268 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1269 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001270 cricket::MediaType media_type =
1271 (track->kind() == MediaStreamTrackInterface::kAudioKind
1272 ? cricket::MEDIA_TYPE_AUDIO
1273 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001274 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001275 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001276 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001277 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001278 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001279 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001280 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001281 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001282 if (sender_info) {
1283 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001284 }
Steve Antonf9381f02017-12-14 10:23:57 -08001285 } else {
1286 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001287 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001288 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001289 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001290 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001291 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001292 if (sender_info) {
1293 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001294 }
deadbeefe1f9d832016-01-14 15:35:42 -08001295 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001296 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001297}
deadbeefe1f9d832016-01-14 15:35:42 -08001298
Steve Antonf9381f02017-12-14 10:23:57 -08001299RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1300PeerConnection::AddTrackUnifiedPlan(
1301 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001302 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001303 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1304 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001305 RTC_LOG(LS_INFO) << "Reusing an existing "
1306 << cricket::MediaTypeToString(transceiver->media_type())
1307 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001308 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001309 transceiver->internal()->set_direction(
1310 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001312 transceiver->internal()->set_direction(
1313 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001314 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001315 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001316 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001317 } else {
1318 cricket::MediaType media_type =
1319 (track->kind() == MediaStreamTrackInterface::kAudioKind
1320 ? cricket::MEDIA_TYPE_AUDIO
1321 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001322 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1323 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001324 std::string sender_id = track->id();
1325 // Avoid creating a sender with an existing ID by generating a random ID.
1326 // This can happen if this is the second time AddTrack has created a sender
1327 // for this track.
1328 if (FindSenderById(sender_id)) {
1329 sender_id = rtc::CreateRandomUuid();
1330 }
Florent Castelli892acf02018-10-01 22:47:20 +02001331 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001332 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1333 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001334 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001335 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001336 }
Steve Antonf9381f02017-12-14 10:23:57 -08001337 return transceiver->sender();
1338}
1339
1340rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1341PeerConnection::FindFirstTransceiverForAddedTrack(
1342 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1343 RTC_DCHECK(track);
1344 for (auto transceiver : transceivers_) {
1345 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001346 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001347 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001348 !transceiver->internal()->has_ever_been_used_to_send() &&
1349 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001350 return transceiver;
1351 }
1352 }
1353 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001354}
1355
1356bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1357 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001358 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001359}
1360
Steve Anton24db5732018-07-23 10:27:33 -07001361RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001362 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001363 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001364 if (!sender) {
1365 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1366 }
deadbeefe1f9d832016-01-14 15:35:42 -08001367 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001368 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1369 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001370 }
Steve Antonf9381f02017-12-14 10:23:57 -08001371 if (IsUnifiedPlan()) {
1372 auto transceiver = FindTransceiverBySender(sender);
1373 if (!transceiver || !sender->track()) {
1374 return RTCError::OK();
1375 }
1376 sender->SetTrack(nullptr);
1377 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001378 transceiver->internal()->set_direction(
1379 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001380 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001381 transceiver->internal()->set_direction(
1382 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001383 }
Steve Anton4171afb2017-11-20 10:20:22 -08001384 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001385 bool removed;
1386 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1387 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1388 } else {
1389 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1390 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1391 }
1392 if (!removed) {
1393 LOG_AND_RETURN_ERROR(
1394 RTCErrorType::INVALID_PARAMETER,
1395 "Couldn't find sender " + sender->id() + " to remove.");
1396 }
Steve Anton4171afb2017-11-20 10:20:22 -08001397 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001398 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001399 return RTCError::OK();
1400}
1401
1402rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1403PeerConnection::FindTransceiverBySender(
1404 rtc::scoped_refptr<RtpSenderInterface> sender) {
1405 for (auto transceiver : transceivers_) {
1406 if (transceiver->sender() == sender) {
1407 return transceiver;
1408 }
1409 }
1410 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001411}
1412
Steve Anton9158ef62017-11-27 13:01:52 -08001413RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1414PeerConnection::AddTransceiver(
1415 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1416 return AddTransceiver(track, RtpTransceiverInit());
1417}
1418
1419RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1420PeerConnection::AddTransceiver(
1421 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1422 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001423 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001424 RTC_CHECK(IsUnifiedPlan())
1425 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001426 if (!track) {
1427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1428 }
1429 cricket::MediaType media_type;
1430 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1431 media_type = cricket::MEDIA_TYPE_AUDIO;
1432 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1433 media_type = cricket::MEDIA_TYPE_VIDEO;
1434 } else {
1435 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1436 "Track kind is not audio or video");
1437 }
1438 return AddTransceiver(media_type, track, init);
1439}
1440
1441RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1442PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1443 return AddTransceiver(media_type, RtpTransceiverInit());
1444}
1445
1446RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1447PeerConnection::AddTransceiver(cricket::MediaType media_type,
1448 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001449 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001450 RTC_CHECK(IsUnifiedPlan())
1451 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001452 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1453 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1455 "media type is not audio or video");
1456 }
1457 return AddTransceiver(media_type, nullptr, init);
1458}
1459
1460RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1461PeerConnection::AddTransceiver(
1462 cricket::MediaType media_type,
1463 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001464 const RtpTransceiverInit& init,
1465 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001466 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1467 media_type == cricket::MEDIA_TYPE_VIDEO));
1468 if (track) {
1469 RTC_DCHECK_EQ(media_type,
1470 (track->kind() == MediaStreamTrackInterface::kAudioKind
1471 ? cricket::MEDIA_TYPE_AUDIO
1472 : cricket::MEDIA_TYPE_VIDEO));
1473 }
1474
Amit Hilbuchaa584152019-02-06 17:09:52 -08001475 size_t num_rids = absl::c_count_if(init.send_encodings,
1476 [](const RtpEncodingParameters& encoding) {
1477 return !encoding.rid.empty();
1478 });
1479 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001480 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001481 RTCErrorType::INVALID_PARAMETER,
1482 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001483 }
1484
Amit Hilbuchaa584152019-02-06 17:09:52 -08001485 if (absl::c_any_of(init.send_encodings,
1486 [](const RtpEncodingParameters& encoding) {
1487 return encoding.ssrc.has_value();
1488 })) {
1489 LOG_AND_RETURN_ERROR(
1490 RTCErrorType::UNSUPPORTED_PARAMETER,
1491 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001492 }
1493
1494 RtpParameters parameters;
1495 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001496
1497 // Encodings are dropped from the tail if too many are provided.
1498 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1499 parameters.encodings.erase(
1500 parameters.encodings.begin() + kMaxSimulcastStreams,
1501 parameters.encodings.end());
1502 }
1503
1504 // Single RID should be removed.
1505 if (parameters.encodings.size() == 1 &&
1506 !parameters.encodings[0].rid.empty()) {
1507 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1508 parameters.encodings[0].rid.clear();
1509 }
1510
1511 // If RIDs were not provided, they are generated for simulcast scenario.
1512 if (parameters.encodings.size() > 1 && num_rids == 0) {
1513 rtc::UniqueStringGenerator rid_generator;
1514 for (RtpEncodingParameters& encoding : parameters.encodings) {
1515 encoding.rid = rid_generator();
1516 }
1517 }
1518
Florent Castelli892acf02018-10-01 22:47:20 +02001519 if (UnimplementedRtpParameterHasValue(parameters)) {
1520 LOG_AND_RETURN_ERROR(
1521 RTCErrorType::UNSUPPORTED_PARAMETER,
1522 "Attempted to set an unimplemented parameter of RtpParameters.");
1523 }
Steve Anton9158ef62017-11-27 13:01:52 -08001524
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001525 auto result = cricket::CheckRtpParametersValues(parameters);
1526 if (!result.ok()) {
1527 LOG_AND_RETURN_ERROR(result.type(), result.message());
1528 }
1529
Steve Anton3d954a62018-04-02 11:27:23 -07001530 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1531 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001532 // Set the sender ID equal to the track ID if the track is specified unless
1533 // that sender ID is already in use.
1534 std::string sender_id =
1535 (track && !FindSenderById(track->id()) ? track->id()
1536 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001537 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001538 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001539 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1540 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1541 transceiver->internal()->set_direction(init.direction);
1542
Steve Anton22da89f2018-01-25 13:58:07 -08001543 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001544 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001545 }
Steve Antonf9381f02017-12-14 10:23:57 -08001546
1547 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1548}
1549
Steve Anton02ee47c2018-01-10 16:26:06 -08001550rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1551PeerConnection::CreateSender(
1552 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001553 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001554 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001555 const std::vector<std::string>& stream_ids,
1556 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001557 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001558 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1559 RTC_DCHECK(!track ||
1560 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1561 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1562 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001563 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001564 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001565 } else {
1566 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1567 RTC_DCHECK(!track ||
1568 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1569 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001570 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001571 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001572 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001573 bool set_track_succeeded = sender->SetTrack(track);
1574 RTC_DCHECK(set_track_succeeded);
1575 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001576 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001577 return sender;
1578}
1579
1580rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1581PeerConnection::CreateReceiver(cricket::MediaType media_type,
1582 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001583 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1584 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001585 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001586 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001587 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1588 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001589 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001590 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001591 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001592 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001593 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1594 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001595 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001596 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001597 return receiver;
1598}
1599
1600rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1601PeerConnection::CreateAndAddTransceiver(
1602 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1603 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1604 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001605 // Ensure that the new sender does not have an ID that is already in use by
1606 // another sender.
1607 // Allow receiver IDs to conflict since those come from remote SDP (which
1608 // could be invalid, but should not cause a crash).
1609 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001610 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1611 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001612 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001613 transceiver->internal()->SignalNegotiationNeeded.connect(
1614 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001615 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001616}
1617
Steve Anton52d86772018-02-20 15:48:12 -08001618void PeerConnection::OnNegotiationNeeded() {
1619 RTC_DCHECK_RUN_ON(signaling_thread());
1620 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001621 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001622}
1623
deadbeeffac06552015-11-25 11:26:01 -08001624rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001625 const std::string& kind,
1626 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001627 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1628 "Plan SdpSemantics. Please use AddTransceiver "
1629 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001630 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001631 if (IsClosed()) {
1632 return nullptr;
1633 }
Steve Anton4171afb2017-11-20 10:20:22 -08001634
Seth Hampson5b4f0752018-04-02 16:31:36 -07001635 // Internally we need to have one stream with Plan B semantics, so we
1636 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001637 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001638 if (stream_id.empty()) {
1639 stream_ids.push_back(rtc::CreateRandomUuid());
1640 RTC_LOG(LS_INFO)
1641 << "No stream_id specified for sender. Generated stream ID: "
1642 << stream_ids[0];
1643 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001644 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001645 }
1646
Steve Anton4171afb2017-11-20 10:20:22 -08001647 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001648 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001649 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001650 auto* audio_sender = new AudioRtpSender(
1651 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001652 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001653 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001654 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001655 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001656 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001657 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001658 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001659 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001660 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001661 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001662 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001663 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001664 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001665 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001666 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001667 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001668
deadbeefe1f9d832016-01-14 15:35:42 -08001669 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001670}
1671
deadbeef70ab1a12015-09-28 16:53:55 -07001672std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1673 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001674 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001675 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001676 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001677 }
1678 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001679}
1680
Steve Anton4171afb2017-11-20 10:20:22 -08001681std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1682PeerConnection::GetSendersInternal() const {
1683 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1684 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001685 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001686 auto senders = transceiver->internal()->senders();
1687 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1688 }
1689 return all_senders;
1690}
1691
deadbeef70ab1a12015-09-28 16:53:55 -07001692std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1693PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001694 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001695 for (const auto& receiver : GetReceiversInternal()) {
1696 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001697 }
1698 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001699}
1700
Steve Anton4171afb2017-11-20 10:20:22 -08001701std::vector<
1702 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1703PeerConnection::GetReceiversInternal() const {
1704 std::vector<
1705 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1706 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001707 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001708 auto receivers = transceiver->internal()->receivers();
1709 all_receivers.insert(all_receivers.end(), receivers.begin(),
1710 receivers.end());
1711 }
1712 return all_receivers;
1713}
1714
Steve Anton9158ef62017-11-27 13:01:52 -08001715std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1716PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001717 RTC_CHECK(IsUnifiedPlan())
1718 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001719 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001720 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001721 all_transceivers.push_back(transceiver);
1722 }
1723 return all_transceivers;
1724}
1725
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001726bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001727 MediaStreamTrackInterface* track,
1728 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001729 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001730 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001731 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001732 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733 return false;
1734 }
1735
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001736 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001737 // The StatsCollector is used to tell if a track is valid because it may
1738 // remember tracks that the PeerConnection previously removed.
1739 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1741 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001742 return false;
1743 }
Steve Antonad182762018-09-05 20:22:40 +00001744 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1745 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746 return true;
1747}
1748
hbos74e1a4f2016-09-15 23:33:01 -07001749void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001750 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001751 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001752 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001753 stats_collector_->GetStatsReport(callback);
1754}
1755
Henrik Boström1df1bf82018-03-20 13:24:20 +01001756void PeerConnection::GetStats(
1757 rtc::scoped_refptr<RtpSenderInterface> selector,
1758 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1759 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1760 RTC_DCHECK(callback);
1761 RTC_DCHECK(stats_collector_);
1762 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1763 if (selector) {
1764 for (const auto& proxy_transceiver : transceivers_) {
1765 for (const auto& proxy_sender :
1766 proxy_transceiver->internal()->senders()) {
1767 if (proxy_sender == selector) {
1768 internal_sender = proxy_sender->internal();
1769 break;
1770 }
1771 }
1772 if (internal_sender)
1773 break;
1774 }
1775 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001776 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001777 // belong to the PeerConnection (in Plan B, senders can be removed from the
1778 // PeerConnection). This means that "all the stats objects representing the
1779 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1780 // produces an empty stats report.
1781 stats_collector_->GetStatsReport(internal_sender, callback);
1782}
1783
1784void PeerConnection::GetStats(
1785 rtc::scoped_refptr<RtpReceiverInterface> selector,
1786 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1787 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1788 RTC_DCHECK(callback);
1789 RTC_DCHECK(stats_collector_);
1790 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1791 if (selector) {
1792 for (const auto& proxy_transceiver : transceivers_) {
1793 for (const auto& proxy_receiver :
1794 proxy_transceiver->internal()->receivers()) {
1795 if (proxy_receiver == selector) {
1796 internal_receiver = proxy_receiver->internal();
1797 break;
1798 }
1799 }
1800 if (internal_receiver)
1801 break;
1802 }
1803 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001804 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001805 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1806 // the PeerConnection). This means that "all the stats objects representing
1807 // the selector" is an empty set. Invoking GetStatsReport() with a null
1808 // selector produces an empty stats report.
1809 stats_collector_->GetStatsReport(internal_receiver, callback);
1810}
1811
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1813 return signaling_state_;
1814}
1815
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001816PeerConnectionInterface::IceConnectionState
1817PeerConnection::ice_connection_state() {
1818 return ice_connection_state_;
1819}
1820
Alex Loiko9289eda2018-11-23 16:18:59 +00001821PeerConnectionInterface::IceConnectionState
1822PeerConnection::standardized_ice_connection_state() {
1823 return standardized_ice_connection_state_;
1824}
1825
Jonas Olsson635474e2018-10-18 15:58:17 +02001826PeerConnectionInterface::PeerConnectionState
1827PeerConnection::peer_connection_state() {
1828 return connection_state_;
1829}
1830
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001831PeerConnectionInterface::IceGatheringState
1832PeerConnection::ice_gathering_state() {
1833 return ice_gathering_state_;
1834}
1835
Yves Gerey665174f2018-06-19 15:03:05 +02001836rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837 const std::string& label,
1838 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001839 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001840 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001841
deadbeefab9b2d12015-10-14 11:33:11 -07001842 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001843
kwibergd1fe2812016-04-27 06:47:29 -07001844 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001845 if (config) {
1846 internal_config.reset(new InternalDataChannelInit(*config));
1847 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001848 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001849 InternalCreateDataChannel(label, internal_config.get()));
1850 if (!channel.get()) {
1851 return nullptr;
1852 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001854 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1855 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001856 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001857 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001858 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001859 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860 return DataChannelProxy::Create(signaling_thread(), channel.get());
1861}
1862
1863void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001864 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001865 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001866
nisse7ce109a2017-01-31 00:57:56 -08001867 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001868 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001869 return;
1870 }
deadbeefab9b2d12015-10-14 11:33:11 -07001871
Steve Anton8d3444d2017-10-20 15:30:51 -07001872 if (IsClosed()) {
1873 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001874 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001875 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001876 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001877 return;
1878 }
1879
zhihuang1c378ed2017-08-17 14:10:50 -07001880 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001881 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001882 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001883 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001884 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001885 return;
1886 }
1887
Steve Anton22da89f2018-01-25 13:58:07 -08001888 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1889 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1890 if (IsUnifiedPlan()) {
1891 RTCError error = HandleLegacyOfferOptions(options);
1892 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001893 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001894 return;
1895 }
1896 }
1897
zhihuang1c378ed2017-08-17 14:10:50 -07001898 cricket::MediaSessionOptions session_options;
1899 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001900 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001901}
1902
Steve Anton22da89f2018-01-25 13:58:07 -08001903RTCError PeerConnection::HandleLegacyOfferOptions(
1904 const RTCOfferAnswerOptions& options) {
1905 RTC_DCHECK(IsUnifiedPlan());
1906
1907 if (options.offer_to_receive_audio == 0) {
1908 RemoveRecvDirectionFromReceivingTransceiversOfType(
1909 cricket::MEDIA_TYPE_AUDIO);
1910 } else if (options.offer_to_receive_audio == 1) {
1911 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1912 } else if (options.offer_to_receive_audio > 1) {
1913 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1914 "offer_to_receive_audio > 1 is not supported.");
1915 }
1916
1917 if (options.offer_to_receive_video == 0) {
1918 RemoveRecvDirectionFromReceivingTransceiversOfType(
1919 cricket::MEDIA_TYPE_VIDEO);
1920 } else if (options.offer_to_receive_video == 1) {
1921 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1922 } else if (options.offer_to_receive_video > 1) {
1923 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1924 "offer_to_receive_video > 1 is not supported.");
1925 }
1926
1927 return RTCError::OK();
1928}
1929
1930void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1931 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001932 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001933 RtpTransceiverDirection new_direction =
1934 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1935 if (new_direction != transceiver->direction()) {
1936 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1937 << " transceiver (MID="
1938 << transceiver->mid().value_or("<not set>") << ") from "
1939 << RtpTransceiverDirectionToString(
1940 transceiver->direction())
1941 << " to "
1942 << RtpTransceiverDirectionToString(new_direction)
1943 << " since CreateOffer specified offer_to_receive=0";
1944 transceiver->internal()->set_direction(new_direction);
1945 }
Steve Anton22da89f2018-01-25 13:58:07 -08001946 }
1947}
1948
1949void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1950 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001951 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08001952 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001953 RTC_LOG(LS_INFO)
1954 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1955 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001956 RtpTransceiverInit init;
1957 init.direction = RtpTransceiverDirection::kRecvOnly;
1958 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1959 }
1960}
1961
1962std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1963PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1964 std::vector<
1965 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1966 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001967 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001968 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001969 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1970 receiving_transceivers.push_back(transceiver);
1971 }
1972 }
1973 return receiving_transceivers;
1974}
1975
htaa2a49d92016-03-04 02:51:39 -08001976void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1977 const RTCOfferAnswerOptions& options) {
1978 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001979 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001980 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001981 return;
1982 }
1983
Steve Antondffead82018-02-06 10:31:29 -08001984 if (!(signaling_state_ == kHaveRemoteOffer ||
1985 signaling_state_ == kHaveLocalPrAnswer)) {
1986 std::string error =
1987 "PeerConnection cannot create an answer in a state other than "
1988 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001989 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001990 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001991 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001992 return;
1993 }
1994
Steve Antondffead82018-02-06 10:31:29 -08001995 // The remote description should be set if we're in the right state.
1996 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001997
Steve Anton22da89f2018-01-25 13:58:07 -08001998 if (IsUnifiedPlan()) {
1999 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2000 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2001 "supported with Unified Plan semantics. Use the "
2002 "RtpTransceiver API instead.";
2003 }
2004 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2005 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2006 "supported with Unified Plan semantics. Use the "
2007 "RtpTransceiver API instead.";
2008 }
2009 }
2010
htaa2a49d92016-03-04 02:51:39 -08002011 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002012 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002013
Steve Antond25da372017-11-06 14:50:29 -08002014 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015}
2016
2017void PeerConnection::SetLocalDescription(
2018 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002019 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002020 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002021
Steve Anton80dd7b52018-02-16 17:08:42 -08002022 // The SetLocalDescription contract is that we take ownership of the session
2023 // description regardless of the outcome, so wrap it in a unique_ptr right
2024 // away. Ideally, SetLocalDescription's signature will be changed to take the
2025 // description as a unique_ptr argument to formalize this agreement.
2026 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2027
nisse7ce109a2017-01-31 00:57:56 -08002028 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002029 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 return;
2031 }
Steve Anton8a006912017-12-04 15:25:56 -08002032
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002034 PostSetSessionDescriptionFailure(
2035 observer,
2036 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 return;
2038 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002039
Steve Anton80dd7b52018-02-16 17:08:42 -08002040 // If a session error has occurred the PeerConnection is in a possibly
2041 // inconsistent state so fail right away.
2042 if (session_error() != SessionError::kNone) {
2043 std::string error_message = GetSessionErrorMsg();
2044 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002045 PostSetSessionDescriptionFailure(
2046 observer,
2047 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002048 return;
2049 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002050
Steve Anton80dd7b52018-02-16 17:08:42 -08002051 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2052 if (!error.ok()) {
2053 std::string error_message = GetSetDescriptionErrorMessage(
2054 cricket::CS_LOCAL, desc->GetType(), error);
2055 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002056 PostSetSessionDescriptionFailure(
2057 observer,
2058 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002059 return;
2060 }
2061
2062 // Grab the description type before moving ownership to ApplyLocalDescription,
2063 // which may destroy it before returning.
2064 const SdpType type = desc->GetType();
2065
2066 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002067 // |desc| may be destroyed at this point.
2068
2069 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002070 // If ApplyLocalDescription fails, the PeerConnection could be in an
2071 // inconsistent state, so act conservatively here and set the session error
2072 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2073 SetSessionError(SessionError::kContent, error.message());
2074 std::string error_message =
2075 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2076 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002077 PostSetSessionDescriptionFailure(
2078 observer,
2079 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002080 return;
2081 }
Steve Anton8a006912017-12-04 15:25:56 -08002082 RTC_DCHECK(local_description());
2083
2084 PostSetSessionDescriptionSuccess(observer);
2085
Steve Antonad182762018-09-05 20:22:40 +00002086 // MaybeStartGathering needs to be called after posting
2087 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2088 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002089 transport_controller_->MaybeStartGathering();
2090
Steve Antona3a92c22017-12-07 10:27:41 -08002091 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002092 // TODO(deadbeef): We already had to hop to the network thread for
2093 // MaybeStartGathering...
2094 network_thread()->Invoke<void>(
2095 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2096 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002097 // Make UMA notes about what was agreed to.
2098 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002099 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002100 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002101}
2102
2103RTCError PeerConnection::ApplyLocalDescription(
2104 std::unique_ptr<SessionDescriptionInterface> desc) {
2105 RTC_DCHECK_RUN_ON(signaling_thread());
2106 RTC_DCHECK(desc);
2107
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 // Update stats here so that we have the most recent stats for tracks and
2109 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002110 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002111
Steve Antondcc3c022017-12-22 16:02:54 -08002112 // Take a reference to the old local description since it's used below to
2113 // compare against the new local description. When setting the new local
2114 // description, grab ownership of the replaced session description in case it
2115 // is the same as |old_local_description|, to keep it alive for the duration
2116 // of the method.
2117 const SessionDescriptionInterface* old_local_description =
2118 local_description();
2119 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002120 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002121 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002122 replaced_local_description = pending_local_description_
2123 ? std::move(pending_local_description_)
2124 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002125 current_local_description_ = std::move(desc);
2126 pending_local_description_ = nullptr;
2127 current_remote_description_ = std::move(pending_remote_description_);
2128 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002129 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002130 pending_local_description_ = std::move(desc);
2131 }
2132 // The session description to apply now must be accessed by
2133 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002134 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002135
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002136 if (!is_caller_) {
2137 if (remote_description()) {
2138 // Remote description was applied first, so this PC is the callee.
2139 is_caller_ = false;
2140 } else {
2141 // Local description is applied first, so this PC is the caller.
2142 is_caller_ = true;
2143 }
2144 }
2145
Zhi Huange830e682018-03-30 10:48:35 -07002146 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2147 if (!error.ok()) {
2148 return error;
2149 }
2150
Steve Antondcc3c022017-12-22 16:02:54 -08002151 if (IsUnifiedPlan()) {
2152 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002153 cricket::CS_LOCAL, *local_description(), old_local_description,
2154 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002155 if (!error.ok()) {
2156 return error;
2157 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002158 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2159 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002160 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002161 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2162 // Note that code paths that don't set MID won't be able to use
2163 // information about DTLS transports.
2164 if (transceiver->mid()) {
2165 auto dtls_transport =
2166 LookupDtlsTransportByMidInternal(*transceiver->mid());
2167 transceiver->internal()->sender_internal()->set_transport(
2168 dtls_transport);
2169 transceiver->internal()->receiver_internal()->set_transport(
2170 dtls_transport);
2171 }
2172
Steve Antondcc3c022017-12-22 16:02:54 -08002173 const ContentInfo* content =
2174 FindMediaSectionForTransceiver(transceiver, local_description());
2175 if (!content) {
2176 continue;
2177 }
2178 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002179 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2180 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002181 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002182 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2183 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2184 // "recvonly", process the removal of a remote track for the media
2185 // description, given transceiver, removeList, and muteTracks.
2186 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2187 (transceiver->internal()->fired_direction() &&
2188 RtpTransceiverDirectionHasRecv(
2189 *transceiver->internal()->fired_direction()))) {
2190 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2191 &removed_streams);
2192 }
2193 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2194 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002195 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002196 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002197 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002198 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002199 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002200 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002201 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002202 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002203 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002204 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002205 }
2206 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002207 // Media channels will be created only when offer is set. These may use new
2208 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002209 if (type == SdpType::kOffer) {
2210 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2211 // description is applied. Restore back to old description.
2212 RTCError error = CreateChannels(*local_description()->description());
2213 if (!error.ok()) {
2214 return error;
2215 }
2216 }
Steve Antondcc3c022017-12-22 16:02:54 -08002217 // Remove unused channels if MediaContentDescription is rejected.
2218 RemoveUnusedChannels(local_description()->description());
2219 }
Steve Anton8a006912017-12-04 15:25:56 -08002220
Zhi Huange830e682018-03-30 10:48:35 -07002221 error = UpdateSessionState(type, cricket::CS_LOCAL,
2222 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002223 if (!error.ok()) {
2224 return error;
2225 }
Steve Antondcc3c022017-12-22 16:02:54 -08002226
Steve Anton8a006912017-12-04 15:25:56 -08002227 if (remote_description()) {
2228 // Now that we have a local description, we can push down remote candidates.
2229 UseCandidatesInSessionDescription(remote_description());
2230 }
2231
2232 pending_ice_restarts_.clear();
2233 if (session_error() != SessionError::kNone) {
2234 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2235 }
2236
deadbeefab9b2d12015-10-14 11:33:11 -07002237 // If setting the description decided our SSL role, allocate any necessary
2238 // SCTP sids.
2239 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002240 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002241 AllocateSctpSids(role);
2242 }
2243
Steve Antond3679212018-01-17 17:41:02 -08002244 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002245 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002246 const ContentInfo* content =
2247 FindMediaSectionForTransceiver(transceiver, local_description());
2248 if (!content) {
2249 continue;
2250 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002251 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2252 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002253 // 0 is a special value meaning "this sender has no associated send
2254 // stream". Need to call this so the sender won't attempt to configure
2255 // a no longer existing stream and run into DCHECKs in the lower
2256 // layers.
2257 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002258 } else {
2259 // Get the StreamParams from the channel which could generate SSRCs.
2260 const std::vector<StreamParams>& streams = channel->local_streams();
2261 transceiver->internal()->sender_internal()->set_stream_ids(
2262 streams[0].stream_ids());
2263 transceiver->internal()->sender_internal()->SetSsrc(
2264 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002265 }
2266 }
2267 } else {
2268 // Plan B semantics.
2269
Steve Antondcc3c022017-12-22 16:02:54 -08002270 // Update state and SSRC of local MediaStreams and DataChannels based on the
2271 // local session description.
2272 const cricket::ContentInfo* audio_content =
2273 GetFirstAudioContent(local_description()->description());
2274 if (audio_content) {
2275 if (audio_content->rejected) {
2276 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2277 } else {
2278 const cricket::AudioContentDescription* audio_desc =
2279 audio_content->media_description()->as_audio();
2280 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2281 }
deadbeeffaac4972015-11-12 15:33:07 -08002282 }
deadbeefab9b2d12015-10-14 11:33:11 -07002283
Steve Antondcc3c022017-12-22 16:02:54 -08002284 const cricket::ContentInfo* video_content =
2285 GetFirstVideoContent(local_description()->description());
2286 if (video_content) {
2287 if (video_content->rejected) {
2288 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2289 } else {
2290 const cricket::VideoContentDescription* video_desc =
2291 video_content->media_description()->as_video();
2292 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2293 }
deadbeeffaac4972015-11-12 15:33:07 -08002294 }
deadbeefab9b2d12015-10-14 11:33:11 -07002295 }
2296
2297 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002298 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002299 if (data_content) {
2300 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002301 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002302 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002303 cricket::kMediaProtocolRtpPrefix)) {
2304 UpdateLocalRtpDataChannels(data_desc->streams());
2305 }
2306 }
2307
Steve Anton8a006912017-12-04 15:25:56 -08002308 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002309}
2310
Steve Anton06817cd2018-12-18 15:55:30 -08002311// The SDP parser used to populate these values by default for the 'content
2312// name' if an a=mid line was absent.
2313static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2314 switch (media_type) {
2315 case cricket::MEDIA_TYPE_AUDIO:
2316 return cricket::CN_AUDIO;
2317 case cricket::MEDIA_TYPE_VIDEO:
2318 return cricket::CN_VIDEO;
2319 case cricket::MEDIA_TYPE_DATA:
2320 return cricket::CN_DATA;
2321 }
2322 RTC_NOTREACHED();
2323 return "";
2324}
2325
2326void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002327 cricket::SessionDescription* new_remote_description) {
2328 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002329 const cricket::ContentInfos& local_contents =
2330 (local_description() ? local_description()->description()->contents()
2331 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002332 const cricket::ContentInfos& remote_contents =
2333 (remote_description() ? remote_description()->description()->contents()
2334 : cricket::ContentInfos());
2335 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2336 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002337 if (!content.name.empty()) {
2338 continue;
2339 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002340 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002341 absl::string_view source_explanation;
2342 if (IsUnifiedPlan()) {
2343 if (i < local_contents.size()) {
2344 new_mid = local_contents[i].name;
2345 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002346 } else if (i < remote_contents.size()) {
2347 new_mid = remote_contents[i].name;
2348 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002349 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002350 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002351 source_explanation = "generated just now";
2352 }
2353 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002354 new_mid = std::string(
2355 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002356 source_explanation = "to match pre-existing behavior";
2357 }
Steve Antond7180cc2019-02-07 10:44:53 -08002358 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002359 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002360 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002361 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2362 << " is missing an a=mid line. Filling in the value '"
2363 << new_mid << "' " << source_explanation << ".";
2364 }
2365}
2366
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002367void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002368 SetSessionDescriptionObserver* observer,
2369 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002370 SetRemoteDescription(
2371 std::unique_ptr<SessionDescriptionInterface>(desc),
2372 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2373 new SetRemoteDescriptionObserverAdapter(this, observer)));
2374}
2375
2376void PeerConnection::SetRemoteDescription(
2377 std::unique_ptr<SessionDescriptionInterface> desc,
2378 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002379 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002380
nisse7ce109a2017-01-31 00:57:56 -08002381 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002382 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002383 return;
2384 }
Steve Anton8a006912017-12-04 15:25:56 -08002385
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002386 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002387 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002388 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002389 return;
2390 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002391
Steve Anton80dd7b52018-02-16 17:08:42 -08002392 // If a session error has occurred the PeerConnection is in a possibly
2393 // inconsistent state so fail right away.
2394 if (session_error() != SessionError::kNone) {
2395 std::string error_message = GetSessionErrorMsg();
2396 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2397 observer->OnSetRemoteDescriptionComplete(
2398 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2399 return;
2400 }
Steve Anton71439a62018-02-15 11:53:06 -08002401
Steve Antonba42e992018-04-09 14:10:01 -07002402 if (desc->GetType() == SdpType::kOffer) {
2403 // Report to UMA the format of the received offer.
2404 ReportSdpFormatReceived(*desc);
2405 }
2406
Steve Anton06817cd2018-12-18 15:55:30 -08002407 // Handle remote descriptions missing a=mid lines for interop with legacy end
2408 // points.
2409 FillInMissingRemoteMids(desc->description());
2410
Steve Anton80dd7b52018-02-16 17:08:42 -08002411 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002412 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002413 std::string error_message = GetSetDescriptionErrorMessage(
2414 cricket::CS_REMOTE, desc->GetType(), error);
2415 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002416 observer->OnSetRemoteDescriptionComplete(
2417 RTCError(error.type(), std::move(error_message)));
2418 return;
2419 }
Steve Anton71439a62018-02-15 11:53:06 -08002420
Steve Anton80dd7b52018-02-16 17:08:42 -08002421 // Grab the description type before moving ownership to
2422 // ApplyRemoteDescription, which may destroy it before returning.
2423 const SdpType type = desc->GetType();
2424
2425 error = ApplyRemoteDescription(std::move(desc));
2426 // |desc| may be destroyed at this point.
2427
2428 if (!error.ok()) {
2429 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2430 // inconsistent state, so act conservatively here and set the session error
2431 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2432 SetSessionError(SessionError::kContent, error.message());
2433 std::string error_message =
2434 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2435 RTC_LOG(LS_ERROR) << error_message;
2436 observer->OnSetRemoteDescriptionComplete(
2437 RTCError(error.type(), std::move(error_message)));
2438 return;
2439 }
2440 RTC_DCHECK(remote_description());
2441
2442 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002443 // TODO(deadbeef): We already had to hop to the network thread for
2444 // MaybeStartGathering...
2445 network_thread()->Invoke<void>(
2446 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2447 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002448 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002449 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002450 }
2451
2452 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002453 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002454}
2455
2456RTCError PeerConnection::ApplyRemoteDescription(
2457 std::unique_ptr<SessionDescriptionInterface> desc) {
2458 RTC_DCHECK_RUN_ON(signaling_thread());
2459 RTC_DCHECK(desc);
2460
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002461 // Update stats here so that we have the most recent stats for tracks and
2462 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002463 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002464
Steve Antondcc3c022017-12-22 16:02:54 -08002465 // Take a reference to the old remote description since it's used below to
2466 // compare against the new remote description. When setting the new remote
2467 // description, grab ownership of the replaced session description in case it
2468 // is the same as |old_remote_description|, to keep it alive for the duration
2469 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002470 const SessionDescriptionInterface* old_remote_description =
2471 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002472 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002473 SdpType type = desc->GetType();
2474 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002475 replaced_remote_description = pending_remote_description_
2476 ? std::move(pending_remote_description_)
2477 : std::move(current_remote_description_);
2478 current_remote_description_ = std::move(desc);
2479 pending_remote_description_ = nullptr;
2480 current_local_description_ = std::move(pending_local_description_);
2481 } else {
2482 replaced_remote_description = std::move(pending_remote_description_);
2483 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002484 }
Steve Anton8a006912017-12-04 15:25:56 -08002485 // The session description to apply now must be accessed by
2486 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002487 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002488
Zhi Huange830e682018-03-30 10:48:35 -07002489 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2490 if (!error.ok()) {
2491 return error;
2492 }
Steve Anton8a006912017-12-04 15:25:56 -08002493 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002494 if (IsUnifiedPlan()) {
2495 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002496 cricket::CS_REMOTE, *remote_description(), local_description(),
2497 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002498 if (!error.ok()) {
2499 return error;
2500 }
Steve Antondcc3c022017-12-22 16:02:54 -08002501 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002502 // Media channels will be created only when offer is set. These may use new
2503 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002504 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002505 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002506 // description is applied. Restore back to old description.
2507 RTCError error = CreateChannels(*remote_description()->description());
2508 if (!error.ok()) {
2509 return error;
2510 }
2511 }
Steve Antondcc3c022017-12-22 16:02:54 -08002512 // Remove unused channels if MediaContentDescription is rejected.
2513 RemoveUnusedChannels(remote_description()->description());
2514 }
Steve Anton8a006912017-12-04 15:25:56 -08002515
Zhi Huange830e682018-03-30 10:48:35 -07002516 // NOTE: Candidates allocation will be initiated only when
2517 // SetLocalDescription is called.
2518 error = UpdateSessionState(type, cricket::CS_REMOTE,
2519 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002520 if (!error.ok()) {
2521 return error;
2522 }
2523
2524 if (local_description() &&
2525 !UseCandidatesInSessionDescription(remote_description())) {
2526 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2527 }
2528
2529 if (old_remote_description) {
2530 for (const cricket::ContentInfo& content :
2531 old_remote_description->description()->contents()) {
2532 // Check if this new SessionDescription contains new ICE ufrag and
2533 // password that indicates the remote peer requests an ICE restart.
2534 // TODO(deadbeef): When we start storing both the current and pending
2535 // remote description, this should reset pending_ice_restarts and compare
2536 // against the current description.
2537 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2538 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002539 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002540 pending_ice_restarts_.insert(content.name);
2541 }
2542 } else {
2543 // We retain all received candidates only if ICE is not restarted.
2544 // When ICE is restarted, all previous candidates belong to an old
2545 // generation and should not be kept.
2546 // TODO(deadbeef): This goes against the W3C spec which says the remote
2547 // description should only contain candidates from the last set remote
2548 // description plus any candidates added since then. We should remove
2549 // this once we're sure it won't break anything.
2550 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2551 old_remote_description, content.name, mutable_remote_description());
2552 }
2553 }
2554 }
2555
2556 if (session_error() != SessionError::kNone) {
2557 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2558 }
2559
2560 // Set the the ICE connection state to connecting since the connection may
2561 // become writable with peer reflexive candidates before any remote candidate
2562 // is signaled.
2563 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2564 // is to have a new signal the indicates a change in checking state from the
2565 // transport and expose a new checking() member from transport that can be
2566 // read to determine the current checking state. The existing SignalConnecting
2567 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002568 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002569 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002570 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2571 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2572 }
2573
deadbeefab9b2d12015-10-14 11:33:11 -07002574 // If setting the description decided our SSL role, allocate any necessary
2575 // SCTP sids.
2576 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002577 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002578 AllocateSctpSids(role);
2579 }
2580
Steve Antondcc3c022017-12-22 16:02:54 -08002581 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002582 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002583 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002584 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002585 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002586 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002587 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002588 const ContentInfo* content =
2589 FindMediaSectionForTransceiver(transceiver, remote_description());
2590 if (!content) {
2591 continue;
2592 }
2593 const MediaContentDescription* media_desc = content->media_description();
2594 RtpTransceiverDirection local_direction =
2595 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002596 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2597 // RTCSessionDescription: Set the associated remote streams given
2598 // transceiver.[[Receiver]], msids, addList, and removeList".
2599 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2600 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2601 std::vector<std::string> stream_ids;
2602 if (!media_desc->streams().empty()) {
2603 // The remote description has signaled the stream IDs.
2604 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002605 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002606 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2607 << " (" << GetStreamIdsString(stream_ids) << ").";
2608 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2609 stream_ids, &added_streams,
2610 &removed_streams);
2611 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2612 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2613 // and transceiver's current direction is neither sendrecv nor recvonly,
2614 // process the addition of a remote track for the media description.
2615 if (!transceiver->fired_direction() ||
2616 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2617 RTC_LOG(LS_INFO)
2618 << "Processing the addition of a remote track for MID="
2619 << content->name << ".";
2620 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002621 }
Steve Antondcc3c022017-12-22 16:02:54 -08002622 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002623 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002624 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2625 // removal of a remote track for the media description, given transceiver,
2626 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002627 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002628 (transceiver->fired_direction() &&
2629 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2630 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2631 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002632 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002633 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002634 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002635 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002636 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002637 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002638 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002639 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002640 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002641 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2642 if (transceiver->mid()) {
2643 auto dtls_transport =
2644 LookupDtlsTransportByMidInternal(*transceiver->mid());
2645 transceiver->internal()->sender_internal()->set_transport(
2646 dtls_transport);
2647 transceiver->internal()->receiver_internal()->set_transport(
2648 dtls_transport);
2649 }
Steve Antondcc3c022017-12-22 16:02:54 -08002650 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002651 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002652 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002653 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002654 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2655 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002656 transceiver->Stop();
2657 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002658 if (!content->rejected &&
2659 RtpTransceiverDirectionHasRecv(local_direction)) {
2660 // Set ssrc to 0 in the case of an unsignalled ssrc.
2661 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002662 if (!media_desc->streams().empty() &&
2663 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002664 ssrc = media_desc->streams()[0].first_ssrc();
2665 }
2666 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002667 }
Steve Antondcc3c022017-12-22 16:02:54 -08002668 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002669 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002670 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002671 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002672 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002673 observer->OnTrack(transceiver);
2674 observer->OnAddTrack(transceiver->receiver(),
2675 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002676 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002677 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002678 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002679 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002680 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002681 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002682 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002683 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002684 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002685 }
Steve Antondcc3c022017-12-22 16:02:54 -08002686 }
2687
Henrik Boströmfdb92012017-11-09 19:55:44 +01002688 const cricket::ContentInfo* audio_content =
2689 GetFirstAudioContent(remote_description()->description());
2690 const cricket::ContentInfo* video_content =
2691 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002692 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002693 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002694 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002695 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002696 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002697 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002698
2699 // Check if the descriptions include streams, just in case the peer supports
2700 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002701 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002702 (audio_desc && !audio_desc->streams().empty()) ||
2703 (video_desc && !video_desc->streams().empty())) {
2704 remote_peer_supports_msid_ = true;
2705 }
deadbeefab9b2d12015-10-14 11:33:11 -07002706
2707 // We wait to signal new streams until we finish processing the description,
2708 // since only at that point will new streams have all their tracks.
2709 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2710
Steve Antondcc3c022017-12-22 16:02:54 -08002711 if (!IsUnifiedPlan()) {
2712 // TODO(steveanton): When removing RTP senders/receivers in response to a
2713 // rejected media section, there is some cleanup logic that expects the
2714 // voice/ video channel to still be set. But in this method the voice/video
2715 // channel would have been destroyed by the SetRemoteDescription caller
2716 // above so the cleanup that relies on them fails to run. The RemoveSenders
2717 // calls should be moved to right before the DestroyChannel calls to fix
2718 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002719
Steve Antondcc3c022017-12-22 16:02:54 -08002720 // Find all audio rtp streams and create corresponding remote AudioTracks
2721 // and MediaStreams.
2722 if (audio_content) {
2723 if (audio_content->rejected) {
2724 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2725 } else {
2726 bool default_audio_track_needed =
2727 !remote_peer_supports_msid_ &&
2728 RtpTransceiverDirectionHasSend(audio_desc->direction());
2729 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2730 default_audio_track_needed, audio_desc->type(),
2731 new_streams);
2732 }
deadbeeffaac4972015-11-12 15:33:07 -08002733 }
deadbeefab9b2d12015-10-14 11:33:11 -07002734
Steve Antondcc3c022017-12-22 16:02:54 -08002735 // Find all video rtp streams and create corresponding remote VideoTracks
2736 // and MediaStreams.
2737 if (video_content) {
2738 if (video_content->rejected) {
2739 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2740 } else {
2741 bool default_video_track_needed =
2742 !remote_peer_supports_msid_ &&
2743 RtpTransceiverDirectionHasSend(video_desc->direction());
2744 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2745 default_video_track_needed, video_desc->type(),
2746 new_streams);
2747 }
deadbeeffaac4972015-11-12 15:33:07 -08002748 }
deadbeefab9b2d12015-10-14 11:33:11 -07002749
Steve Antondcc3c022017-12-22 16:02:54 -08002750 // Update the DataChannels with the information from the remote peer.
2751 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002752 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002753 cricket::kMediaProtocolRtpPrefix)) {
2754 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2755 }
deadbeefab9b2d12015-10-14 11:33:11 -07002756 }
deadbeefab9b2d12015-10-14 11:33:11 -07002757
Steve Antondcc3c022017-12-22 16:02:54 -08002758 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002759 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002760 for (size_t i = 0; i < new_streams->count(); ++i) {
2761 MediaStreamInterface* new_stream = new_streams->at(i);
2762 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002763 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002764 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2765 }
deadbeefab9b2d12015-10-14 11:33:11 -07002766
Steve Antondcc3c022017-12-22 16:02:54 -08002767 UpdateEndedRemoteMediaStreams();
2768 }
deadbeefab9b2d12015-10-14 11:33:11 -07002769
Steve Anton8a006912017-12-04 15:25:56 -08002770 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002771}
2772
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002773void PeerConnection::SetAssociatedRemoteStreams(
2774 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2775 const std::vector<std::string>& stream_ids,
2776 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2777 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2778 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2779 for (const std::string& stream_id : stream_ids) {
2780 rtc::scoped_refptr<MediaStreamInterface> stream =
2781 remote_streams_->find(stream_id);
2782 if (!stream) {
2783 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2784 MediaStream::Create(stream_id));
2785 remote_streams_->AddStream(stream);
2786 added_streams->push_back(stream);
2787 }
2788 media_streams.push_back(stream);
2789 }
2790 // Special case: "a=msid" missing, use random stream ID.
2791 if (media_streams.empty() &&
2792 !(remote_description()->description()->msid_signaling() &
2793 cricket::kMsidSignalingMediaSection)) {
2794 if (!missing_msid_default_stream_) {
2795 missing_msid_default_stream_ = MediaStreamProxy::Create(
2796 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2797 added_streams->push_back(missing_msid_default_stream_);
2798 }
2799 media_streams.push_back(missing_msid_default_stream_);
2800 }
2801 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2802 receiver->streams();
2803 // SetStreams() will add/remove the receiver's track to/from the streams. This
2804 // differs from the spec - the spec uses an "addList" and "removeList" to
2805 // update the stream-track relationships in a later step. We do this earlier,
2806 // changing the order of things, but the end-result is the same.
2807 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2808 // instead. https://crbug.com/webrtc/9480
2809 receiver->SetStreams(media_streams);
2810 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2811}
2812
Steve Anton0f5400a2018-07-17 14:25:36 -07002813void PeerConnection::ProcessRemovalOfRemoteTrack(
2814 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2815 transceiver,
2816 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2817 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2818 RTC_DCHECK(transceiver->mid());
2819 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2820 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002821 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002822 transceiver->internal()->receiver_internal()->streams();
2823 // This will remove the remote track from the streams.
2824 transceiver->internal()->receiver_internal()->set_stream_ids({});
2825 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002826 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2827}
2828
2829void PeerConnection::RemoveRemoteStreamsIfEmpty(
2830 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2831 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2832 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2833 // streams, see if the stream was removed by checking if this was the last
2834 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002835 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002836 if (remote_stream->GetAudioTracks().empty() &&
2837 remote_stream->GetVideoTracks().empty()) {
2838 remote_streams_->RemoveStream(remote_stream);
2839 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002840 }
2841 }
2842}
2843
Steve Antondcc3c022017-12-22 16:02:54 -08002844RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2845 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002846 const SessionDescriptionInterface& new_session,
2847 const SessionDescriptionInterface* old_local_description,
2848 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002849 RTC_DCHECK(IsUnifiedPlan());
2850
Steve Anton7464fca2018-01-19 11:10:37 -08002851 const cricket::ContentGroup* bundle_group = nullptr;
2852 if (new_session.GetType() == SdpType::kOffer) {
2853 auto bundle_group_or_error =
2854 GetEarlyBundleGroup(*new_session.description());
2855 if (!bundle_group_or_error.ok()) {
2856 return bundle_group_or_error.MoveError();
2857 }
2858 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002859 }
Steve Antondcc3c022017-12-22 16:02:54 -08002860
Steve Antondcc3c022017-12-22 16:02:54 -08002861 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002862 for (size_t i = 0; i < new_contents.size(); ++i) {
2863 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002864 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002865 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002866 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2867 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002868 const cricket::ContentInfo* old_local_content = nullptr;
2869 if (old_local_description &&
2870 i < old_local_description->description()->contents().size()) {
2871 old_local_content =
2872 &old_local_description->description()->contents()[i];
2873 }
2874 const cricket::ContentInfo* old_remote_content = nullptr;
2875 if (old_remote_description &&
2876 i < old_remote_description->description()->contents().size()) {
2877 old_remote_content =
2878 &old_remote_description->description()->contents()[i];
2879 }
Steve Antondcc3c022017-12-22 16:02:54 -08002880 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002881 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2882 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002883 if (!transceiver_or_error.ok()) {
2884 return transceiver_or_error.MoveError();
2885 }
2886 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002887 RTCError error =
2888 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2889 if (!error.ok()) {
2890 return error;
2891 }
2892 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002893 if (GetDataMid() && new_content.name != *GetDataMid()) {
2894 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002895 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2896 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002897 continue;
2898 }
2899 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2900 if (!error.ok()) {
2901 return error;
2902 }
Steve Antondcc3c022017-12-22 16:02:54 -08002903 } else {
2904 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2905 "Unknown section type.");
2906 }
2907 }
2908
2909 return RTCError::OK();
2910}
2911
2912RTCError PeerConnection::UpdateTransceiverChannel(
2913 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2914 transceiver,
2915 const cricket::ContentInfo& content,
2916 const cricket::ContentGroup* bundle_group) {
2917 RTC_DCHECK(IsUnifiedPlan());
2918 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002919 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002920 if (content.rejected) {
2921 if (channel) {
2922 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002923 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002924 }
2925 } else {
2926 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002927 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002928 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002929 } else {
Steve Anton69470252018-02-09 11:43:08 -08002930 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002931 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002932 }
2933 if (!channel) {
2934 LOG_AND_RETURN_ERROR(
2935 RTCErrorType::INTERNAL_ERROR,
2936 "Failed to create channel for mid=" + content.name);
2937 }
2938 transceiver->internal()->SetChannel(channel);
2939 }
2940 }
2941 return RTCError::OK();
2942}
2943
Steve Antonfa2260d2017-12-28 16:38:23 -08002944RTCError PeerConnection::UpdateDataChannel(
2945 cricket::ContentSource source,
2946 const cricket::ContentInfo& content,
2947 const cricket::ContentGroup* bundle_group) {
2948 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002949 // If data channels are disabled, ignore this media section. CreateAnswer
2950 // will take care of rejecting it.
2951 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002952 }
2953 if (content.rejected) {
2954 DestroyDataChannel();
2955 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002956 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002957 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002958 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2959 "Failed to create data channel.");
2960 }
2961 }
2962 if (source == cricket::CS_REMOTE) {
2963 const MediaContentDescription* data_desc = content.media_description();
2964 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2965 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2966 }
2967 }
2968 }
2969 return RTCError::OK();
2970}
2971
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002972// This method will extract any send encodings that were sent by the remote
2973// connection. This is currently only relevant for Simulcast scenario (where
2974// the number of layers may be communicated by the server).
2975static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2976 const MediaContentDescription& desc) {
2977 if (!desc.HasSimulcast()) {
2978 return {};
2979 }
2980 std::vector<RtpEncodingParameters> result;
2981 const SimulcastDescription& simulcast = desc.simulcast_description();
2982
2983 // This is a remote description, the parameters we are after should appear
2984 // as receive streams.
2985 for (const auto& alternatives : simulcast.receive_layers()) {
2986 RTC_DCHECK(!alternatives.empty());
2987 // There is currently no way to specify or choose from alternatives.
2988 // We will always use the first alternative, which is the most preferred.
2989 const SimulcastLayer& layer = alternatives[0];
2990 RtpEncodingParameters parameters;
2991 parameters.rid = layer.rid;
2992 parameters.active = !layer.is_paused;
2993 result.push_back(parameters);
2994 }
2995
2996 return result;
2997}
2998
2999static RTCError UpdateSimulcastLayerStatusInSender(
3000 const std::vector<SimulcastLayer>& layers,
3001 RtpSenderInterface* sender) {
3002 RTC_DCHECK(sender);
3003 RtpParameters parameters = sender->GetParameters();
3004
3005 // The simulcast envelope cannot be changed, only the status of the streams.
3006 // So we will iterate over the send encodings rather than the layers.
3007 for (RtpEncodingParameters& encoding : parameters.encodings) {
3008 auto iter = std::find_if(layers.begin(), layers.end(),
3009 [&encoding](const SimulcastLayer& layer) {
3010 return layer.rid == encoding.rid;
3011 });
3012 // A layer that cannot be found may have been removed by the remote party.
3013 encoding.active = iter != layers.end() && !iter->is_paused;
3014 }
3015
3016 return sender->SetParameters(parameters);
3017}
3018
3019static RTCError DisableSimulcastInSender(RtpSenderInterface* sender) {
3020 RTC_DCHECK(sender);
3021 RtpParameters parameters = sender->GetParameters();
3022 if (parameters.encodings.empty()) {
3023 return RTCError::OK();
3024 }
3025
3026 bool first_layer_status = parameters.encodings[0].active;
3027 for (RtpEncodingParameters& encoding : parameters.encodings) {
3028 // TODO(bugs.webrtc.org/10251): Active does not really disable the layer.
3029 // The user might enable it at a later point in time even though it was
3030 // rejected.
3031 encoding.active = false;
3032 }
3033 parameters.encodings[0].active = first_layer_status;
3034
3035 return sender->SetParameters(parameters);
3036}
3037
Steve Antondcc3c022017-12-22 16:02:54 -08003038RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3039PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003040 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003041 size_t mline_index,
3042 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003043 const ContentInfo* old_local_content,
3044 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003045 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003046 // If this is an offer then the m= section might be recycled. If the m=
3047 // section is being recycled (defined as: rejected in the current local or
3048 // remote description and not rejected in new description), dissociate the
3049 // currently associated RtpTransceiver by setting its mid property to null,
3050 // and discard the mapping between the transceiver and its m= section index.
3051 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3052 old_remote_content)) {
3053 // We want to dissociate the transceiver that has the rejected mid.
3054 const std::string& old_mid =
3055 (old_local_content && old_local_content->rejected)
3056 ? old_local_content->name
3057 : old_remote_content->name;
3058 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003059 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003060 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3061 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003062 old_transceiver->internal()->set_mid(absl::nullopt);
3063 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003064 }
3065 }
3066 const MediaContentDescription* media_desc = content.media_description();
3067 auto transceiver = GetAssociatedTransceiver(content.name);
3068 if (source == cricket::CS_LOCAL) {
3069 // Find the RtpTransceiver that corresponds to this m= section, using the
3070 // mapping between transceivers and m= section indices established when
3071 // creating the offer.
3072 if (!transceiver) {
3073 transceiver = GetTransceiverByMLineIndex(mline_index);
3074 }
3075 if (!transceiver) {
3076 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3077 "Unknown transceiver");
3078 }
3079 } else {
3080 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3081 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3082 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003083 // When simulcast is requested, a transceiver cannot be associated because
3084 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003085 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003086 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3087 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003088 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3089 }
3090 // If no RtpTransceiver was found in the previous step, create one with a
3091 // recvonly direction.
3092 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003093 RTC_LOG(LS_INFO) << "Adding "
3094 << cricket::MediaTypeToString(media_desc->type())
3095 << " transceiver for MID=" << content.name
3096 << " at i=" << mline_index
3097 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003098 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003099 std::vector<RtpEncodingParameters> send_encodings =
3100 GetSendEncodingsFromRemoteDescription(*media_desc);
3101 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3102 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003103 std::string receiver_id;
3104 if (!media_desc->streams().empty()) {
3105 receiver_id = media_desc->streams()[0].id;
3106 } else {
3107 receiver_id = rtc::CreateRandomUuid();
3108 }
3109 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003110 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003111 transceiver->internal()->set_direction(
3112 RtpTransceiverDirection::kRecvOnly);
3113 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003114
3115 // Check if the offer indicated simulcast but the answer rejected it.
3116 // This can happen when simulcast is not supported on the remote party.
3117 // This check can be simplified to comparing the number of send encodings,
3118 // but that might break legacy implementation in which simulcast is not
3119 // signaled in the remote description.
3120 if (old_local_content && old_local_content->media_description() &&
3121 old_local_content->media_description()->HasSimulcast() &&
3122 !media_desc->HasSimulcast()) {
3123 RTCError error =
3124 DisableSimulcastInSender(transceiver->internal()->sender());
3125 if (!error.ok()) {
3126 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3127 return std::move(error);
3128 }
3129 }
Steve Antondcc3c022017-12-22 16:02:54 -08003130 }
3131 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003132 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003133 LOG_AND_RETURN_ERROR(
3134 RTCErrorType::INVALID_PARAMETER,
3135 "Transceiver type does not match media description type.");
3136 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003137 if (media_desc->HasSimulcast()) {
3138 std::vector<SimulcastLayer> layers =
3139 source == cricket::CS_LOCAL
3140 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3141 : media_desc->simulcast_description()
3142 .receive_layers()
3143 .GetAllLayers();
3144 RTCError error = UpdateSimulcastLayerStatusInSender(
3145 layers, transceiver->internal()->sender());
3146 if (!error.ok()) {
3147 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3148 return std::move(error);
3149 }
3150 }
Steve Antondcc3c022017-12-22 16:02:54 -08003151 // Associate the found or created RtpTransceiver with the m= section by
3152 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3153 // section, and establish a mapping between the transceiver and the index of
3154 // the m= section.
3155 transceiver->internal()->set_mid(content.name);
3156 transceiver->internal()->set_mline_index(mline_index);
3157 return std::move(transceiver);
3158}
3159
3160rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3161PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3162 RTC_DCHECK(IsUnifiedPlan());
3163 for (auto transceiver : transceivers_) {
3164 if (transceiver->mid() == mid) {
3165 return transceiver;
3166 }
3167 }
3168 return nullptr;
3169}
3170
3171rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3172PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3173 RTC_DCHECK(IsUnifiedPlan());
3174 for (auto transceiver : transceivers_) {
3175 if (transceiver->internal()->mline_index() == mline_index) {
3176 return transceiver;
3177 }
3178 }
3179 return nullptr;
3180}
3181
3182rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3183PeerConnection::FindAvailableTransceiverToReceive(
3184 cricket::MediaType media_type) const {
3185 RTC_DCHECK(IsUnifiedPlan());
3186 // From JSEP section 5.10 (Applying a Remote Description):
3187 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3188 // the same type that were added to the PeerConnection by addTrack and are not
3189 // associated with any m= section and are not stopped, find the first such
3190 // RtpTransceiver.
3191 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003192 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003193 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3194 !transceiver->stopped()) {
3195 return transceiver;
3196 }
3197 }
3198 return nullptr;
3199}
3200
Steve Antoned10bd92017-12-05 10:52:59 -08003201const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3202 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3203 transceiver,
3204 const SessionDescriptionInterface* sdesc) const {
3205 RTC_DCHECK(transceiver);
3206 RTC_DCHECK(sdesc);
3207 if (IsUnifiedPlan()) {
3208 if (!transceiver->internal()->mid()) {
3209 // This transceiver is not associated with a media section yet.
3210 return nullptr;
3211 }
3212 return sdesc->description()->GetContentByName(
3213 *transceiver->internal()->mid());
3214 } else {
3215 // Plan B only allows at most one audio and one video section, so use the
3216 // first media section of that type.
3217 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003218 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003219 }
3220}
3221
deadbeef46c73892016-11-16 19:42:04 -08003222PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3223 return configuration_;
3224}
3225
deadbeef293e9262017-01-11 12:28:30 -08003226bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3227 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003228 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003229 if (IsClosed()) {
3230 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3231 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3232 }
3233
Qingsi Wanga2d60672018-04-11 16:57:45 -07003234 // According to JSEP, after setLocalDescription, changing the candidate pool
3235 // size is not allowed, and changing the set of ICE servers will not result
3236 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003237 if (local_description() && configuration.ice_candidate_pool_size !=
3238 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003239 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3240 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003241 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003242 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003243
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003244 if (local_description() &&
3245 configuration.use_media_transport != configuration_.use_media_transport) {
3246 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3247 "SetLocalDescription.";
3248 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3249 }
3250
3251 if (remote_description() &&
3252 configuration.use_media_transport != configuration_.use_media_transport) {
3253 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3254 "SetRemoteDescription.";
3255 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3256 }
3257
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003258 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003259 configuration.use_media_transport_for_data_channels !=
3260 configuration_.use_media_transport_for_data_channels) {
3261 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3262 "after calling SetLocalDescription.";
3263 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3264 }
3265
3266 if (remote_description() &&
3267 configuration.use_media_transport_for_data_channels !=
3268 configuration_.use_media_transport_for_data_channels) {
3269 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3270 "after calling SetRemoteDescription.";
3271 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3272 }
3273
3274 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003275 configuration.crypto_options != configuration_.crypto_options) {
3276 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3277 "SetLocalDescription.";
3278 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3279 }
3280
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003281 if (configuration.use_media_transport_for_data_channels ||
3282 configuration.use_media_transport) {
3283 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3284 << "Media transport requires MaxBundle policy.";
3285 }
3286
deadbeef293e9262017-01-11 12:28:30 -08003287 // The simplest (and most future-compatible) way to tell if the config was
3288 // modified in an invalid way is to copy each property we do support
3289 // modifying, then use operator==. There are far more properties we don't
3290 // support modifying than those we do, and more could be added.
3291 RTCConfiguration modified_config = configuration_;
3292 modified_config.servers = configuration.servers;
3293 modified_config.type = configuration.type;
3294 modified_config.ice_candidate_pool_size =
3295 configuration.ice_candidate_pool_size;
3296 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003297 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003298 modified_config.ice_check_interval_strong_connectivity =
3299 configuration.ice_check_interval_strong_connectivity;
3300 modified_config.ice_check_interval_weak_connectivity =
3301 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003302 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3303 modified_config.ice_unwritable_min_checks =
3304 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003305 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003306 modified_config.stun_candidate_keepalive_interval =
3307 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003308 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003309 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003310 modified_config.active_reset_srtp_params =
3311 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003312 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003313 modified_config.use_media_transport_for_data_channels =
3314 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003315 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003316 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003317 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3318 }
3319
Steve Anton038834f2017-07-14 15:59:59 -07003320 // Validate the modified configuration.
3321 RTCError validate_error = ValidateConfiguration(modified_config);
3322 if (!validate_error.ok()) {
3323 return SafeSetError(std::move(validate_error), error);
3324 }
3325
deadbeef293e9262017-01-11 12:28:30 -08003326 // Note that this isn't possible through chromium, since it's an unsigned
3327 // short in WebIDL.
3328 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003329 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003330 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3331 }
3332
3333 // Parse ICE servers before hopping to network thread.
3334 cricket::ServerAddresses stun_servers;
3335 std::vector<cricket::RelayServerConfig> turn_servers;
3336 RTCErrorType parse_error =
3337 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3338 if (parse_error != RTCErrorType::NONE) {
3339 return SafeSetError(parse_error, error);
3340 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003341 // Note if STUN or TURN servers were supplied.
3342 if (!stun_servers.empty()) {
3343 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3344 }
3345 if (!turn_servers.empty()) {
3346 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3347 }
deadbeef293e9262017-01-11 12:28:30 -08003348
3349 // In theory this shouldn't fail.
3350 if (!network_thread()->Invoke<bool>(
3351 RTC_FROM_HERE,
3352 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3353 stun_servers, turn_servers, modified_config.type,
3354 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003355 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003356 modified_config.turn_customizer,
3357 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003358 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003359 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3360 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003361
deadbeefd1a38b52016-12-10 13:15:33 -08003362 // As described in JSEP, calling setConfiguration with new ICE servers or
3363 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3364 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003365 if (modified_config.servers != configuration_.servers ||
3366 modified_config.type != configuration_.type ||
3367 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003368 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003369 }
skvladd1f5fda2017-02-03 16:54:05 -08003370
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003371 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003372 transport_controller_->SetMediaTransportSettings(
3373 modified_config.use_media_transport,
3374 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003375
Zhi Huangb57e1692018-06-12 11:41:11 -07003376 if (configuration_.active_reset_srtp_params !=
3377 modified_config.active_reset_srtp_params) {
3378 transport_controller_->SetActiveResetSrtpParams(
3379 modified_config.active_reset_srtp_params);
3380 }
3381
deadbeef293e9262017-01-11 12:28:30 -08003382 configuration_ = modified_config;
3383 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003384}
3385
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003386bool PeerConnection::AddIceCandidate(
3387 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003388 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003389 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003390 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003391 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003392 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003393 return false;
3394 }
Steve Antond25da372017-11-06 14:50:29 -08003395
3396 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003397 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003398 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003399 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003400 return false;
3401 }
3402
3403 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003404 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003405 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003406 return false;
3407 }
3408
3409 bool valid = false;
3410 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3411 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003412 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003413 return false;
3414 }
3415
3416 // Add this candidate to the remote session description.
3417 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003418 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003419 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003420 return false;
3421 }
3422
3423 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003424 bool result = UseCandidate(ice_candidate);
3425 if (result) {
3426 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3427 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3428 } else {
3429 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3430 }
3431 return result;
Steve Antond25da372017-11-06 14:50:29 -08003432 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003433 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003434 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003435 return true;
3436 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003437}
3438
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003439bool PeerConnection::RemoveIceCandidates(
3440 const std::vector<cricket::Candidate>& candidates) {
3441 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003442 if (IsClosed()) {
3443 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3444 return false;
3445 }
3446
Steve Antond25da372017-11-06 14:50:29 -08003447 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003448 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3449 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003450 return false;
3451 }
3452
3453 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003454 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003455 return false;
3456 }
3457
3458 size_t number_removed =
3459 mutable_remote_description()->RemoveCandidates(candidates);
3460 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003461 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003462 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003463 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003464 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003465 }
3466
3467 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003468 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3469 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003470 RTC_LOG(LS_ERROR)
3471 << "RemoveIceCandidates: Error when removing remote candidates: "
3472 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003473 }
3474 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003475}
3476
Niels Möller0c4f7be2018-05-07 14:01:37 +02003477RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003478 if (!worker_thread()->IsCurrent()) {
3479 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003480 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003481 }
3482
Niels Möller0c4f7be2018-05-07 14:01:37 +02003483 const bool has_min = bitrate.min_bitrate_bps.has_value();
3484 const bool has_start = bitrate.start_bitrate_bps.has_value();
3485 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003486 if (has_min && *bitrate.min_bitrate_bps < 0) {
3487 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3488 "min_bitrate_bps <= 0");
3489 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003490 if (has_start) {
3491 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003492 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003493 "start_bitrate_bps < min_bitrate_bps");
3494 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003495 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3496 "curent_bitrate_bps < 0");
3497 }
3498 }
3499 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003500 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003502 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003503 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3504 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3505 "max_bitrate_bps < min_bitrate_bps");
3506 } else if (*bitrate.max_bitrate_bps < 0) {
3507 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3508 "max_bitrate_bps < 0");
3509 }
3510 }
3511
zstein4b979802017-06-02 14:37:37 -07003512 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003513 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003514
3515 return RTCError::OK();
3516}
3517
Alex Narest78609d52017-10-20 10:37:47 +02003518void PeerConnection::SetBitrateAllocationStrategy(
3519 std::unique_ptr<rtc::BitrateAllocationStrategy>
3520 bitrate_allocation_strategy) {
3521 rtc::Thread* worker_thread = factory_->worker_thread();
3522 if (!worker_thread->IsCurrent()) {
3523 rtc::BitrateAllocationStrategy* strategy_raw =
3524 bitrate_allocation_strategy.release();
3525 auto functor = [this, strategy_raw]() {
3526 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003527 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003528 };
3529 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3530 return;
3531 }
3532 RTC_DCHECK(call_.get());
3533 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3534}
3535
henrika5f6bf242017-11-01 11:06:56 +01003536void PeerConnection::SetAudioPlayout(bool playout) {
3537 if (!worker_thread()->IsCurrent()) {
3538 worker_thread()->Invoke<void>(
3539 RTC_FROM_HERE,
3540 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3541 return;
3542 }
3543 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003544 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003545 audio_state->SetPlayout(playout);
3546}
3547
3548void PeerConnection::SetAudioRecording(bool recording) {
3549 if (!worker_thread()->IsCurrent()) {
3550 worker_thread()->Invoke<void>(
3551 RTC_FROM_HERE,
3552 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3553 return;
3554 }
3555 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003556 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003557 audio_state->SetRecording(recording);
3558}
3559
Steve Anton8c0f7a72017-10-03 10:03:10 -07003560std::unique_ptr<rtc::SSLCertificate>
3561PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003562 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3563 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003564 return nullptr;
3565 }
Steve Antonf25303e2018-10-16 15:23:31 -07003566 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003567}
3568
Zhi Huang70b820f2018-01-27 14:16:15 -08003569std::unique_ptr<rtc::SSLCertChain>
3570PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003571 auto audio_transceiver = GetFirstAudioTransceiver();
3572 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003573 return nullptr;
3574 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003575 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003576 audio_transceiver->internal()->channel()->transport_name());
3577}
3578
3579rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3580PeerConnection::GetFirstAudioTransceiver() const {
3581 for (auto transceiver : transceivers_) {
3582 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3583 return transceiver;
3584 }
3585 }
3586 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003587}
3588
ivoc14d5dbe2016-07-04 07:06:55 -07003589bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3590 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003591 // TODO(eladalon): It would be better to not allow negative values into PC.
3592 const size_t max_size = (max_size_bytes < 0)
3593 ? RtcEventLog::kUnlimitedOutput
3594 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003595 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3596 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3597 output_period_ms = 5000;
3598 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003599 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003600 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003601 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003602}
3603
Bjorn Tereliusde939432017-11-20 17:38:14 +01003604bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3605 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003606 // TODO(eladalon): In C++14, this can be done with a lambda.
3607 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003608 bool operator()() {
3609 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3610 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003611 PeerConnection* const pc;
3612 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003613 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003614 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003615 return worker_thread()->Invoke<bool>(
3616 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003617}
3618
3619void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003620 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003621 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3622}
3623
Harald Alvestrandad88c882018-11-28 16:47:46 +01003624rtc::scoped_refptr<DtlsTransportInterface>
3625PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3626 return transport_controller_->LookupDtlsTransportByMid(mid);
3627}
3628
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003629rtc::scoped_refptr<DtlsTransport>
3630PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3631 return transport_controller_->LookupDtlsTransportByMid(mid);
3632}
3633
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003634const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003635 return pending_local_description_ ? pending_local_description_.get()
3636 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003637}
3638
3639const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003640 return pending_remote_description_ ? pending_remote_description_.get()
3641 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003642}
3643
deadbeeffe4a8a42016-12-20 17:56:17 -08003644const SessionDescriptionInterface* PeerConnection::current_local_description()
3645 const {
Steve Anton75737c02017-11-06 10:37:17 -08003646 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003647}
3648
3649const SessionDescriptionInterface* PeerConnection::current_remote_description()
3650 const {
Steve Anton75737c02017-11-06 10:37:17 -08003651 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003652}
3653
3654const SessionDescriptionInterface* PeerConnection::pending_local_description()
3655 const {
Steve Anton75737c02017-11-06 10:37:17 -08003656 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003657}
3658
3659const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3660 const {
Steve Anton75737c02017-11-06 10:37:17 -08003661 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003662}
3663
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003664void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003665 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003666 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003667 // Update stats here so that we have the most recent stats for tracks and
3668 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003669 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003670
Steve Anton75737c02017-11-06 10:37:17 -08003671 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003672 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003673
Mirko Bonadei739baf02019-01-27 17:29:42 +01003674 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003675 transceiver->Stop();
3676 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003677
3678 // Ensure that all asynchronous stats requests are completed before destroying
3679 // the transport controller below.
3680 if (stats_collector_) {
3681 stats_collector_->WaitForPendingRequest();
3682 }
3683
3684 // Don't destroy BaseChannels until after stats has been cleaned up so that
3685 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003686 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003687
Qingsi Wang93a84392018-01-30 17:13:09 -08003688 // The event log is used in the transport controller, which must be outlived
3689 // by the former. CreateOffer by the peer connection is implemented
3690 // asynchronously and if the peer connection is closed without resetting the
3691 // WebRTC session description factory, the session description factory would
3692 // call the transport controller.
3693 webrtc_session_desc_factory_.reset();
3694 transport_controller_.reset();
3695
deadbeef42a42632017-03-10 15:18:00 -08003696 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003697 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3698 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003699
Steve Anton978b8762017-09-29 12:15:02 -07003700 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003701 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003702 call_.reset();
3703 // The event log must outlive call (and any other object that uses it).
3704 event_log_.reset();
3705 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003706 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003707 // The .h file says that observer can be discarded after close() returns.
3708 // Make sure this is true.
3709 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003710}
3711
Steve Antonad182762018-09-05 20:22:40 +00003712void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003713 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003714 switch (msg->message_id) {
3715 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3716 SetSessionDescriptionMsg* param =
3717 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3718 param->observer->OnSuccess();
3719 delete param;
3720 break;
3721 }
3722 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3723 SetSessionDescriptionMsg* param =
3724 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3725 param->observer->OnFailure(std::move(param->error));
3726 delete param;
3727 break;
3728 }
3729 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3730 CreateSessionDescriptionMsg* param =
3731 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3732 param->observer->OnFailure(std::move(param->error));
3733 delete param;
3734 break;
3735 }
3736 case MSG_GETSTATS: {
3737 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3738 StatsReports reports;
3739 stats_->GetStats(param->track, &reports);
3740 param->observer->OnComplete(reports);
3741 delete param;
3742 break;
3743 }
3744 case MSG_FREE_DATACHANNELS: {
3745 sctp_data_channels_to_free_.clear();
3746 break;
3747 }
3748 case MSG_REPORT_USAGE_PATTERN: {
3749 ReportUsagePattern();
3750 break;
3751 }
3752 default:
3753 RTC_NOTREACHED() << "Not implemented";
3754 break;
3755 }
3756}
3757
Steve Antonafb0bb72018-02-20 11:35:37 -08003758cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3759 RTC_DCHECK(!IsUnifiedPlan());
3760 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3761 GetAudioTransceiver()->internal()->channel());
3762 if (voice_channel) {
3763 return voice_channel->media_channel();
3764 } else {
3765 return nullptr;
3766 }
3767}
3768
3769cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3770 RTC_DCHECK(!IsUnifiedPlan());
3771 auto* video_channel = static_cast<cricket::VideoChannel*>(
3772 GetVideoTransceiver()->internal()->channel());
3773 if (video_channel) {
3774 return video_channel->media_channel();
3775 } else {
3776 return nullptr;
3777 }
3778}
3779
Steve Anton4171afb2017-11-20 10:20:22 -08003780void PeerConnection::CreateAudioReceiver(
3781 MediaStreamInterface* stream,
3782 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003783 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3784 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003785 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3786 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003787 auto* audio_receiver = new AudioRtpReceiver(
3788 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003789 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003790 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3791 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3792 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003793 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003794 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003795 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003796}
3797
Steve Anton4171afb2017-11-20 10:20:22 -08003798void PeerConnection::CreateVideoReceiver(
3799 MediaStreamInterface* stream,
3800 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003801 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3802 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003803 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3804 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003805 auto* video_receiver = new VideoRtpReceiver(
3806 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003807 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003808 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3809 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3810 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003811 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003812 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003813 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003814}
3815
deadbeef70ab1a12015-09-28 16:53:55 -07003816// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3817// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003818rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003819 const RtpSenderInfo& remote_sender_info) {
3820 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3821 if (!receiver) {
3822 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3823 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003824 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003825 }
Steve Anton4171afb2017-11-20 10:20:22 -08003826 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3827 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3828 } else {
3829 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3830 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003831 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003832}
3833
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003834void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3835 MediaStreamInterface* stream) {
3836 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003837 RTC_DCHECK(track);
3838 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003839 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003840 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003841 // We already have a sender for this track, so just change the stream_id
3842 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003843 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003844 return;
3845 }
3846
3847 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003848 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003849 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003850 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003851 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003852 // If the sender has already been configured in SDP, we call SetSsrc,
3853 // which will connect the sender to the underlying transport. This can
3854 // occur if a local session description that contains the ID of the sender
3855 // is set before AddStream is called. It can also occur if the local
3856 // session description is not changed and RemoveStream is called, and
3857 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003858 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003859 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003860 if (sender_info) {
3861 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003862 }
3863}
3864
3865// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3866// indefinitely, when we have unified plan SDP.
3867void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3868 MediaStreamInterface* stream) {
3869 RTC_DCHECK(!IsClosed());
3870 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003871 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003872 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3873 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003874 return;
3875 }
Steve Anton4171afb2017-11-20 10:20:22 -08003876 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003877}
3878
3879void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3880 MediaStreamInterface* stream) {
3881 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003882 RTC_DCHECK(track);
3883 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003884 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003885 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003886 // We already have a sender for this track, so just change the stream_id
3887 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003888 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003889 return;
3890 }
3891
3892 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003893 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003894 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003895 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003896 GetVideoTransceiver()->internal()->AddSender(new_sender);
3897 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003898 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003899 if (sender_info) {
3900 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003901 }
3902}
3903
3904void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3905 MediaStreamInterface* stream) {
3906 RTC_DCHECK(!IsClosed());
3907 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003908 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003909 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3910 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003911 return;
3912 }
Steve Anton4171afb2017-11-20 10:20:22 -08003913 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003914}
3915
Steve Antonba818672017-11-06 10:21:57 -08003916void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08003917 if (ice_connection_state_ == new_state) {
3918 return;
3919 }
3920
deadbeefcbecd352015-09-23 11:50:27 -07003921 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003922 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003923 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003924 return;
3925 }
Steve Antonba818672017-11-06 10:21:57 -08003926
Mirko Bonadei675513b2017-11-09 11:09:25 +01003927 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3928 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003929 RTC_DCHECK(ice_connection_state_ !=
3930 PeerConnectionInterface::kIceConnectionClosed);
3931
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003932 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003933 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003934}
3935
Alex Loiko9289eda2018-11-23 16:18:59 +00003936void PeerConnection::SetStandardizedIceConnectionState(
3937 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00003938 if (standardized_ice_connection_state_ == new_state)
3939 return;
3940 if (IsClosed())
3941 return;
3942 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003943 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003944}
3945
Jonas Olsson635474e2018-10-18 15:58:17 +02003946void PeerConnection::SetConnectionState(
3947 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02003948 if (connection_state_ == new_state)
3949 return;
3950 if (IsClosed())
3951 return;
3952 connection_state_ = new_state;
3953 Observer()->OnConnectionChange(new_state);
3954}
3955
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003956void PeerConnection::OnIceGatheringChange(
3957 PeerConnectionInterface::IceGatheringState new_state) {
3958 if (IsClosed()) {
3959 return;
3960 }
3961 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003962 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003963}
3964
jbauch81bf7b02017-03-25 08:31:12 -07003965void PeerConnection::OnIceCandidate(
3966 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07003967 if (IsClosed()) {
3968 return;
3969 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003970 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003971 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3972 candidate->candidate().address().IsPrivateIP()) {
3973 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3974 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003975 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003976}
3977
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003978void PeerConnection::OnIceCandidatesRemoved(
3979 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07003980 if (IsClosed()) {
3981 return;
3982 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003983 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003984}
3985
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003986void PeerConnection::ChangeSignalingState(
3987 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003988 if (signaling_state_ == signaling_state) {
3989 return;
3990 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003991 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3992 << GetSignalingStateString(signaling_state_)
3993 << " New state: "
3994 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003995 signaling_state_ = signaling_state;
3996 if (signaling_state == kClosed) {
3997 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003998 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003999 standardized_ice_connection_state_ =
4000 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004001 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4002 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004003 if (ice_gathering_state_ != kIceGatheringComplete) {
4004 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004005 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004006 }
4007 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004008 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004009}
4010
deadbeefeb459812015-12-15 19:24:43 -08004011void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4012 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004013 if (IsClosed()) {
4014 return;
4015 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004016 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004017 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004018}
4019
deadbeefeb459812015-12-15 19:24:43 -08004020void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4021 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004022 if (IsClosed()) {
4023 return;
4024 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004025 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004026 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004027}
4028
4029void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4030 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004031 if (IsClosed()) {
4032 return;
4033 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004034 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004035 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004036}
4037
4038void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4039 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004040 if (IsClosed()) {
4041 return;
4042 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004043 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004044 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004045}
4046
Henrik Boström31638672017-11-23 17:48:32 +01004047void PeerConnection::PostSetSessionDescriptionSuccess(
4048 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004049 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4050 signaling_thread()->Post(RTC_FROM_HERE, this,
4051 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004052}
4053
deadbeefab9b2d12015-10-14 11:33:11 -07004054void PeerConnection::PostSetSessionDescriptionFailure(
4055 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004056 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004057 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004058 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4059 msg->error = std::move(error);
4060 signaling_thread()->Post(RTC_FROM_HERE, this,
4061 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004062}
4063
4064void PeerConnection::PostCreateSessionDescriptionFailure(
4065 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004066 RTCError error) {
4067 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004068 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4069 msg->error = std::move(error);
4070 signaling_thread()->Post(RTC_FROM_HERE, this,
4071 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004072}
4073
zhihuang1c378ed2017-08-17 14:10:50 -07004074void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004075 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004076 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004077 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004078
Steve Antondcc3c022017-12-22 16:02:54 -08004079 if (IsUnifiedPlan()) {
4080 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4081 } else {
4082 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4083 }
4084
Steve Antonfa2260d2017-12-28 16:38:23 -08004085 // Intentionally unset the data channel type for RTP data channel with the
4086 // second condition. Otherwise the RTP data channels would be successfully
4087 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4088 // when building with chromium. We want to leave RTP data channels broken, so
4089 // people won't try to use them.
4090 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4091 session_options->data_channel_type = data_channel_type();
4092 }
4093
Steve Antondcc3c022017-12-22 16:02:54 -08004094 // Apply ICE restart flag and renomination flag.
4095 for (auto& options : session_options->media_description_options) {
4096 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4097 options.transport_options.enable_ice_renomination =
4098 configuration_.enable_ice_renomination;
4099 }
4100
4101 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004102 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004103 session_options->pooled_ice_credentials =
4104 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4105 RTC_FROM_HERE,
4106 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4107 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004108 session_options->offer_extmap_allow_mixed =
4109 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004110}
4111
4112void PeerConnection::GetOptionsForPlanBOffer(
4113 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4114 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004115 // Figure out transceiver directional preferences.
4116 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4117 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4118
4119 // By default, generate sendrecv/recvonly m= sections.
4120 bool recv_audio = true;
4121 bool recv_video = true;
4122
4123 // By default, only offer a new m= section if we have media to send with it.
4124 bool offer_new_audio_description = send_audio;
4125 bool offer_new_video_description = send_video;
4126 bool offer_new_data_description = HasDataChannels();
4127
4128 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004129 if (offer_answer_options.offer_to_receive_audio !=
4130 RTCOfferAnswerOptions::kUndefined) {
4131 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004132 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004133 offer_new_audio_description ||
4134 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004135 }
Steve Antondcc3c022017-12-22 16:02:54 -08004136 if (offer_answer_options.offer_to_receive_video !=
4137 RTCOfferAnswerOptions::kUndefined) {
4138 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004139 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004140 offer_new_video_description ||
4141 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004142 }
4143
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004144 absl::optional<size_t> audio_index;
4145 absl::optional<size_t> video_index;
4146 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004147 // If a current description exists, generate m= sections in the same order,
4148 // using the first audio/video/data section that appears and rejecting
4149 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004150 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004151 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004152 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004153 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4154 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4155 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004156 }
4157
zhihuang1c378ed2017-08-17 14:10:50 -07004158 // Add audio/video/data m= sections to the end if needed.
4159 if (!audio_index && offer_new_audio_description) {
4160 session_options->media_description_options.push_back(
4161 cricket::MediaDescriptionOptions(
4162 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004163 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4164 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004165 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004166 }
zhihuang1c378ed2017-08-17 14:10:50 -07004167 if (!video_index && offer_new_video_description) {
4168 session_options->media_description_options.push_back(
4169 cricket::MediaDescriptionOptions(
4170 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004171 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4172 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004173 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004174 }
zhihuang1c378ed2017-08-17 14:10:50 -07004175 if (!data_index && offer_new_data_description) {
4176 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004177 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004178 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004179 }
4180
4181 cricket::MediaDescriptionOptions* audio_media_description_options =
4182 !audio_index ? nullptr
4183 : &session_options->media_description_options[*audio_index];
4184 cricket::MediaDescriptionOptions* video_media_description_options =
4185 !video_index ? nullptr
4186 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004187
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004188 AddPlanBRtpSenderOptions(GetSendersInternal(),
4189 audio_media_description_options,
4190 video_media_description_options,
4191 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004192}
4193
Steve Antondcc3c022017-12-22 16:02:54 -08004194static cricket::MediaDescriptionOptions
4195GetMediaDescriptionOptionsForTransceiver(
4196 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4197 transceiver,
4198 const std::string& mid) {
4199 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004200 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004201 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004202 // This behavior is specified in JSEP. The gist is that:
4203 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4204 // sendrecv.
4205 // 2. If the MSID is included, then it must be included in any subsequent
4206 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004207 if (transceiver->stopped() ||
4208 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4209 !transceiver->internal()->has_ever_been_used_to_send())) {
4210 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004211 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004212
4213 cricket::SenderOptions sender_options;
4214 sender_options.track_id = transceiver->sender()->id();
4215 sender_options.stream_ids = transceiver->sender()->stream_ids();
4216
4217 // The following sets up RIDs and Simulcast.
4218 // RIDs are included if Simulcast is requested or if any RID was specified.
4219 RtpParameters send_parameters = transceiver->sender()->GetParameters();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004220 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4221 send_parameters.encodings.end(),
4222 [](const RtpEncodingParameters& encoding) {
4223 return !encoding.rid.empty();
4224 });
4225
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004226 std::vector<RidDescription> send_rids;
4227 SimulcastLayerList send_layers;
4228 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4229 if (encoding.rid.empty()) {
4230 continue;
4231 }
4232 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4233 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4234 }
4235
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004236 if (has_rids) {
4237 sender_options.rids = send_rids;
4238 }
4239
4240 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004241 // When RIDs are configured, we must set num_sim_layers to 0 to.
4242 // Otherwise, num_sim_layers must be 1 because either there is no
4243 // simulcast, or simulcast is acheived by munging the SDP.
4244 sender_options.num_sim_layers = has_rids ? 0 : 1;
4245 media_description_options.sender_options.push_back(sender_options);
4246
Steve Antondcc3c022017-12-22 16:02:54 -08004247 return media_description_options;
4248}
4249
Steve Anton5c72e712018-12-10 14:25:30 -08004250// Returns the ContentInfo at mline index |i|, or null if none exists.
4251static const ContentInfo* GetContentByIndex(
4252 const SessionDescriptionInterface* sdesc,
4253 size_t i) {
4254 if (!sdesc) {
4255 return nullptr;
4256 }
4257 const ContentInfos& contents = sdesc->description()->contents();
4258 return (i < contents.size() ? &contents[i] : nullptr);
4259}
4260
Steve Antondcc3c022017-12-22 16:02:54 -08004261void PeerConnection::GetOptionsForUnifiedPlanOffer(
4262 const RTCOfferAnswerOptions& offer_answer_options,
4263 cricket::MediaSessionOptions* session_options) {
4264 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4265 // Offers) and 5.2.2 (Subsequent Offers).
4266 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4267 const ContentInfos& local_contents =
4268 (local_description() ? local_description()->description()->contents()
4269 : ContentInfos());
4270 const ContentInfos& remote_contents =
4271 (remote_description() ? remote_description()->description()->contents()
4272 : ContentInfos());
4273 // The mline indices that can be recycled. New transceivers should reuse these
4274 // slots first.
4275 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004276 // First, go through each media section that exists in either the local or
4277 // remote description and generate a media section in this offer for the
4278 // associated transceiver. If a media section can be recycled, generate a
4279 // default, rejected media section here that can be later overwritten.
4280 for (size_t i = 0;
4281 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4282 // Either |local_content| or |remote_content| is non-null.
4283 const ContentInfo* local_content =
4284 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004285 const ContentInfo* current_local_content =
4286 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004287 const ContentInfo* remote_content =
4288 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004289 const ContentInfo* current_remote_content =
4290 GetContentByIndex(current_remote_description(), i);
4291 bool had_been_rejected =
4292 (current_local_content && current_local_content->rejected) ||
4293 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004294 const std::string& mid =
4295 (local_content ? local_content->name : remote_content->name);
4296 cricket::MediaType media_type =
4297 (local_content ? local_content->media_description()->type()
4298 : remote_content->media_description()->type());
4299 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4300 media_type == cricket::MEDIA_TYPE_VIDEO) {
4301 auto transceiver = GetAssociatedTransceiver(mid);
4302 RTC_CHECK(transceiver);
4303 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004304 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004305 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004306 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004307 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4308 RtpTransceiverDirection::kInactive,
4309 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004310 recycleable_mline_indices.push(i);
4311 } else {
4312 session_options->media_description_options.push_back(
4313 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4314 // CreateOffer shouldn't really cause any state changes in
4315 // PeerConnection, but we need a way to match new transceivers to new
4316 // media sections in SetLocalDescription and JSEP specifies this is done
4317 // by recording the index of the media section generated for the
4318 // transceiver in the offer.
4319 transceiver->internal()->set_mline_index(i);
4320 }
4321 } else {
4322 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004323 RTC_CHECK(GetDataMid());
4324 if (had_been_rejected || mid != *GetDataMid()) {
4325 session_options->media_description_options.push_back(
4326 GetMediaDescriptionOptionsForRejectedData(mid));
4327 } else {
4328 session_options->media_description_options.push_back(
4329 GetMediaDescriptionOptionsForActiveData(mid));
4330 }
Steve Antondcc3c022017-12-22 16:02:54 -08004331 }
4332 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004333
Steve Antondcc3c022017-12-22 16:02:54 -08004334 // Next, look for transceivers that are newly added (that is, are not stopped
4335 // and not associated). Reuse media sections marked as recyclable first,
4336 // otherwise append to the end of the offer. New media sections should be
4337 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004338 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004339 if (transceiver->mid() || transceiver->stopped()) {
4340 continue;
4341 }
4342 size_t mline_index;
4343 if (!recycleable_mline_indices.empty()) {
4344 mline_index = recycleable_mline_indices.front();
4345 recycleable_mline_indices.pop();
4346 session_options->media_description_options[mline_index] =
4347 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004348 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004349 } else {
4350 mline_index = session_options->media_description_options.size();
4351 session_options->media_description_options.push_back(
4352 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004353 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004354 }
4355 // See comment above for why CreateOffer changes the transceiver's state.
4356 transceiver->internal()->set_mline_index(mline_index);
4357 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004358 // Lastly, add a m-section if we have local data channels and an m section
4359 // does not already exist.
4360 if (!GetDataMid() && HasDataChannels()) {
4361 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004362 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004363 }
Steve Antondcc3c022017-12-22 16:02:54 -08004364}
4365
4366void PeerConnection::GetOptionsForAnswer(
4367 const RTCOfferAnswerOptions& offer_answer_options,
4368 cricket::MediaSessionOptions* session_options) {
4369 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4370
4371 if (IsUnifiedPlan()) {
4372 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4373 } else {
4374 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4375 }
4376
Steve Antonfa2260d2017-12-28 16:38:23 -08004377 // Intentionally unset the data channel type for RTP data channel. Otherwise
4378 // the RTP data channels would be successfully negotiated by default and the
4379 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4380 // We want to leave RTP data channels broken, so people won't try to use them.
4381 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4382 session_options->data_channel_type = data_channel_type();
4383 }
4384
Steve Antondcc3c022017-12-22 16:02:54 -08004385 // Apply ICE renomination flag.
4386 for (auto& options : session_options->media_description_options) {
4387 options.transport_options.enable_ice_renomination =
4388 configuration_.enable_ice_renomination;
4389 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004390
4391 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004392 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004393 session_options->pooled_ice_credentials =
4394 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4395 RTC_FROM_HERE,
4396 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4397 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004398}
4399
Steve Antondcc3c022017-12-22 16:02:54 -08004400void PeerConnection::GetOptionsForPlanBAnswer(
4401 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004402 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004403 // Figure out transceiver directional preferences.
4404 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4405 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4406
4407 // By default, generate sendrecv/recvonly m= sections. The direction is also
4408 // restricted by the direction in the offer.
4409 bool recv_audio = true;
4410 bool recv_video = true;
4411
4412 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004413 if (offer_answer_options.offer_to_receive_audio !=
4414 RTCOfferAnswerOptions::kUndefined) {
4415 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004416 }
Steve Antondcc3c022017-12-22 16:02:54 -08004417 if (offer_answer_options.offer_to_receive_video !=
4418 RTCOfferAnswerOptions::kUndefined) {
4419 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004420 }
4421
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004422 absl::optional<size_t> audio_index;
4423 absl::optional<size_t> video_index;
4424 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004425
4426 // Generate m= sections that match those in the offer.
4427 // Note that mediasession.cc will handle intersection our preferred
4428 // direction with the offered direction.
4429 GenerateMediaDescriptionOptions(
4430 remote_description(),
4431 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4432 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4433 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004434
4435 cricket::MediaDescriptionOptions* audio_media_description_options =
4436 !audio_index ? nullptr
4437 : &session_options->media_description_options[*audio_index];
4438 cricket::MediaDescriptionOptions* video_media_description_options =
4439 !video_index ? nullptr
4440 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004441
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004442 AddPlanBRtpSenderOptions(GetSendersInternal(),
4443 audio_media_description_options,
4444 video_media_description_options,
4445 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004446}
zhihuangaf388472016-11-02 16:49:48 -07004447
Steve Antondcc3c022017-12-22 16:02:54 -08004448void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4449 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4450 cricket::MediaSessionOptions* session_options) {
4451 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4452 // Answers) and 5.3.2 (Subsequent Answers).
4453 RTC_DCHECK(remote_description());
4454 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4455 for (const ContentInfo& content :
4456 remote_description()->description()->contents()) {
4457 cricket::MediaType media_type = content.media_description()->type();
4458 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4459 media_type == cricket::MEDIA_TYPE_VIDEO) {
4460 auto transceiver = GetAssociatedTransceiver(content.name);
4461 RTC_CHECK(transceiver);
4462 session_options->media_description_options.push_back(
4463 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4464 } else {
4465 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004466 // Reject all data sections if data channels are disabled.
4467 // Reject a data section if it has already been rejected.
4468 // Reject all data sections except for the first one.
4469 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4470 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004471 session_options->media_description_options.push_back(
4472 GetMediaDescriptionOptionsForRejectedData(content.name));
4473 } else {
4474 session_options->media_description_options.push_back(
4475 GetMediaDescriptionOptionsForActiveData(content.name));
4476 }
Steve Antondcc3c022017-12-22 16:02:54 -08004477 }
4478 }
htaa2a49d92016-03-04 02:51:39 -08004479}
4480
zhihuang1c378ed2017-08-17 14:10:50 -07004481void PeerConnection::GenerateMediaDescriptionOptions(
4482 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004483 RtpTransceiverDirection audio_direction,
4484 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004485 absl::optional<size_t>* audio_index,
4486 absl::optional<size_t>* video_index,
4487 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004488 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004489 for (const cricket::ContentInfo& content :
4490 session_desc->description()->contents()) {
4491 if (IsAudioContent(&content)) {
4492 // If we already have an audio m= section, reject this extra one.
4493 if (*audio_index) {
4494 session_options->media_description_options.push_back(
4495 cricket::MediaDescriptionOptions(
4496 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004497 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004498 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004499 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004500 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004501 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4502 content.name, audio_direction,
4503 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004504 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004505 }
4506 } else if (IsVideoContent(&content)) {
4507 // If we already have an video m= section, reject this extra one.
4508 if (*video_index) {
4509 session_options->media_description_options.push_back(
4510 cricket::MediaDescriptionOptions(
4511 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004512 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004513 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004514 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004515 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004516 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4517 content.name, video_direction,
4518 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004519 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004520 }
4521 } else {
4522 RTC_DCHECK(IsDataContent(&content));
4523 // If we already have an data m= section, reject this extra one.
4524 if (*data_index) {
4525 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004526 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004527 } else {
4528 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004529 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004530 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004531 }
4532 }
htaa2a49d92016-03-04 02:51:39 -08004533 }
deadbeefab9b2d12015-10-14 11:33:11 -07004534}
4535
Steve Antonfa2260d2017-12-28 16:38:23 -08004536cricket::MediaDescriptionOptions
4537PeerConnection::GetMediaDescriptionOptionsForActiveData(
4538 const std::string& mid) const {
4539 // Direction for data sections is meaningless, but legacy endpoints might
4540 // expect sendrecv.
4541 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4542 RtpTransceiverDirection::kSendRecv,
4543 /*stopped=*/false);
4544 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4545 return options;
4546}
4547
4548cricket::MediaDescriptionOptions
4549PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4550 const std::string& mid) const {
4551 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4552 RtpTransceiverDirection::kInactive,
4553 /*stopped=*/true);
4554 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4555 return options;
4556}
4557
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004558absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004559 switch (data_channel_type_) {
4560 case cricket::DCT_RTP:
4561 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004562 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004563 }
4564 return rtp_data_channel_->content_name();
4565 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004566 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004567 case cricket::DCT_MEDIA_TRANSPORT:
4568 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004569 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004570 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004571 }
4572}
4573
Steve Anton4171afb2017-11-20 10:20:22 -08004574void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4575 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4576 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004577 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004578}
4579
Steve Anton4171afb2017-11-20 10:20:22 -08004580void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004581 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004582 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004583 cricket::MediaType media_type,
4584 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004585 RTC_DCHECK(!IsUnifiedPlan());
4586
Steve Anton4171afb2017-11-20 10:20:22 -08004587 std::vector<RtpSenderInfo>* current_senders =
4588 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004589
Steve Anton4171afb2017-11-20 10:20:22 -08004590 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004591 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004592 for (auto sender_it = current_senders->begin();
4593 sender_it != current_senders->end();
4594 /* incremented manually */) {
4595 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004596 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004597 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004598 std::string params_stream_id;
4599 if (params) {
4600 params_stream_id =
4601 (!params->first_stream_id().empty() ? params->first_stream_id()
4602 : kDefaultStreamId);
4603 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004604 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004605 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004606 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004607 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004608 sender_exists) {
4609 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004610 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004611 OnRemoteSenderRemoved(info, media_type);
4612 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004613 }
4614 }
4615
Steve Anton4171afb2017-11-20 10:20:22 -08004616 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004617 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004618 if (!params.has_ssrcs()) {
4619 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4620 // sender, this means it is coming from a Unified Plan endpoint,so we just
4621 // create a default.
4622 default_sender_needed = true;
4623 break;
4624 }
4625
Seth Hampson845e8782018-03-02 11:34:10 -08004626 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004627 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004628 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4629 // not supported in Plan B, we just take the first here and create the
4630 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004631 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004632 (!params.first_stream_id().empty() ? params.first_stream_id()
4633 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004634 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004635 uint32_t ssrc = params.first_ssrc();
4636
4637 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004638 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004639 if (!stream) {
4640 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004641 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004642 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004643 remote_streams_->AddStream(stream);
4644 new_streams->AddStream(stream);
4645 }
4646
Steve Anton4171afb2017-11-20 10:20:22 -08004647 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004648 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004649 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004650 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004651 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004652 }
4653 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004654
Steve Anton4171afb2017-11-20 10:20:22 -08004655 // Add default sender if necessary.
4656 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004657 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004658 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004659 if (!default_stream) {
4660 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004661 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004662 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004663 remote_streams_->AddStream(default_stream);
4664 new_streams->AddStream(default_stream);
4665 }
Steve Anton4171afb2017-11-20 10:20:22 -08004666 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4667 ? kDefaultAudioSenderId
4668 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004669 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004670 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004671 if (!default_sender_info) {
4672 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004673 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004674 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004675 }
4676 }
deadbeefab9b2d12015-10-14 11:33:11 -07004677}
4678
Steve Anton4171afb2017-11-20 10:20:22 -08004679void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4680 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004681 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4682 << " receiver for track_id=" << sender_info.sender_id
4683 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004684
Steve Anton3d954a62018-04-02 11:27:23 -07004685 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004686 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004687 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004688 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004689 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004690 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004691 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004692 }
4693}
4694
Steve Anton4171afb2017-11-20 10:20:22 -08004695void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4696 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004697 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4698 << " receiver for track_id=" << sender_info.sender_id
4699 << " and stream_id=" << sender_info.stream_id;
4700
Seth Hampson845e8782018-03-02 11:34:10 -08004701 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004702
Henrik Boström933d8b02017-10-10 10:05:16 -07004703 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004704 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004705 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4706 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004707 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004708 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004709 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004710 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004711 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004712 }
4713 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004714 // Stopping or destroying a VideoRtpReceiver will end the
4715 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004716 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004717 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004718 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004719 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004720 // There's no guarantee the track is still available, e.g. the track may
4721 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004722 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004723 }
4724 } else {
nisseede5da42017-01-12 05:15:36 -08004725 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004726 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004727 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004728 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004729 }
deadbeefab9b2d12015-10-14 11:33:11 -07004730}
4731
4732void PeerConnection::UpdateEndedRemoteMediaStreams() {
4733 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4734 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4735 MediaStreamInterface* stream = remote_streams_->at(i);
4736 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4737 streams_to_remove.push_back(stream);
4738 }
4739 }
4740
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004741 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004742 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004743 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004744 }
4745}
4746
Steve Anton4171afb2017-11-20 10:20:22 -08004747void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004748 const std::vector<cricket::StreamParams>& streams,
4749 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004750 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004751
Seth Hampson845e8782018-03-02 11:34:10 -08004752 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004753 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004754 for (auto sender_it = current_senders->begin();
4755 sender_it != current_senders->end();
4756 /* incremented manually */) {
4757 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004758 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004759 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4760 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004761 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004762 OnLocalSenderRemoved(info, media_type);
4763 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004764 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004765 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004766 }
4767 }
4768
Steve Anton4171afb2017-11-20 10:20:22 -08004769 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004770 for (const cricket::StreamParams& params : streams) {
4771 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004772 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004773 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004774 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004775 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004776 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004777 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004778 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004779 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004780 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004781 }
4782 }
4783}
4784
Steve Anton4171afb2017-11-20 10:20:22 -08004785void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4786 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004787 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004788 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004789 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004790 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4791 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004792 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004793 return;
4794 }
4795
deadbeeffac06552015-11-25 11:26:01 -08004796 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004797 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004798 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004799 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004800 }
deadbeeffac06552015-11-25 11:26:01 -08004801
Seth Hampson5b4f0752018-04-02 16:31:36 -07004802 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004803 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004804}
4805
Steve Anton4171afb2017-11-20 10:20:22 -08004806void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4807 cricket::MediaType media_type) {
4808 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004809 if (!sender) {
4810 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004811 // SessionDescriptions has been renegotiated.
4812 return;
4813 }
deadbeeffac06552015-11-25 11:26:01 -08004814
4815 // A sender has been removed from the SessionDescription but it's still
4816 // associated with the PeerConnection. This only occurs if the SDP doesn't
4817 // match with the calls to CreateSender, AddStream and RemoveStream.
4818 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004819 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004820 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004821 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004822 }
deadbeeffac06552015-11-25 11:26:01 -08004823
Steve Anton4171afb2017-11-20 10:20:22 -08004824 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004825}
4826
4827void PeerConnection::UpdateLocalRtpDataChannels(
4828 const cricket::StreamParamsVec& streams) {
4829 std::vector<std::string> existing_channels;
4830
4831 // Find new and active data channels.
4832 for (const cricket::StreamParams& params : streams) {
4833 // |it->sync_label| is actually the data channel label. The reason is that
4834 // we use the same naming of data channels as we do for
4835 // MediaStreams and Tracks.
4836 // For MediaStreams, the sync_label is the MediaStream label and the
4837 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004838 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004839 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004840 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004841 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004842 continue;
4843 }
4844 // Set the SSRC the data channel should use for sending.
4845 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4846 existing_channels.push_back(data_channel_it->first);
4847 }
4848
4849 UpdateClosingRtpDataChannels(existing_channels, true);
4850}
4851
4852void PeerConnection::UpdateRemoteRtpDataChannels(
4853 const cricket::StreamParamsVec& streams) {
4854 std::vector<std::string> existing_channels;
4855
4856 // Find new and active data channels.
4857 for (const cricket::StreamParams& params : streams) {
4858 // The data channel label is either the mslabel or the SSRC if the mslabel
4859 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004860 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004861 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004862 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004863 auto data_channel_it = rtp_data_channels_.find(label);
4864 if (data_channel_it == rtp_data_channels_.end()) {
4865 // This is a new data channel.
4866 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4867 } else {
4868 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4869 }
4870 existing_channels.push_back(label);
4871 }
4872
4873 UpdateClosingRtpDataChannels(existing_channels, false);
4874}
4875
4876void PeerConnection::UpdateClosingRtpDataChannels(
4877 const std::vector<std::string>& active_channels,
4878 bool is_local_update) {
4879 auto it = rtp_data_channels_.begin();
4880 while (it != rtp_data_channels_.end()) {
4881 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004882 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004883 ++it;
4884 continue;
4885 }
4886
4887 if (is_local_update) {
4888 data_channel->SetSendSsrc(0);
4889 } else {
4890 data_channel->RemotePeerRequestClose();
4891 }
4892
4893 if (data_channel->state() == DataChannel::kClosed) {
4894 rtp_data_channels_.erase(it);
4895 it = rtp_data_channels_.begin();
4896 } else {
4897 ++it;
4898 }
4899 }
4900}
4901
4902void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4903 uint32_t remote_ssrc) {
4904 rtc::scoped_refptr<DataChannel> channel(
4905 InternalCreateDataChannel(label, nullptr));
4906 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004907 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004908 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004909 return;
4910 }
4911 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004912 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4913 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004914 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004915}
4916
4917rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4918 const std::string& label,
4919 const InternalDataChannelInit* config) {
4920 if (IsClosed()) {
4921 return nullptr;
4922 }
Steve Anton75737c02017-11-06 10:37:17 -08004923 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004924 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004925 << "InternalCreateDataChannel: Data is not supported in this call.";
4926 return nullptr;
4927 }
4928 InternalDataChannelInit new_config =
4929 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004930 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004931 if (new_config.id < 0) {
4932 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004933 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004934 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004935 RTC_LOG(LS_ERROR)
4936 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004937 return nullptr;
4938 }
4939 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004940 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004941 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004942 return nullptr;
4943 }
4944 }
4945
Steve Anton75737c02017-11-06 10:37:17 -08004946 rtc::scoped_refptr<DataChannel> channel(
4947 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004948 if (!channel) {
4949 sid_allocator_.ReleaseSid(new_config.id);
4950 return nullptr;
4951 }
4952
4953 if (channel->data_channel_type() == cricket::DCT_RTP) {
4954 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004955 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4956 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004957 return nullptr;
4958 }
4959 rtp_data_channels_[channel->label()] = channel;
4960 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004961 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004962 sctp_data_channels_.push_back(channel);
4963 channel->SignalClosed.connect(this,
4964 &PeerConnection::OnSctpDataChannelClosed);
4965 }
4966
Steve Anton2d8609c2018-01-23 16:38:46 -08004967 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004968 return channel;
4969}
4970
4971bool PeerConnection::HasDataChannels() const {
4972 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4973}
4974
4975void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4976 for (const auto& channel : sctp_data_channels_) {
4977 if (channel->id() < 0) {
4978 int sid;
4979 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004980 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004981 continue;
4982 }
4983 channel->SetSctpSid(sid);
4984 }
4985 }
4986}
4987
4988void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004989 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004990 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4991 ++it) {
4992 if (it->get() == channel) {
4993 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004994 // After the closing procedure is done, it's safe to use this ID for
4995 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004996 sid_allocator_.ReleaseSid(channel->id());
4997 }
deadbeefbd292462015-12-14 18:15:29 -08004998 // Since this method is triggered by a signal from the DataChannel,
4999 // we can't free it directly here; we need to free it asynchronously.
5000 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005001 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005002 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5003 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005004 return;
5005 }
5006 }
5007}
5008
deadbeefab9b2d12015-10-14 11:33:11 -07005009void PeerConnection::OnDataChannelDestroyed() {
5010 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5011 // DataChannel may callback to us and try to modify the list.
5012 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5013 temp_rtp_dcs.swap(rtp_data_channels_);
5014 for (const auto& kv : temp_rtp_dcs) {
5015 kv.second->OnTransportChannelDestroyed();
5016 }
5017
5018 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5019 temp_sctp_dcs.swap(sctp_data_channels_);
5020 for (const auto& channel : temp_sctp_dcs) {
5021 channel->OnTransportChannelDestroyed();
5022 }
5023}
5024
5025void PeerConnection::OnDataChannelOpenMessage(
5026 const std::string& label,
5027 const InternalDataChannelInit& config) {
5028 rtc::scoped_refptr<DataChannel> channel(
5029 InternalCreateDataChannel(label, &config));
5030 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005031 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005032 return;
5033 }
5034
deadbeefa601f5c2016-06-06 14:27:39 -07005035 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5036 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005037 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005038 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005039}
5040
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005041bool PeerConnection::HandleOpenMessage_s(
5042 const cricket::ReceiveDataParams& params,
5043 const rtc::CopyOnWriteBuffer& buffer) {
5044 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5045 // Received OPEN message; parse and signal that a new data channel should
5046 // be created.
5047 std::string label;
5048 InternalDataChannelInit config;
5049 config.id = params.ssrc;
5050 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5051 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5052 << params.ssrc;
5053 return true;
5054 }
5055 config.open_handshake_role = InternalDataChannelInit::kAcker;
5056 OnDataChannelOpenMessage(label, config);
5057 return true;
5058 }
5059 return false;
5060}
5061
Steve Anton4171afb2017-11-20 10:20:22 -08005062rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5063PeerConnection::GetAudioTransceiver() const {
5064 // This method only works with Plan B SDP, where there is a single
5065 // audio/video transceiver.
5066 RTC_DCHECK(!IsUnifiedPlan());
5067 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005068 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005069 return transceiver;
5070 }
5071 }
5072 RTC_NOTREACHED();
5073 return nullptr;
5074}
5075
5076rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5077PeerConnection::GetVideoTransceiver() const {
5078 // This method only works with Plan B SDP, where there is a single
5079 // audio/video transceiver.
5080 RTC_DCHECK(!IsUnifiedPlan());
5081 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005082 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005083 return transceiver;
5084 }
5085 }
5086 RTC_NOTREACHED();
5087 return nullptr;
5088}
5089
5090// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5091// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005092bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005093 switch (type) {
5094 case cricket::MEDIA_TYPE_AUDIO:
5095 return !GetAudioTransceiver()->internal()->senders().empty();
5096 case cricket::MEDIA_TYPE_VIDEO:
5097 return !GetVideoTransceiver()->internal()->senders().empty();
5098 case cricket::MEDIA_TYPE_DATA:
5099 return false;
5100 }
5101 RTC_NOTREACHED();
5102 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005103}
5104
Steve Anton4171afb2017-11-20 10:20:22 -08005105rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5106PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005107 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005108 for (auto sender : transceiver->internal()->senders()) {
5109 if (sender->track() == track) {
5110 return sender;
5111 }
5112 }
5113 }
5114 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005115}
5116
Steve Anton4171afb2017-11-20 10:20:22 -08005117rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5118PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005119 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005120 for (auto sender : transceiver->internal()->senders()) {
5121 if (sender->id() == sender_id) {
5122 return sender;
5123 }
5124 }
5125 }
5126 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005127}
5128
Steve Anton4171afb2017-11-20 10:20:22 -08005129rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5130PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005131 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005132 for (auto receiver : transceiver->internal()->receivers()) {
5133 if (receiver->id() == receiver_id) {
5134 return receiver;
5135 }
5136 }
5137 }
5138 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005139}
5140
Steve Anton4171afb2017-11-20 10:20:22 -08005141std::vector<PeerConnection::RtpSenderInfo>*
5142PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5143 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5144 media_type == cricket::MEDIA_TYPE_VIDEO);
5145 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5146 ? &remote_audio_sender_infos_
5147 : &remote_video_sender_infos_;
5148}
5149
5150std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005151 cricket::MediaType media_type) {
5152 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5153 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005154 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5155 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005156}
5157
Steve Anton4171afb2017-11-20 10:20:22 -08005158const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5159 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005160 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005161 const std::string sender_id) const {
5162 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005163 if (sender_info.stream_id == stream_id &&
5164 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005165 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005166 }
5167 }
5168 return nullptr;
5169}
5170
5171DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5172 for (const auto& channel : sctp_data_channels_) {
5173 if (channel->id() == sid) {
5174 return channel;
5175 }
5176 }
5177 return nullptr;
5178}
5179
deadbeef91dd5672016-05-18 16:55:30 -07005180bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005181 const cricket::ServerAddresses& stun_servers,
5182 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005183 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005184 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005185 // To handle both internal and externally created port allocator, we will
5186 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005187 port_allocator_flags_ = port_allocator_->flags();
5188 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5189 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5190 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005191 // If the disable-IPv6 flag was specified, we'll not override it
5192 // by experiment.
5193 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005194 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005195 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5196 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005197 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005198 }
5199
zhihuangb09b3f92017-03-07 14:40:51 -08005200 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005201 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005202 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005203 }
5204
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005205 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005206 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005207 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005208 }
5209
honghaiz60347052016-05-31 18:29:12 -07005210 if (configuration.candidate_network_policy ==
5211 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005212 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005213 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005214 }
5215
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005216 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005217 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005218 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5219 }
5220
Qingsi Wanga2d60672018-04-11 16:57:45 -07005221 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005222 // No step delay is used while allocating ports.
5223 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5224 port_allocator_->set_candidate_filter(
5225 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005226 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005227
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005228 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005229 for (auto& turn_server : turn_servers_copy) {
5230 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005231 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005232 // Call this last since it may create pooled allocator sessions using the
5233 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005234 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005235 stun_servers, std::move(turn_servers_copy),
5236 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5237 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005238 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005239 return true;
5240}
5241
deadbeef91dd5672016-05-18 16:55:30 -07005242bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005243 const cricket::ServerAddresses& stun_servers,
5244 const std::vector<cricket::RelayServerConfig>& turn_servers,
5245 IceTransportsType type,
5246 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005247 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005248 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005249 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005250 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005251 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005252 // According to JSEP, after setLocalDescription, changing the candidate pool
5253 // size is not allowed, and changing the set of ICE servers will not result
5254 // in new candidates being gathered.
5255 if (local_description()) {
5256 port_allocator_->FreezeCandidatePool();
5257 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005258 // Add the custom tls turn servers if they exist.
5259 auto turn_servers_copy = turn_servers;
5260 for (auto& turn_server : turn_servers_copy) {
5261 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5262 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005263 // Call this last since it may create pooled allocator sessions using the
5264 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005265 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005266 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5267 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005268}
5269
Steve Antonba818672017-11-06 10:21:57 -08005270cricket::ChannelManager* PeerConnection::channel_manager() const {
5271 return factory_->channel_manager();
5272}
5273
Elad Alon99c3fe52017-10-13 16:29:40 +02005274bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005275 std::unique_ptr<RtcEventLogOutput> output,
5276 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005277 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005278 if (!event_log_) {
5279 return false;
5280 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005281 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005282}
5283
5284void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005285 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005286 if (event_log_) {
5287 event_log_->StopLogging();
5288 }
ivoc14d5dbe2016-07-04 07:06:55 -07005289}
nisseeaabdf62017-05-05 02:23:02 -07005290
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005291cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005292 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005293 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005294 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005295 if (channel && channel->content_name() == content_name) {
5296 return channel;
5297 }
Steve Anton75737c02017-11-06 10:37:17 -08005298 }
5299 if (rtp_data_channel() &&
5300 rtp_data_channel()->content_name() == content_name) {
5301 return rtp_data_channel();
5302 }
5303 return nullptr;
5304}
5305
5306bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005307 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005308 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005309 RTC_LOG(LS_INFO)
5310 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005311 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005312 return false;
5313 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005314 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005315 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005316 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005317 return false;
5318 }
5319
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005320 absl::optional<rtc::SSLRole> dtls_role;
5321 if (sctp_mid_) {
5322 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5323 } else if (is_caller_) {
5324 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5325 }
Zhi Huange830e682018-03-30 10:48:35 -07005326 if (dtls_role) {
5327 *role = *dtls_role;
5328 return true;
5329 }
5330 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005331}
5332
5333bool PeerConnection::GetSslRole(const std::string& content_name,
5334 rtc::SSLRole* role) {
5335 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005336 RTC_LOG(LS_INFO)
5337 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005338 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005339 return false;
5340 }
5341
Zhi Huange830e682018-03-30 10:48:35 -07005342 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5343 if (dtls_role) {
5344 *role = *dtls_role;
5345 return true;
5346 }
5347 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005348}
5349
Steve Antonf8470812017-12-04 10:46:21 -08005350void PeerConnection::SetSessionError(SessionError error,
5351 const std::string& error_desc) {
5352 RTC_DCHECK_RUN_ON(signaling_thread());
5353 if (error != session_error_) {
5354 session_error_ = error;
5355 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005356 }
5357}
5358
Zhi Huange830e682018-03-30 10:48:35 -07005359RTCError PeerConnection::UpdateSessionState(
5360 SdpType type,
5361 cricket::ContentSource source,
5362 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005363 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005364
5365 // If there's already a pending error then no state transition should happen.
5366 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005367 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005368
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005369 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005370 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005371 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005372 }
5373
5374 // Update the signaling state according to the specified state machine (see
5375 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005376 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005377 ChangeSignalingState(source == cricket::CS_LOCAL
5378 ? PeerConnectionInterface::kHaveLocalOffer
5379 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005380 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005381 ChangeSignalingState(source == cricket::CS_LOCAL
5382 ? PeerConnectionInterface::kHaveLocalPrAnswer
5383 : PeerConnectionInterface::kHaveRemotePrAnswer);
5384 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005385 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005386 ChangeSignalingState(PeerConnectionInterface::kStable);
5387 }
5388
5389 // Update internal objects according to the session description's media
5390 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005391 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005392 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005393 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005394 }
5395
Steve Anton8a006912017-12-04 15:25:56 -08005396 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005397}
5398
Steve Anton8a006912017-12-04 15:25:56 -08005399RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005400 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005401 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005402 const SessionDescriptionInterface* sdesc =
5403 (source == cricket::CS_LOCAL ? local_description()
5404 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005405 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005406
5407 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005408 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005409 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005410 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005411 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005412 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005413 continue;
5414 }
5415 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005416 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005417 if (!content_desc) {
5418 continue;
5419 }
5420 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005421 bool success = (source == cricket::CS_LOCAL)
5422 ? channel->SetLocalContent(content_desc, type, &error)
5423 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005424 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005425 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005426 }
5427 }
5428
5429 // If using the RtpDataChannel, push down the new SDP section for it too.
5430 if (rtp_data_channel_) {
5431 const ContentInfo* data_content =
5432 cricket::GetFirstDataContent(sdesc->description());
5433 if (data_content && !data_content->rejected) {
5434 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005435 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005436 if (data_desc) {
5437 std::string error;
5438 bool success =
5439 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005440 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005441 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005442 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005443 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005444 }
Steve Anton75737c02017-11-06 10:37:17 -08005445 }
5446 }
5447 }
Steve Antoned10bd92017-12-05 10:52:59 -08005448
Steve Anton75737c02017-11-06 10:37:17 -08005449 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5450 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5451 if (sctp_transport_ && local_description() && remote_description() &&
5452 cricket::GetFirstDataContent(local_description()->description()) &&
5453 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005454 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005455 RTC_FROM_HERE,
5456 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005457 if (!success) {
5458 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5459 "Failed to push down SCTP parameters.");
5460 }
Steve Anton75737c02017-11-06 10:37:17 -08005461 }
Steve Antoned10bd92017-12-05 10:52:59 -08005462
Steve Anton8a006912017-12-04 15:25:56 -08005463 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005464}
5465
5466bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5467 RTC_DCHECK(network_thread()->IsCurrent());
5468 RTC_DCHECK(local_description());
5469 RTC_DCHECK(remote_description());
5470 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5471 // When we support "max-message-size", that would also be pushed down here.
5472 return sctp_transport_->Start(
5473 GetSctpPort(local_description()->description()),
5474 GetSctpPort(remote_description()->description()));
5475}
5476
Steve Anton8a006912017-12-04 15:25:56 -08005477RTCError PeerConnection::PushdownTransportDescription(
5478 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005479 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005480 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005481
Zhi Huange830e682018-03-30 10:48:35 -07005482 if (source == cricket::CS_LOCAL) {
5483 const SessionDescriptionInterface* sdesc = local_description();
5484 RTC_DCHECK(sdesc);
5485 return transport_controller_->SetLocalDescription(type,
5486 sdesc->description());
5487 } else {
5488 const SessionDescriptionInterface* sdesc = remote_description();
5489 RTC_DCHECK(sdesc);
5490 return transport_controller_->SetRemoteDescription(type,
5491 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005492 }
Steve Anton75737c02017-11-06 10:37:17 -08005493}
5494
5495bool PeerConnection::GetTransportDescription(
5496 const SessionDescription* description,
5497 const std::string& content_name,
5498 cricket::TransportDescription* tdesc) {
5499 if (!description || !tdesc) {
5500 return false;
5501 }
5502 const TransportInfo* transport_info =
5503 description->GetTransportInfoByName(content_name);
5504 if (!transport_info) {
5505 return false;
5506 }
5507 *tdesc = transport_info->description;
5508 return true;
5509}
5510
Steve Anton75737c02017-11-06 10:37:17 -08005511cricket::IceConfig PeerConnection::ParseIceConfig(
5512 const PeerConnectionInterface::RTCConfiguration& config) const {
5513 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005514 switch (config.continual_gathering_policy) {
5515 case PeerConnectionInterface::GATHER_ONCE:
5516 gathering_policy = cricket::GATHER_ONCE;
5517 break;
5518 case PeerConnectionInterface::GATHER_CONTINUALLY:
5519 gathering_policy = cricket::GATHER_CONTINUALLY;
5520 break;
5521 default:
5522 RTC_NOTREACHED();
5523 gathering_policy = cricket::GATHER_ONCE;
5524 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005525
Steve Anton75737c02017-11-06 10:37:17 -08005526 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005527 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5528 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005529 ice_config.prioritize_most_likely_candidate_pairs =
5530 config.prioritize_most_likely_ice_candidate_pairs;
5531 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005532 RTCConfigurationToIceConfigOptionalInt(
5533 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005534 ice_config.continual_gathering_policy = gathering_policy;
5535 ice_config.presume_writable_when_fully_relayed =
5536 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005537 ice_config.ice_check_interval_strong_connectivity =
5538 config.ice_check_interval_strong_connectivity;
5539 ice_config.ice_check_interval_weak_connectivity =
5540 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005541 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005542 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5543 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005544 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005545 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005546 ice_config.regather_all_networks_interval_range =
5547 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005548 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005549 return ice_config;
5550}
5551
Steve Antona41959e2018-11-28 11:15:33 -08005552static absl::string_view GetTrackIdBySsrc(
5553 const SessionDescriptionInterface* session_description,
5554 uint32_t ssrc) {
5555 if (!session_description) {
5556 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005557 }
Steve Antona41959e2018-11-28 11:15:33 -08005558 for (const cricket::ContentInfo& content :
5559 session_description->description()->contents()) {
5560 const cricket::MediaContentDescription& media =
5561 *content.media_description();
5562 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5563 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5564 const cricket::StreamParams* stream_params =
5565 cricket::GetStreamBySsrc(media.streams(), ssrc);
5566 if (stream_params) {
5567 return stream_params->id;
5568 }
5569 }
5570 }
5571 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005572}
5573
Steve Antona41959e2018-11-28 11:15:33 -08005574absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5575 return GetTrackIdBySsrc(local_description(), ssrc);
5576}
5577
5578absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5579 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005580}
5581
5582bool PeerConnection::SendData(const cricket::SendDataParams& params,
5583 const rtc::CopyOnWriteBuffer& payload,
5584 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005585 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5586 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5587 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005588 return false;
5589 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005590 if (media_transport_) {
5591 SendDataParams send_params;
5592 send_params.type = ToWebrtcDataMessageType(params.type);
5593 send_params.ordered = params.ordered;
5594 if (params.max_rtx_count >= 0) {
5595 send_params.max_rtx_count = params.max_rtx_count;
5596 } else if (params.max_rtx_ms >= 0) {
5597 send_params.max_rtx_ms = params.max_rtx_ms;
5598 }
5599 return media_transport_->SendData(params.sid, send_params, payload).ok();
5600 }
Steve Anton75737c02017-11-06 10:37:17 -08005601 return rtp_data_channel_
5602 ? rtp_data_channel_->SendData(params, payload, result)
5603 : network_thread()->Invoke<bool>(
5604 RTC_FROM_HERE,
5605 Bind(&cricket::SctpTransportInternal::SendData,
5606 sctp_transport_.get(), params, payload, result));
5607}
5608
5609bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005610 RTC_DCHECK_RUN_ON(signaling_thread());
5611 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005612 // Don't log an error here, because DataChannels are expected to call
5613 // ConnectDataChannel in this state. It's the only way to initially tell
5614 // whether or not the underlying transport is ready.
5615 return false;
5616 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005617 if (media_transport_) {
5618 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5619 &DataChannel::OnChannelReady);
5620 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5621 &DataChannel::OnDataReceived);
5622 SignalMediaTransportChannelClosing_s.connect(
5623 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5624 SignalMediaTransportChannelClosed_s.connect(
5625 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5626 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005627 rtp_data_channel_->SignalReadyToSendData.connect(
5628 webrtc_data_channel, &DataChannel::OnChannelReady);
5629 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5630 &DataChannel::OnDataReceived);
5631 } else {
5632 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5633 &DataChannel::OnChannelReady);
5634 SignalSctpDataReceived.connect(webrtc_data_channel,
5635 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005636 SignalSctpClosingProcedureStartedRemotely.connect(
5637 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5638 SignalSctpClosingProcedureComplete.connect(
5639 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005640 }
5641 return true;
5642}
5643
5644void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005645 RTC_DCHECK_RUN_ON(signaling_thread());
5646 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005647 RTC_LOG(LS_ERROR)
5648 << "DisconnectDataChannel called when rtp_data_channel_ and "
5649 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005650 return;
5651 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005652 if (media_transport_) {
5653 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5654 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5655 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5656 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5657 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005658 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5659 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5660 } else {
5661 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5662 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005663 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5664 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005665 }
5666}
5667
5668void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005669 if (media_transport_) {
5670 // No-op. Media transport does not need to add streams.
5671 return;
5672 }
Steve Anton75737c02017-11-06 10:37:17 -08005673 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005674 RTC_LOG(LS_ERROR)
5675 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005676 return;
5677 }
5678 network_thread()->Invoke<void>(
5679 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5680 sctp_transport_.get(), sid));
5681}
5682
5683void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005684 if (media_transport_) {
5685 media_transport_->CloseChannel(sid);
5686 return;
5687 }
Steve Anton75737c02017-11-06 10:37:17 -08005688 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005689 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005690 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005691 return;
5692 }
5693 network_thread()->Invoke<void>(
5694 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5695 sctp_transport_.get(), sid));
5696}
5697
5698bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005699 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005700 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005701 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005702 sctp_ready_to_send_data_;
5703}
5704
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005705void PeerConnection::OnDataReceived(int channel_id,
5706 DataMessageType type,
5707 const rtc::CopyOnWriteBuffer& buffer) {
5708 cricket::ReceiveDataParams params;
5709 params.sid = channel_id;
5710 params.type = ToCricketDataMessageType(type);
5711 media_transport_invoker_->AsyncInvoke<void>(
5712 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5713 RTC_DCHECK_RUN_ON(signaling_thread());
5714 if (!HandleOpenMessage_s(params, buffer)) {
5715 SignalMediaTransportReceivedData_s(params, buffer);
5716 }
5717 });
5718}
5719
5720void PeerConnection::OnChannelClosing(int channel_id) {
5721 media_transport_invoker_->AsyncInvoke<void>(
5722 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5723 RTC_DCHECK_RUN_ON(signaling_thread());
5724 SignalMediaTransportChannelClosing_s(channel_id);
5725 });
5726}
5727
5728void PeerConnection::OnChannelClosed(int channel_id) {
5729 media_transport_invoker_->AsyncInvoke<void>(
5730 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5731 RTC_DCHECK_RUN_ON(signaling_thread());
5732 SignalMediaTransportChannelClosed_s(channel_id);
5733 });
5734}
5735
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005736absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005737 if (sctp_mid_ && transport_controller_) {
5738 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5739 if (dtls_transport) {
5740 return dtls_transport->transport_name();
5741 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005742 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005743 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005744 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005745}
5746
Qingsi Wang72a43a12018-02-20 16:03:18 -08005747cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5748 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005749 network_thread()->Invoke<void>(
5750 RTC_FROM_HERE,
5751 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5752 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005753 return candidate_states_list;
5754}
5755
Steve Anton5dfde182018-02-06 10:34:40 -08005756std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5757 const {
5758 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005759 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005760 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005761 if (channel) {
5762 transport_names_by_mid[channel->content_name()] =
5763 channel->transport_name();
5764 }
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
Steve Anton5dfde182018-02-06 10:34:40 -08005766 if (rtp_data_channel_) {
5767 transport_names_by_mid[rtp_data_channel_->content_name()] =
5768 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
5770 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005771 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005772 RTC_DCHECK(transport_name);
5773 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005774 }
Steve Anton5dfde182018-02-06 10:34:40 -08005775 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005776}
5777
Steve Anton5dfde182018-02-06 10:34:40 -08005778std::map<std::string, cricket::TransportStats>
5779PeerConnection::GetTransportStatsByNames(
5780 const std::set<std::string>& transport_names) {
5781 if (!network_thread()->IsCurrent()) {
5782 return network_thread()
5783 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5784 RTC_FROM_HERE,
5785 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005786 }
Steve Anton5dfde182018-02-06 10:34:40 -08005787 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5788 for (const std::string& transport_name : transport_names) {
5789 cricket::TransportStats transport_stats;
5790 bool success =
5791 transport_controller_->GetStats(transport_name, &transport_stats);
5792 if (success) {
5793 transport_stats_by_name[transport_name] = std::move(transport_stats);
5794 } else {
5795 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5796 << transport_name;
5797 }
5798 }
5799 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005800}
5801
5802bool PeerConnection::GetLocalCertificate(
5803 const std::string& transport_name,
5804 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005805 if (!certificate) {
5806 return false;
5807 }
5808 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5809 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005810}
5811
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005812std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005813 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005814 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005815}
5816
5817cricket::DataChannelType PeerConnection::data_channel_type() const {
5818 return data_channel_type_;
5819}
5820
5821bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5822 return pending_ice_restarts_.find(content_name) !=
5823 pending_ice_restarts_.end();
5824}
5825
Steve Anton75737c02017-11-06 10:37:17 -08005826bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5827 return transport_controller_->NeedsIceRestart(content_name);
5828}
5829
5830void PeerConnection::OnCertificateReady(
5831 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5832 transport_controller_->SetLocalCertificate(certificate);
5833}
5834
5835void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005836 SetSessionError(SessionError::kTransport,
5837 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005838}
5839
Alex Loiko9289eda2018-11-23 16:18:59 +00005840void PeerConnection::OnTransportControllerConnectionState(
5841 cricket::IceConnectionState state) {
5842 switch (state) {
5843 case cricket::kIceConnectionConnecting:
5844 // If the current state is Connected or Completed, then there were
5845 // writable channels but now there are not, so the next state must
5846 // be Disconnected.
5847 // kIceConnectionConnecting is currently used as the default,
5848 // un-connected state by the TransportController, so its only use is
5849 // detecting disconnections.
5850 if (ice_connection_state_ ==
5851 PeerConnectionInterface::kIceConnectionConnected ||
5852 ice_connection_state_ ==
5853 PeerConnectionInterface::kIceConnectionCompleted) {
5854 SetIceConnectionState(
5855 PeerConnectionInterface::kIceConnectionDisconnected);
5856 }
5857 break;
5858 case cricket::kIceConnectionFailed:
5859 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5860 break;
5861 case cricket::kIceConnectionConnected:
5862 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5863 "all transports are writable.";
5864 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5865 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5866 break;
5867 case cricket::kIceConnectionCompleted:
5868 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5869 "all transports are complete.";
5870 if (ice_connection_state_ !=
5871 PeerConnectionInterface::kIceConnectionConnected) {
5872 // If jumping directly from "checking" to "connected",
5873 // signal "connected" first.
5874 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5875 }
5876 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5877 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5878 ReportTransportStats();
5879 break;
5880 default:
5881 RTC_NOTREACHED();
5882 }
5883}
5884
Steve Anton75737c02017-11-06 10:37:17 -08005885void PeerConnection::OnTransportControllerCandidatesGathered(
5886 const std::string& transport_name,
5887 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005888 int sdp_mline_index;
5889 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005890 RTC_LOG(LS_ERROR)
5891 << "OnTransportControllerCandidatesGathered: content name "
5892 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005893 return;
5894 }
5895
5896 for (cricket::Candidates::const_iterator citer = candidates.begin();
5897 citer != candidates.end(); ++citer) {
5898 // Use transport_name as the candidate media id.
5899 std::unique_ptr<JsepIceCandidate> candidate(
5900 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5901 if (local_description()) {
5902 mutable_local_description()->AddCandidate(candidate.get());
5903 }
5904 OnIceCandidate(std::move(candidate));
5905 }
5906}
5907
5908void PeerConnection::OnTransportControllerCandidatesRemoved(
5909 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005910 // Sanity check.
5911 for (const cricket::Candidate& candidate : candidates) {
5912 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005913 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005914 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005915 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005916 return;
5917 }
5918 }
5919
5920 if (local_description()) {
5921 mutable_local_description()->RemoveCandidates(candidates);
5922 }
5923 OnIceCandidatesRemoved(candidates);
5924}
5925
5926void PeerConnection::OnTransportControllerDtlsHandshakeError(
5927 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005928 RTC_HISTOGRAM_ENUMERATION(
5929 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5930 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005931}
5932
Steve Antoned10bd92017-12-05 10:52:59 -08005933void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005934 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005935 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005936 if (channel && !channel->enabled()) {
5937 channel->Enable(true);
5938 }
Steve Anton75737c02017-11-06 10:37:17 -08005939 }
5940
Steve Anton4171afb2017-11-20 10:20:22 -08005941 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005942 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005943 }
Steve Anton75737c02017-11-06 10:37:17 -08005944}
5945
5946// Returns the media index for a local ice candidate given the content name.
5947bool PeerConnection::GetLocalCandidateMediaIndex(
5948 const std::string& content_name,
5949 int* sdp_mline_index) {
5950 if (!local_description() || !sdp_mline_index) {
5951 return false;
5952 }
5953
5954 bool content_found = false;
5955 const ContentInfos& contents = local_description()->description()->contents();
5956 for (size_t index = 0; index < contents.size(); ++index) {
5957 if (contents[index].name == content_name) {
5958 *sdp_mline_index = static_cast<int>(index);
5959 content_found = true;
5960 break;
5961 }
5962 }
5963 return content_found;
5964}
5965
5966bool PeerConnection::UseCandidatesInSessionDescription(
5967 const SessionDescriptionInterface* remote_desc) {
5968 if (!remote_desc) {
5969 return true;
5970 }
5971 bool ret = true;
5972
5973 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5974 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5975 for (size_t n = 0; n < candidates->count(); ++n) {
5976 const IceCandidateInterface* candidate = candidates->at(n);
5977 bool valid = false;
5978 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5979 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005980 RTC_LOG(LS_INFO)
5981 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005982 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005983 }
5984 continue;
5985 }
5986 ret = UseCandidate(candidate);
5987 if (!ret) {
5988 break;
5989 }
5990 }
5991 }
5992 return ret;
5993}
5994
5995bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5996 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5997 size_t remote_content_size =
5998 remote_description()->description()->contents().size();
5999 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006000 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006001 return false;
6002 }
6003
6004 cricket::ContentInfo content =
6005 remote_description()->description()->contents()[mediacontent_index];
6006 std::vector<cricket::Candidate> candidates;
6007 candidates.push_back(candidate->candidate());
6008 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006009 RTCError error =
6010 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006011 if (error.ok()) {
6012 // Candidates successfully submitted for checking.
6013 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6014 ice_connection_state_ ==
6015 PeerConnectionInterface::kIceConnectionDisconnected) {
6016 // If state is New, then the session has just gotten its first remote ICE
6017 // candidates, so go to Checking.
6018 // If state is Disconnected, the session is re-using old candidates or
6019 // receiving additional ones, so go to Checking.
6020 // If state is Connected, stay Connected.
6021 // TODO(bemasc): If state is Connected, and the new candidates are for a
6022 // newly added transport, then the state actually _should_ move to
6023 // checking. Add a way to distinguish that case.
6024 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6025 }
6026 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006027 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006028 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006029 }
6030 return true;
6031}
6032
6033void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006034 // Destroy video channel first since it may have a pointer to the
6035 // voice channel.
6036 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006037 if (!video_info || video_info->rejected) {
6038 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006039 }
6040
Steve Anton6fec8802017-12-04 10:37:29 -08006041 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6042 if (!audio_info || audio_info->rejected) {
6043 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006044 }
6045
6046 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6047 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006048 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006049 }
6050}
6051
Steve Antondcc3c022017-12-22 16:02:54 -08006052RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6053 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006054 const cricket::ContentGroup* bundle_group = nullptr;
6055 if (configuration_.bundle_policy ==
6056 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006057 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006058 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006059 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6060 "max-bundle configured but session description "
6061 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006062 }
6063 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006064 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006065}
6066
6067RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006068 // Creating the media channels. Transports should already have been created
6069 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006070 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006071 if (voice && !voice->rejected &&
6072 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006073 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006074 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006075 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6076 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006077 }
6078 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6079 }
6080
Steve Antondcc3c022017-12-22 16:02:54 -08006081 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006082 if (video && !video->rejected &&
6083 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006084 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006085 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006086 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6087 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006088 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006089 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006090 }
6091
Steve Antondcc3c022017-12-22 16:02:54 -08006092 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006093 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006094 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006095 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006096 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6097 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006098 }
6099 }
6100
Steve Anton8a006912017-12-04 15:25:56 -08006101 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006102}
6103
Steve Anton4171afb2017-11-20 10:20:22 -08006104// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006105cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006106 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006107 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006108 MediaTransportInterface* media_transport = nullptr;
6109 if (configuration_.use_media_transport) {
6110 media_transport = GetMediaTransport(mid);
6111 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006112
Steve Anton75737c02017-11-06 10:37:17 -08006113 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006114 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006115 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006116 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006117 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006118 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006119 }
Steve Anton75737c02017-11-06 10:37:17 -08006120 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6121 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006122 voice_channel->SignalSentPacket.connect(this,
6123 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006124 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006125
Steve Antoneda6ccd2017-12-04 10:21:55 -08006126 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006127}
6128
Steve Anton4171afb2017-11-20 10:20:22 -08006129// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006130cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006131 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006132 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006133 MediaTransportInterface* media_transport = nullptr;
6134 if (configuration_.use_media_transport) {
6135 media_transport = GetMediaTransport(mid);
6136 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006137
Steve Anton75737c02017-11-06 10:37:17 -08006138 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006139 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006140 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006141 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006142 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006143 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006144 }
Steve Anton75737c02017-11-06 10:37:17 -08006145 video_channel->SignalDtlsSrtpSetupFailure.connect(
6146 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006147 video_channel->SignalSentPacket.connect(this,
6148 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006149 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006150
Steve Antoneda6ccd2017-12-04 10:21:55 -08006151 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006152}
6153
Zhi Huange830e682018-03-30 10:48:35 -07006154bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006155 switch (data_channel_type_) {
6156 case cricket::DCT_MEDIA_TRANSPORT:
6157 if (network_thread()->Invoke<bool>(
6158 RTC_FROM_HERE,
6159 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6160 this, mid))) {
6161 for (const auto& channel : sctp_data_channels_) {
6162 channel->OnTransportChannelCreated();
6163 }
6164 return true;
6165 }
Steve Anton75737c02017-11-06 10:37:17 -08006166 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006167 case cricket::DCT_SCTP:
6168 if (!sctp_factory_) {
6169 RTC_LOG(LS_ERROR)
6170 << "Trying to create SCTP transport, but didn't compile with "
6171 "SCTP support (HAVE_SCTP)";
6172 return false;
6173 }
6174 if (!network_thread()->Invoke<bool>(
6175 RTC_FROM_HERE,
6176 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6177 return false;
6178 }
6179 for (const auto& channel : sctp_data_channels_) {
6180 channel->OnTransportChannelCreated();
6181 }
6182 return true;
6183 case cricket::DCT_RTP:
6184 default:
6185 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6186 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6187 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006188 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006189 if (!rtp_data_channel_) {
6190 return false;
6191 }
6192 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6193 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6194 rtp_data_channel_->SignalSentPacket.connect(
6195 this, &PeerConnection::OnSentPacket_w);
6196 rtp_data_channel_->SetRtpTransport(rtp_transport);
6197 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006198 }
6199
Steve Anton75737c02017-11-06 10:37:17 -08006200 return true;
6201}
6202
6203Call::Stats PeerConnection::GetCallStats() {
6204 if (!worker_thread()->IsCurrent()) {
6205 return worker_thread()->Invoke<Call::Stats>(
6206 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6207 }
6208 if (call_) {
6209 return call_->GetStats();
6210 } else {
6211 return Call::Stats();
6212 }
6213}
6214
Zhi Huange830e682018-03-30 10:48:35 -07006215bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006216 RTC_DCHECK(network_thread()->IsCurrent());
6217 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006218 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006219 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006220 RTC_DCHECK(dtls_transport);
6221 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006222 RTC_DCHECK(sctp_transport_);
6223 sctp_invoker_.reset(new rtc::AsyncInvoker());
6224 sctp_transport_->SignalReadyToSendData.connect(
6225 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6226 sctp_transport_->SignalDataReceived.connect(
6227 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006228 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6229 // another thread. Would be nice if there was a helper class similar to
6230 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6231 // code.
6232 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6233 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6234 sctp_transport_->SignalClosingProcedureComplete.connect(
6235 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006236 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006237 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006238 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006239}
6240
6241void PeerConnection::DestroySctpTransport_n() {
6242 RTC_DCHECK(network_thread()->IsCurrent());
6243 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006244 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006245 sctp_invoker_.reset(nullptr);
6246 sctp_ready_to_send_data_ = false;
6247}
6248
6249void PeerConnection::OnSctpTransportReadyToSendData_n() {
6250 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6251 RTC_DCHECK(network_thread()->IsCurrent());
6252 // Note: Cannot use rtc::Bind here because it will grab a reference to
6253 // PeerConnection and potentially cause PeerConnection to live longer than
6254 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6255 // be destroyed before PeerConnection is destroyed, and at that point all
6256 // pending tasks will be cleared.
6257 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6258 OnSctpTransportReadyToSendData_s(true);
6259 });
6260}
6261
6262void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6263 RTC_DCHECK(signaling_thread()->IsCurrent());
6264 sctp_ready_to_send_data_ = ready;
6265 SignalSctpReadyToSendData(ready);
6266}
6267
6268void PeerConnection::OnSctpTransportDataReceived_n(
6269 const cricket::ReceiveDataParams& params,
6270 const rtc::CopyOnWriteBuffer& payload) {
6271 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6272 RTC_DCHECK(network_thread()->IsCurrent());
6273 // Note: Cannot use rtc::Bind here because it will grab a reference to
6274 // PeerConnection and potentially cause PeerConnection to live longer than
6275 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6276 // be destroyed before PeerConnection is destroyed, and at that point all
6277 // pending tasks will be cleared.
6278 sctp_invoker_->AsyncInvoke<void>(
6279 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6280 OnSctpTransportDataReceived_s(params, payload);
6281 });
6282}
6283
6284void PeerConnection::OnSctpTransportDataReceived_s(
6285 const cricket::ReceiveDataParams& params,
6286 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006287 RTC_DCHECK_RUN_ON(signaling_thread());
6288 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006289 SignalSctpDataReceived(params, payload);
6290 }
6291}
6292
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006293void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006294 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6295 RTC_DCHECK(network_thread()->IsCurrent());
6296 sctp_invoker_->AsyncInvoke<void>(
6297 RTC_FROM_HERE, signaling_thread(),
6298 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006299 &SignalSctpClosingProcedureStartedRemotely, sid));
6300}
6301
6302void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6303 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6304 RTC_DCHECK(network_thread()->IsCurrent());
6305 sctp_invoker_->AsyncInvoke<void>(
6306 RTC_FROM_HERE, signaling_thread(),
6307 rtc::Bind(&sigslot::signal1<int>::operator(),
6308 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006309}
6310
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006311bool PeerConnection::SetupMediaTransportForDataChannels_n(
6312 const std::string& mid) {
6313 media_transport_ = transport_controller_->GetMediaTransport(mid);
6314 if (!media_transport_) {
6315 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6316 return false;
6317 }
6318
6319 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6320 media_transport_->SetDataSink(this);
6321 media_transport_data_mid_ = mid;
6322 transport_controller_->SignalMediaTransportStateChanged.connect(
6323 this, &PeerConnection::OnMediaTransportStateChanged_n);
6324 // Check the initial state right away, in case transport is already writable.
6325 OnMediaTransportStateChanged_n();
6326 return true;
6327}
6328
6329void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6330 if (!media_transport_) {
6331 return;
6332 }
6333 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6334 media_transport_data_mid_.reset();
6335 media_transport_->SetDataSink(nullptr);
6336 media_transport_invoker_ = nullptr;
6337 media_transport_ = nullptr;
6338}
6339
6340void PeerConnection::OnMediaTransportStateChanged_n() {
6341 if (!media_transport_data_mid_ ||
6342 transport_controller_->GetMediaTransportState(
6343 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6344 return;
6345 }
6346 media_transport_invoker_->AsyncInvoke<void>(
6347 RTC_FROM_HERE, signaling_thread(), [this] {
6348 RTC_DCHECK_RUN_ON(signaling_thread());
6349 media_transport_ready_to_send_data_ = true;
6350 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6351 });
6352}
6353
Steve Anton75737c02017-11-06 10:37:17 -08006354// Returns false if bundle is enabled and rtcp_mux is disabled.
6355bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6356 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6357 if (!bundle_enabled)
6358 return true;
6359
6360 const cricket::ContentGroup* bundle_group =
6361 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6362 RTC_DCHECK(bundle_group != NULL);
6363
6364 const cricket::ContentInfos& contents = desc->contents();
6365 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6366 citer != contents.end(); ++citer) {
6367 const cricket::ContentInfo* content = (&*citer);
6368 RTC_DCHECK(content != NULL);
6369 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006370 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006371 if (!HasRtcpMuxEnabled(content))
6372 return false;
6373 }
6374 }
6375 // RTCP-MUX is enabled in all the contents.
6376 return true;
6377}
6378
6379bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006380 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006381}
6382
Steve Anton06817cd2018-12-18 15:55:30 -08006383static RTCError ValidateMids(const cricket::SessionDescription& description) {
6384 std::set<std::string> mids;
6385 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006386 if (content.name.empty()) {
6387 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6388 "A media section is missing a MID attribute.");
6389 }
Steve Anton06817cd2018-12-18 15:55:30 -08006390 if (!mids.insert(content.name).second) {
6391 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6392 "Duplicate a=mid value '" + content.name + "'.");
6393 }
6394 }
6395 return RTCError::OK();
6396}
6397
Steve Anton8a006912017-12-04 15:25:56 -08006398RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006399 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006400 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006401 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006402 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006403 }
6404
6405 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006406 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006407 }
6408
Steve Anton3828c062017-12-06 10:34:51 -08006409 SdpType type = sdesc->GetType();
6410 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6411 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006412 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006413 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006414 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006415 }
6416
Steve Anton06817cd2018-12-18 15:55:30 -08006417 RTCError error = ValidateMids(*sdesc->description());
6418 if (!error.ok()) {
6419 return error;
6420 }
6421
Steve Anton75737c02017-11-06 10:37:17 -08006422 // Verify crypto settings.
6423 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006424 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6425 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006426 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006427 if (!crypto_error.ok()) {
6428 return crypto_error;
6429 }
Steve Anton75737c02017-11-06 10:37:17 -08006430 }
6431
6432 // Verify ice-ufrag and ice-pwd.
6433 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006434 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6435 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006436 }
6437
6438 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006439 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6440 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006441 }
6442
6443 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6444 // m-lines that do not rtcp-mux enabled.
6445
6446 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006447 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006448 // With an answer we want to compare the new answer session description with
6449 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006450 const cricket::SessionDescription* offer_desc =
6451 (source == cricket::CS_LOCAL) ? remote_description()->description()
6452 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006453 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6454 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6455 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006456 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6457 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006458 }
6459 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006460 // The re-offers should respect the order of m= sections in current
6461 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006462 // With a re-offer, either the current local or current remote descriptions
6463 // could be the most up to date, so we would like to check against both of
6464 // them if they exist. It could be the case that one of them has a 0 port
6465 // for a media section, but the other does not. This is important to check
6466 // against in the case that we are recycling an m= section.
6467 const cricket::SessionDescription* current_desc = nullptr;
6468 const cricket::SessionDescription* secondary_current_desc = nullptr;
6469 if (local_description()) {
6470 current_desc = local_description()->description();
6471 if (remote_description()) {
6472 secondary_current_desc = remote_description()->description();
6473 }
6474 } else if (remote_description()) {
6475 current_desc = remote_description()->description();
6476 }
Steve Anton75737c02017-11-06 10:37:17 -08006477 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006478 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6479 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006480 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6481 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006482 }
6483 }
6484
Steve Antonba42e992018-04-09 14:10:01 -07006485 if (IsUnifiedPlan()) {
6486 // Ensure that each audio and video media section has at most one
6487 // "StreamParams". This will return an error if receiving a session
6488 // description from a "Plan B" endpoint which adds multiple tracks of the
6489 // same type. With Unified Plan, there can only be at most one track per
6490 // media section.
6491 for (const ContentInfo& content : sdesc->description()->contents()) {
6492 const MediaContentDescription& desc = *content.description;
6493 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6494 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6495 desc.streams().size() > 1u) {
6496 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6497 "Media section has more than one track specified "
6498 "with a=ssrc lines which is not supported with "
6499 "Unified Plan.");
6500 }
6501 }
6502 }
6503
Steve Anton8a006912017-12-04 15:25:56 -08006504 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006505}
6506
Steve Anton3828c062017-12-06 10:34:51 -08006507bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006508 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006509 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006510 return (state == PeerConnectionInterface::kStable) ||
6511 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006512 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006513 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006514 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6515 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6516 }
6517}
6518
Steve Anton3828c062017-12-06 10:34:51 -08006519bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006520 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006521 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006522 return (state == PeerConnectionInterface::kStable) ||
6523 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006524 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006525 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006526 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6527 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6528 }
6529}
6530
Steve Antonf8470812017-12-04 10:46:21 -08006531const char* PeerConnection::SessionErrorToString(SessionError error) const {
6532 switch (error) {
6533 case SessionError::kNone:
6534 return "ERROR_NONE";
6535 case SessionError::kContent:
6536 return "ERROR_CONTENT";
6537 case SessionError::kTransport:
6538 return "ERROR_TRANSPORT";
6539 }
6540 RTC_NOTREACHED();
6541 return "";
6542}
6543
Steve Anton75737c02017-11-06 10:37:17 -08006544std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006545 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006546 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6547 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006548 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006549}
6550
Steve Anton8e20f172018-03-06 10:55:04 -08006551void PeerConnection::ReportSdpFormatReceived(
6552 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006553 int num_audio_mlines = 0;
6554 int num_video_mlines = 0;
6555 int num_audio_tracks = 0;
6556 int num_video_tracks = 0;
6557 for (const ContentInfo& content : remote_offer.description()->contents()) {
6558 cricket::MediaType media_type = content.media_description()->type();
6559 int num_tracks = std::max(
6560 1, static_cast<int>(content.media_description()->streams().size()));
6561 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6562 num_audio_mlines += 1;
6563 num_audio_tracks += num_tracks;
6564 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6565 num_video_mlines += 1;
6566 num_video_tracks += num_tracks;
6567 }
6568 }
6569 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6570 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6571 format = kSdpFormatReceivedComplexUnifiedPlan;
6572 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6573 format = kSdpFormatReceivedComplexPlanB;
6574 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6575 format = kSdpFormatReceivedSimple;
6576 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006577 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6578 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006579}
6580
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006581void PeerConnection::NoteUsageEvent(UsageEvent event) {
6582 RTC_DCHECK_RUN_ON(signaling_thread());
6583 usage_event_accumulator_ |= static_cast<int>(event);
6584}
6585
6586void PeerConnection::ReportUsagePattern() const {
6587 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006588 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6589 usage_event_accumulator_,
6590 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006591 const int bad_bits =
6592 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6593 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6594 const int good_bits =
6595 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6596 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6597 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6598 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6599 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006600 // If called after close(), we can't report, because observer may have
6601 // been deallocated, and therefore pointer is null. Write to log instead.
6602 if (observer_) {
6603 Observer()->OnInterestingUsage(usage_event_accumulator_);
6604 } else {
6605 RTC_LOG(LS_INFO) << "Interesting usage signature "
6606 << usage_event_accumulator_
6607 << " observed after observer shutdown";
6608 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006609 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006610}
6611
Steve Anton0ffaaa22018-02-23 10:31:30 -08006612void PeerConnection::ReportNegotiatedSdpSemantics(
6613 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006614 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006615 switch (answer.description()->msid_signaling()) {
6616 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006617 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006618 break;
6619 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006620 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006621 break;
6622 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006623 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006624 break;
6625 case cricket::kMsidSignalingMediaSection |
6626 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006627 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006628 break;
6629 default:
6630 RTC_NOTREACHED();
6631 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006632 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6633 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006634}
6635
Steve Anton75737c02017-11-06 10:37:17 -08006636// We need to check the local/remote description for the Transport instead of
6637// the session, because a new Transport added during renegotiation may have
6638// them unset while the session has them set from the previous negotiation.
6639// Not doing so may trigger the auto generation of transport description and
6640// mess up DTLS identity information, ICE credential, etc.
6641bool PeerConnection::ReadyToUseRemoteCandidate(
6642 const IceCandidateInterface* candidate,
6643 const SessionDescriptionInterface* remote_desc,
6644 bool* valid) {
6645 *valid = true;
6646
6647 const SessionDescriptionInterface* current_remote_desc =
6648 remote_desc ? remote_desc : remote_description();
6649
6650 if (!current_remote_desc) {
6651 return false;
6652 }
6653
6654 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6655 size_t remote_content_size =
6656 current_remote_desc->description()->contents().size();
6657 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006658 RTC_LOG(LS_ERROR)
6659 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6660 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006661
6662 *valid = false;
6663 return false;
6664 }
6665
6666 cricket::ContentInfo content =
6667 current_remote_desc->description()->contents()[mediacontent_index];
6668
6669 const std::string transport_name = GetTransportName(content.name);
6670 if (transport_name.empty()) {
6671 return false;
6672 }
Zhi Huange830e682018-03-30 10:48:35 -07006673 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006674}
6675
6676bool PeerConnection::SrtpRequired() const {
6677 return dtls_enabled_ ||
6678 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6679}
6680
6681void PeerConnection::OnTransportControllerGatheringState(
6682 cricket::IceGatheringState state) {
6683 RTC_DCHECK(signaling_thread()->IsCurrent());
6684 if (state == cricket::kIceGatheringGathering) {
6685 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6686 } else if (state == cricket::kIceGatheringComplete) {
6687 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6688 }
6689}
6690
6691void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006692 std::map<std::string, std::set<cricket::MediaType>>
6693 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006694 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006695 if (transceiver->internal()->channel()) {
6696 const std::string& transport_name =
6697 transceiver->internal()->channel()->transport_name();
6698 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006699 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006700 }
Steve Anton75737c02017-11-06 10:37:17 -08006701 }
6702 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006703 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6704 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006705 }
Zhi Huange830e682018-03-30 10:48:35 -07006706
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006707 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006708 if (transport_name) {
6709 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006710 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006711 }
Zhi Huange830e682018-03-30 10:48:35 -07006712
Steve Antonc7b964c2018-02-01 14:39:45 -08006713 for (const auto& entry : media_types_by_transport_name) {
6714 const std::string& transport_name = entry.first;
6715 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006716 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006717 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006718 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006719 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006720 }
6721 }
6722}
6723// Walk through the ConnectionInfos to gather best connection usage
6724// for IPv4 and IPv6.
6725void PeerConnection::ReportBestConnectionState(
6726 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006727 for (const cricket::TransportChannelStats& channel_stats :
6728 stats.channel_stats) {
6729 for (const cricket::ConnectionInfo& connection_info :
6730 channel_stats.connection_infos) {
6731 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006732 continue;
6733 }
6734
Steve Antonc7b964c2018-02-01 14:39:45 -08006735 const cricket::Candidate& local = connection_info.local_candidate;
6736 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006737
6738 // Increment the counter for IceCandidatePairType.
6739 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6740 (local.type() == RELAY_PORT_TYPE &&
6741 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006742 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6743 GetIceCandidatePairCounter(local, remote),
6744 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006745 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006746 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6747 GetIceCandidatePairCounter(local, remote),
6748 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006749 } else {
6750 RTC_CHECK(0);
6751 }
Steve Anton75737c02017-11-06 10:37:17 -08006752
6753 // Increment the counter for IP type.
6754 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006755 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6756 kBestConnections_IPv4,
6757 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006758 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006759 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6760 kBestConnections_IPv6,
6761 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006762 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006763 RTC_CHECK(!local.address().hostname().empty() &&
6764 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006765 }
6766
6767 return;
6768 }
6769 }
6770}
6771
6772void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006773 const cricket::TransportStats& stats,
6774 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006775 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6776 return;
6777 }
6778
6779 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6780 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6781 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6782 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6783 return;
6784 }
6785
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006786 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6787 for (cricket::MediaType media_type : media_types) {
6788 switch (media_type) {
6789 case cricket::MEDIA_TYPE_AUDIO:
6790 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6791 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6792 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6793 break;
6794 case cricket::MEDIA_TYPE_VIDEO:
6795 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6796 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6797 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6798 break;
6799 case cricket::MEDIA_TYPE_DATA:
6800 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6801 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6802 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6803 break;
6804 default:
6805 RTC_NOTREACHED();
6806 continue;
6807 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006808 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006809 }
6810
6811 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6812 for (cricket::MediaType media_type : media_types) {
6813 switch (media_type) {
6814 case cricket::MEDIA_TYPE_AUDIO:
6815 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6816 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6817 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6818 break;
6819 case cricket::MEDIA_TYPE_VIDEO:
6820 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6821 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6822 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6823 break;
6824 case cricket::MEDIA_TYPE_DATA:
6825 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6826 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6827 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6828 break;
6829 default:
6830 RTC_NOTREACHED();
6831 continue;
6832 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006833 }
Steve Anton75737c02017-11-06 10:37:17 -08006834 }
6835}
6836
6837void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6838 RTC_DCHECK(worker_thread()->IsCurrent());
6839 RTC_DCHECK(call_);
6840 call_->OnSentPacket(sent_packet);
6841}
6842
6843const std::string PeerConnection::GetTransportName(
6844 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006845 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006846 if (channel) {
6847 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006848 }
Steve Anton6fec8802017-12-04 10:37:29 -08006849 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006850 RTC_DCHECK(sctp_mid_);
6851 if (content_name == *sctp_mid_) {
6852 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006853 }
6854 }
6855 // Return an empty string if failed to retrieve the transport name.
6856 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006857}
6858
Steve Anton6fec8802017-12-04 10:37:29 -08006859void PeerConnection::DestroyTransceiverChannel(
6860 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6861 transceiver) {
6862 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006863
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006864 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006865 if (channel) {
6866 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006867 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006868 }
6869}
6870
6871void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006872 if (rtp_data_channel_) {
6873 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006874 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006875 rtp_data_channel_ = nullptr;
6876 }
6877
6878 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6879 // grab a reference to this PeerConnection. If this is called from the
6880 // PeerConnection destructor, the RefCountedObject vtable will have already
6881 // been destroyed (since it is a subclass of PeerConnection) and using
6882 // rtc::Bind will cause "Pure virtual function called" error to appear.
6883
6884 if (sctp_transport_) {
6885 OnDataChannelDestroyed();
6886 network_thread()->Invoke<void>(RTC_FROM_HERE,
6887 [this] { DestroySctpTransport_n(); });
6888 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006889
6890 if (media_transport_) {
6891 OnDataChannelDestroyed();
6892 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6893 RTC_DCHECK_RUN_ON(network_thread());
6894 TeardownMediaTransportForDataChannels_n();
6895 });
6896 }
Steve Anton6fec8802017-12-04 10:37:29 -08006897}
6898
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006899void PeerConnection::DestroyChannelInterface(
6900 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006901 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006902 switch (channel->media_type()) {
6903 case cricket::MEDIA_TYPE_AUDIO:
6904 channel_manager()->DestroyVoiceChannel(
6905 static_cast<cricket::VoiceChannel*>(channel));
6906 break;
6907 case cricket::MEDIA_TYPE_VIDEO:
6908 channel_manager()->DestroyVideoChannel(
6909 static_cast<cricket::VideoChannel*>(channel));
6910 break;
6911 case cricket::MEDIA_TYPE_DATA:
6912 channel_manager()->DestroyRtpDataChannel(
6913 static_cast<cricket::RtpDataChannel*>(channel));
6914 break;
6915 default:
6916 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6917 break;
6918 }
Zhi Huange830e682018-03-30 10:48:35 -07006919}
Steve Anton6fec8802017-12-04 10:37:29 -08006920
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006921bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006922 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006923 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006924 cricket::DtlsTransportInternal* dtls_transport,
6925 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006926 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006927 auto base_channel = GetChannel(mid);
6928 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006929 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006930 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006931 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006932 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006933 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006934
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006935 if (configuration_.use_media_transport) {
6936 // Only pass media transport to call object if media transport is used
6937 // for media (and not data channel).
6938 call_->MediaTransportChange(media_transport);
6939 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006940
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006941 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006942}
6943
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006944PeerConnectionObserver* PeerConnection::Observer() const {
6945 // In earlier production code, the pointer was not cleared on close,
6946 // which might have led to undefined behavior if the observer was not
6947 // deallocated, or strange crashes if it was.
6948 // We use CHECK in order to catch such behavior if it exists.
6949 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6950 RTC_CHECK(observer_);
6951 return observer_;
6952}
6953
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006954CryptoOptions PeerConnection::GetCryptoOptions() {
6955 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6956 // after it has been removed.
6957 return configuration_.crypto_options.has_value()
6958 ? *configuration_.crypto_options
6959 : factory_->options().crypto_options;
6960}
6961
Harald Alvestrand89061872018-01-02 14:08:34 +01006962void PeerConnection::ClearStatsCache() {
6963 if (stats_collector_) {
6964 stats_collector_->ClearCachedStatsReport();
6965 }
6966}
6967
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006968void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006969 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6970 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006971}
6972
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006973} // namespace webrtc