blob: 3d0f664a19bb610eba10893a30b7ebd14fa276a5 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
27#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020030#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "logging/rtc_event_log/rtc_event_log.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010033#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080035#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "pc/channel_manager.h"
37#include "pc/dtmf_sender.h"
38#include "pc/media_stream.h"
39#include "pc/media_stream_observer.h"
40#include "pc/remote_audio_source.h"
41#include "pc/rtp_media_utils.h"
42#include "pc/rtp_receiver.h"
43#include "pc/rtp_sender.h"
44#include "pc/sctp_utils.h"
45#include "pc/sdp_utils.h"
46#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010047#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/bind.h"
50#include "rtc_base/checks.h"
51#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010052#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020054#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020055#include "rtc_base/trace_event.h"
56#include "system_wrappers/include/clock.h"
57#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070058#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::ContentInfo;
61using cricket::ContentInfos;
62using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080063using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080064using cricket::RidDescription;
65using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080066using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080067using cricket::SimulcastDescription;
68using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080069using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080070using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080071using cricket::TransportInfo;
72
73using cricket::LOCAL_PORT_TYPE;
74using cricket::STUN_PORT_TYPE;
75using cricket::RELAY_PORT_TYPE;
76using cricket::PRFLX_PORT_TYPE;
77
Steve Antonba818672017-11-06 10:21:57 -080078namespace webrtc {
79
Steve Anton75737c02017-11-06 10:37:17 -080080// Error messages
81const char kBundleWithoutRtcpMux[] =
82 "rtcp-mux must be enabled when BUNDLE "
83 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kInvalidCandidates[] = "Description contains invalid candidates.";
85const char kInvalidSdp[] = "Invalid session description.";
86const char kMlineMismatchInAnswer[] =
87 "The order of m-lines in answer doesn't match order in offer. Rejecting "
88 "answer.";
89const char kMlineMismatchInSubsequentOffer[] =
90 "The order of m-lines in subsequent offer doesn't match order from "
91 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080092const char kSdpWithoutDtlsFingerprint[] =
93 "Called with SDP without DTLS fingerprint.";
94const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
95const char kSdpWithoutIceUfragPwd[] =
96 "Called with SDP without ice-ufrag and ice-pwd.";
97const char kSessionError[] = "Session error code: ";
98const char kSessionErrorDesc[] = "Session error description: ";
99const char kDtlsSrtpSetupFailureRtp[] =
100 "Couldn't set up DTLS-SRTP on RTP channel.";
101const char kDtlsSrtpSetupFailureRtcp[] =
102 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103
Steve Anton75737c02017-11-06 10:37:17 -0800104namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105
Seth Hampson845e8782018-03-02 11:34:10 -0800106static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800107static const char kDefaultAudioSenderId[] = "defaulta0";
108static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700109
zhihuang8f65cdf2016-05-06 18:40:30 -0700110// The length of RTCP CNAMEs.
111static const int kRtcpCnameLength = 16;
112
Steve Antonad182762018-09-05 20:22:40 +0000113enum {
114 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
115 MSG_SET_SESSIONDESCRIPTION_FAILED,
116 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
117 MSG_GETSTATS,
118 MSG_FREE_DATACHANNELS,
119 MSG_REPORT_USAGE_PATTERN,
120};
121
Harald Alvestrand19793842018-06-25 12:03:50 +0200122static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
123
Steve Antonad182762018-09-05 20:22:40 +0000124struct SetSessionDescriptionMsg : public rtc::MessageData {
125 explicit SetSessionDescriptionMsg(
126 webrtc::SetSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
130 RTCError error;
131};
132
133struct CreateSessionDescriptionMsg : public rtc::MessageData {
134 explicit CreateSessionDescriptionMsg(
135 webrtc::CreateSessionDescriptionObserver* observer)
136 : observer(observer) {}
137
138 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
139 RTCError error;
140};
141
142struct GetStatsMsg : public rtc::MessageData {
143 GetStatsMsg(webrtc::StatsObserver* observer,
144 webrtc::MediaStreamTrackInterface* track)
145 : observer(observer), track(track) {}
146 rtc::scoped_refptr<webrtc::StatsObserver> observer;
147 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
148};
149
deadbeefab9b2d12015-10-14 11:33:11 -0700150// Check if we can send |new_stream| on a PeerConnection.
151bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
152 webrtc::MediaStreamInterface* new_stream) {
153 if (!new_stream || !current_streams) {
154 return false;
155 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700156 if (current_streams->find(new_stream->id()) != nullptr) {
157 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100158 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700159 return false;
160 }
161 return true;
162}
163
deadbeef5e97fb52015-10-15 12:49:08 -0700164// If the direction is "recvonly" or "inactive", treat the description
165// as containing no streams.
166// See: https://code.google.com/p/webrtc/issues/detail?id=5054
167std::vector<cricket::StreamParams> GetActiveStreams(
168 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800169 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700170 ? desc->streams()
171 : std::vector<cricket::StreamParams>();
172}
173
deadbeefab9b2d12015-10-14 11:33:11 -0700174bool IsValidOfferToReceiveMedia(int value) {
175 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
176 return (value >= Options::kUndefined) &&
177 (value <= Options::kMaxOfferToReceiveMedia);
178}
179
zhihuang1c378ed2017-08-17 14:10:50 -0700180// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800181void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700182 const std::vector<rtc::scoped_refptr<
183 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700184 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200185 cricket::MediaDescriptionOptions* video_media_description_options,
186 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700187 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700188 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
189 if (audio_media_description_options) {
190 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700191 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700192 }
193 } else {
194 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
195 if (video_media_description_options) {
196 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800197 sender->id(), sender->internal()->stream_ids(), {},
198 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700199 }
200 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700201 }
zhihuang1c378ed2017-08-17 14:10:50 -0700202}
olka3c747662017-08-17 06:50:32 -0700203
zhihuang1c378ed2017-08-17 14:10:50 -0700204// Add options to |session_options| from |rtp_data_channels|.
205void AddRtpDataChannelOptions(
206 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
207 rtp_data_channels,
208 cricket::MediaDescriptionOptions* data_media_description_options) {
209 if (!data_media_description_options) {
210 return;
211 }
deadbeefab9b2d12015-10-14 11:33:11 -0700212 // Check for data channels.
213 for (const auto& kv : rtp_data_channels) {
214 const DataChannel* channel = kv.second;
215 if (channel->state() == DataChannel::kConnecting ||
216 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700217 // Legacy RTP data channels are signaled with the track/stream ID set to
218 // the data channel's label.
219 data_media_description_options->AddRtpDataChannel(channel->label(),
220 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700221 }
222 }
223}
224
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225uint32_t ConvertIceTransportTypeToCandidateFilter(
226 PeerConnectionInterface::IceTransportsType type) {
227 switch (type) {
228 case PeerConnectionInterface::kNone:
229 return cricket::CF_NONE;
230 case PeerConnectionInterface::kRelay:
231 return cricket::CF_RELAY;
232 case PeerConnectionInterface::kNoHost:
233 return (cricket::CF_ALL & ~cricket::CF_HOST);
234 case PeerConnectionInterface::kAll:
235 return cricket::CF_ALL;
236 default:
nissec80e7412017-01-11 05:56:46 -0800237 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238 }
239 return cricket::CF_NONE;
240}
241
deadbeef293e9262017-01-11 12:28:30 -0800242// Helper to set an error and return from a method.
243bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
244 if (error) {
245 error->set_type(type);
246 }
247 return type == webrtc::RTCErrorType::NONE;
248}
249
Steve Anton038834f2017-07-14 15:59:59 -0700250bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700251 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700252 if (error_out) {
253 *error_out = std::move(error);
254 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700255 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700256}
257
Steve Antonba818672017-11-06 10:21:57 -0800258std::string GetSignalingStateString(
259 PeerConnectionInterface::SignalingState state) {
260 switch (state) {
261 case PeerConnectionInterface::kStable:
262 return "kStable";
263 case PeerConnectionInterface::kHaveLocalOffer:
264 return "kHaveLocalOffer";
265 case PeerConnectionInterface::kHaveLocalPrAnswer:
266 return "kHavePrAnswer";
267 case PeerConnectionInterface::kHaveRemoteOffer:
268 return "kHaveRemoteOffer";
269 case PeerConnectionInterface::kHaveRemotePrAnswer:
270 return "kHaveRemotePrAnswer";
271 case PeerConnectionInterface::kClosed:
272 return "kClosed";
273 }
274 RTC_NOTREACHED();
275 return "";
276}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700277
Steve Anton75737c02017-11-06 10:37:17 -0800278IceCandidatePairType GetIceCandidatePairCounter(
279 const cricket::Candidate& local,
280 const cricket::Candidate& remote) {
281 const auto& l = local.type();
282 const auto& r = remote.type();
283 const auto& host = LOCAL_PORT_TYPE;
284 const auto& srflx = STUN_PORT_TYPE;
285 const auto& relay = RELAY_PORT_TYPE;
286 const auto& prflx = PRFLX_PORT_TYPE;
287 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800288 bool local_hostname =
289 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
290 bool remote_hostname = !remote.address().hostname().empty() &&
291 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800292 bool local_private = IPIsPrivate(local.address().ipaddr());
293 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800294 if (local_hostname) {
295 if (remote_hostname) {
296 return kIceCandidatePairHostNameHostName;
297 } else if (remote_private) {
298 return kIceCandidatePairHostNameHostPrivate;
299 } else {
300 return kIceCandidatePairHostNameHostPublic;
301 }
302 } else if (local_private) {
303 if (remote_hostname) {
304 return kIceCandidatePairHostPrivateHostName;
305 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800306 return kIceCandidatePairHostPrivateHostPrivate;
307 } else {
308 return kIceCandidatePairHostPrivateHostPublic;
309 }
310 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800311 if (remote_hostname) {
312 return kIceCandidatePairHostPublicHostName;
313 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800314 return kIceCandidatePairHostPublicHostPrivate;
315 } else {
316 return kIceCandidatePairHostPublicHostPublic;
317 }
318 }
319 }
320 if (l == host && r == srflx)
321 return kIceCandidatePairHostSrflx;
322 if (l == host && r == relay)
323 return kIceCandidatePairHostRelay;
324 if (l == host && r == prflx)
325 return kIceCandidatePairHostPrflx;
326 if (l == srflx && r == host)
327 return kIceCandidatePairSrflxHost;
328 if (l == srflx && r == srflx)
329 return kIceCandidatePairSrflxSrflx;
330 if (l == srflx && r == relay)
331 return kIceCandidatePairSrflxRelay;
332 if (l == srflx && r == prflx)
333 return kIceCandidatePairSrflxPrflx;
334 if (l == relay && r == host)
335 return kIceCandidatePairRelayHost;
336 if (l == relay && r == srflx)
337 return kIceCandidatePairRelaySrflx;
338 if (l == relay && r == relay)
339 return kIceCandidatePairRelayRelay;
340 if (l == relay && r == prflx)
341 return kIceCandidatePairRelayPrflx;
342 if (l == prflx && r == host)
343 return kIceCandidatePairPrflxHost;
344 if (l == prflx && r == srflx)
345 return kIceCandidatePairPrflxSrflx;
346 if (l == prflx && r == relay)
347 return kIceCandidatePairPrflxRelay;
348 return kIceCandidatePairMax;
349}
350
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800351// Logic to decide if an m= section can be recycled. This means that the new
352// m= section is not rejected, but the old local or remote m= section is
353// rejected. |old_content_one| and |old_content_two| refer to the m= section
354// of the old remote and old local descriptions in no particular order.
355// We need to check both the old local and remote because either
356// could be the most current from the latest negotation.
357bool IsMediaSectionBeingRecycled(SdpType type,
358 const ContentInfo& content,
359 const ContentInfo* old_content_one,
360 const ContentInfo* old_content_two) {
361 return type == SdpType::kOffer && !content.rejected &&
362 ((old_content_one && old_content_one->rejected) ||
363 (old_content_two && old_content_two->rejected));
364}
365
Steve Anton75737c02017-11-06 10:37:17 -0800366// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800367// |current_desc|. The number of m= sections in |new_desc| should be no
368// less than |current_desc|. In the case of checking an answer's
369// |new_desc|, the |current_desc| is the last offer that was set as the
370// local or remote. In the case of checking an offer's |new_desc| we
371// check against the local and remote descriptions stored from the last
372// negotiation, because either of these could be the most up to date for
373// possible rejected m sections. These are the |current_desc| and
374// |secondary_current_desc|.
375bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
376 const SessionDescription* secondary_current_desc,
377 const SessionDescription& new_desc,
378 const SdpType type) {
379 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800383 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
384 const cricket::ContentInfo* secondary_content_info = nullptr;
385 if (secondary_current_desc &&
386 i < secondary_current_desc->contents().size()) {
387 secondary_content_info = &secondary_current_desc->contents()[i];
388 }
389 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
390 &current_desc.contents()[i],
391 secondary_content_info)) {
392 // For new offer descriptions, if the media section can be recycled, it's
393 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800394 continue;
395 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800400 new_desc.contents()[i].media_description();
401 const MediaContentDescription* current_desc_mdesc =
402 current_desc.contents()[i].media_description();
403 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800404 return false;
405 }
406 }
407 return true;
408}
409
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800410bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
411 const SessionDescription& desc2) {
412 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800413}
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
416 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200417 // Array of structs needed to map {KeyExchangeProtocolType,
418 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
419 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
420 static constexpr struct {
421 KeyExchangeProtocolType protocol_type;
422 cricket::MediaType media_type;
423 KeyExchangeProtocolMedia protocol_media;
424 } kEnumCounterKeyProtocolMediaMap[] = {
425 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
426 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
427 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
428 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
429 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
430 kEnumCounterKeyProtocolMediaTypeDtlsData},
431 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
432 kEnumCounterKeyProtocolMediaTypeSdesAudio},
433 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
434 kEnumCounterKeyProtocolMediaTypeSdesVideo},
435 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
436 kEnumCounterKeyProtocolMediaTypeSdesData},
437 };
438
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700439 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
440 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100441
Mirko Bonadeiab499822018-09-11 10:43:20 +0200442 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
443 if (i.protocol_type == protocol_type && i.media_type == media_type) {
444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
445 i.protocol_media,
446 kEnumCounterKeyProtocolMediaTypeMax);
447 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100448 }
449}
450
Harald Alvestrand76829d72018-07-18 23:24:36 +0200451void NoteAddIceCandidateResult(int result) {
452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
453 kAddIceCandidateMax);
454}
455
Steve Anton75737c02017-11-06 10:37:17 -0800456// Checks that each non-rejected content has SDES crypto keys or a DTLS
457// fingerprint, unless it's in a BUNDLE group, in which case only the
458// BUNDLE-tag section (first media section/description in the BUNDLE group)
459// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
460// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
461// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700462RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800463 const cricket::ContentGroup* bundle =
464 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800465 for (const cricket::ContentInfo& content_info : desc->contents()) {
466 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800467 continue;
468 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100469 // Note what media is used with each crypto protocol, for all sections.
470 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
471 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700472 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800473 const std::string& mid = content_info.name;
474 if (bundle && bundle->HasContentName(mid) &&
475 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 // This isn't the first media section in the BUNDLE group, so it's not
477 // required to have crypto attributes, since only the crypto attributes
478 // from the first section actually get used.
479 continue;
480 }
481
482 // If the content isn't rejected or bundled into another m= section, crypto
483 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800484 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800485 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800486 if (!media || !tinfo) {
487 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800488 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800489 }
490 if (dtls_enabled) {
491 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100492 RTC_LOG(LS_WARNING)
493 << "Session description must have DTLS fingerprint if "
494 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800495 return RTCError(RTCErrorType::INVALID_PARAMETER,
496 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800497 }
498 } else {
499 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100500 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800501 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800502 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800503 }
504 }
505 }
Steve Anton8a006912017-12-04 15:25:56 -0800506 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800507}
508
509// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
510// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
511// media section/description in the BUNDLE group) needs a ufrag and pwd.
512bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
513 const cricket::ContentGroup* bundle =
514 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800515 for (const cricket::ContentInfo& content_info : desc->contents()) {
516 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800517 continue;
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 const std::string& mid = content_info.name;
520 if (bundle && bundle->HasContentName(mid) &&
521 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 // This isn't the first media section in the BUNDLE group, so it's not
523 // required to have ufrag/password, since only the ufrag/password from
524 // the first section actually get used.
525 continue;
526 }
527
528 // If the content isn't rejected or bundled into another m= section,
529 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800530 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800531 if (!tinfo) {
532 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100533 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800534 return false;
535 }
536 if (tinfo->description.ice_ufrag.empty() ||
537 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 }
542 return true;
543}
544
Steve Anton75737c02017-11-06 10:37:17 -0800545// Get the SCTP port out of a SessionDescription.
546// Return -1 if not found.
547int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 const cricket::DataContentDescription* data_desc =
549 GetFirstDataContentDescription(session_description);
550 RTC_DCHECK(data_desc);
551 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800552 return -1;
553 }
Steve Anton75737c02017-11-06 10:37:17 -0800554 std::string value;
555 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
556 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800557 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800558 if (!codec.Matches(match_pattern)) {
559 continue;
560 }
561 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
562 return rtc::FromString<int>(value);
563 }
564 }
565 return -1;
566}
567
Steve Anton75737c02017-11-06 10:37:17 -0800568// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
569bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
570 const SessionDescriptionInterface* new_desc,
571 const std::string& content_name) {
572 if (!old_desc) {
573 return false;
574 }
575 const SessionDescription* new_sd = new_desc->description();
576 const SessionDescription* old_sd = old_desc->description();
577 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
578 if (!cinfo || cinfo->rejected) {
579 return false;
580 }
581 // If the content isn't rejected, check if ufrag and password has changed.
582 const cricket::TransportDescription* new_transport_desc =
583 new_sd->GetTransportDescriptionByName(content_name);
584 const cricket::TransportDescription* old_transport_desc =
585 old_sd->GetTransportDescriptionByName(content_name);
586 if (!new_transport_desc || !old_transport_desc) {
587 // No transport description exists. This is not an ICE restart.
588 return false;
589 }
590 if (cricket::IceCredentialsChanged(
591 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
592 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100593 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
594 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800595 return true;
596 }
597 return false;
598}
599
Steve Anton80dd7b52018-02-16 17:08:42 -0800600// Generates a string error message for SetLocalDescription/SetRemoteDescription
601// from an RTCError.
602std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
603 SdpType type,
604 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200605 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800606 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
607 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200608 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800609}
610
Seth Hampson5b4f0752018-04-02 16:31:36 -0700611std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
612 std::string output = "streams=[";
613 const char* separator = "";
614 for (const auto& stream_id : stream_ids) {
615 output.append(separator).append(stream_id);
616 separator = ", ";
617 }
618 output.append("]");
619 return output;
620}
621
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200622absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700623 int rtc_configuration_parameter) {
624 if (rtc_configuration_parameter ==
625 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200626 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700627 }
628 return rtc_configuration_parameter;
629}
630
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800631cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
632 switch (type) {
633 case DataMessageType::kText:
634 return cricket::DMT_TEXT;
635 case DataMessageType::kBinary:
636 return cricket::DMT_BINARY;
637 case DataMessageType::kControl:
638 return cricket::DMT_CONTROL;
639 default:
640 return cricket::DMT_NONE;
641 }
642 return cricket::DMT_NONE;
643}
644
645DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
646 switch (type) {
647 case cricket::DMT_TEXT:
648 return DataMessageType::kText;
649 case cricket::DMT_BINARY:
650 return DataMessageType::kBinary;
651 case cricket::DMT_CONTROL:
652 return DataMessageType::kControl;
653 case cricket::DMT_NONE:
654 default:
655 RTC_NOTREACHED();
656 }
657 return DataMessageType::kControl;
658}
659
Steve Anton75737c02017-11-06 10:37:17 -0800660} // namespace
661
Henrik Boström31638672017-11-23 17:48:32 +0100662// Upon completion, posts a task to execute the callback of the
663// SetSessionDescriptionObserver asynchronously on the same thread. At this
664// point, the state of the peer connection might no longer reflect the effects
665// of the SetRemoteDescription operation, as the peer connection could have been
666// modified during the post.
667// TODO(hbos): Remove this class once we remove the version of
668// PeerConnectionInterface::SetRemoteDescription() that takes a
669// SetSessionDescriptionObserver as an argument.
670class PeerConnection::SetRemoteDescriptionObserverAdapter
671 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
672 public:
673 SetRemoteDescriptionObserverAdapter(
674 rtc::scoped_refptr<PeerConnection> pc,
675 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
676 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
677
678 // SetRemoteDescriptionObserverInterface implementation.
679 void OnSetRemoteDescriptionComplete(RTCError error) override {
680 if (error.ok())
681 pc_->PostSetSessionDescriptionSuccess(wrapper_);
682 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100683 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100684 }
685
686 private:
687 rtc::scoped_refptr<PeerConnection> pc_;
688 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
689};
690
deadbeef293e9262017-01-11 12:28:30 -0800691bool PeerConnectionInterface::RTCConfiguration::operator==(
692 const PeerConnectionInterface::RTCConfiguration& o) const {
693 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700694 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800695 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000696 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800698 BundlePolicy bundle_policy;
699 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
701 int ice_candidate_pool_size;
702 bool disable_ipv6;
703 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700704 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100705 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700706 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200707 absl::optional<int> screencast_min_bitrate;
708 absl::optional<bool> combined_audio_video_bwe;
709 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800710 TcpCandidatePolicy tcp_candidate_policy;
711 CandidateNetworkPolicy candidate_network_policy;
712 int audio_jitter_buffer_max_packets;
713 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100714 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100715 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800716 int ice_connection_receiving_timeout;
717 int ice_backup_candidate_pair_ping_interval;
718 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800719 bool prioritize_most_likely_ice_candidate_pairs;
720 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800721 bool prune_turn_ports;
722 bool presume_writable_when_fully_relayed;
723 bool enable_ice_renomination;
724 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200725 absl::optional<int> ice_check_interval_strong_connectivity;
726 absl::optional<int> ice_check_interval_weak_connectivity;
727 absl::optional<int> ice_check_min_interval;
728 absl::optional<int> ice_unwritable_timeout;
729 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800730 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200731 absl::optional<int> stun_candidate_keepalive_interval;
732 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200733 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800734 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700736 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700737 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700738 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700739 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100740 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800741 };
742 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
743 "Did you add something to RTCConfiguration and forget to "
744 "update operator==?");
745 return type == o.type && servers == o.servers &&
746 bundle_policy == o.bundle_policy &&
747 rtcp_mux_policy == o.rtcp_mux_policy &&
748 tcp_candidate_policy == o.tcp_candidate_policy &&
749 candidate_network_policy == o.candidate_network_policy &&
750 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
751 audio_jitter_buffer_fast_accelerate ==
752 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100753 audio_jitter_buffer_min_delay_ms ==
754 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100755 audio_jitter_buffer_enable_rtx_handling ==
756 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800757 ice_connection_receiving_timeout ==
758 o.ice_connection_receiving_timeout &&
759 ice_backup_candidate_pair_ping_interval ==
760 o.ice_backup_candidate_pair_ping_interval &&
761 continual_gathering_policy == o.continual_gathering_policy &&
762 certificates == o.certificates &&
763 prioritize_most_likely_ice_candidate_pairs ==
764 o.prioritize_most_likely_ice_candidate_pairs &&
765 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800766 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700767 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100768 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800769 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800770 screencast_min_bitrate == o.screencast_min_bitrate &&
771 combined_audio_video_bwe == o.combined_audio_video_bwe &&
772 enable_dtls_srtp == o.enable_dtls_srtp &&
773 ice_candidate_pool_size == o.ice_candidate_pool_size &&
774 prune_turn_ports == o.prune_turn_ports &&
775 presume_writable_when_fully_relayed ==
776 o.presume_writable_when_fully_relayed &&
777 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800778 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800779 ice_check_interval_strong_connectivity ==
780 o.ice_check_interval_strong_connectivity &&
781 ice_check_interval_weak_connectivity ==
782 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700783 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700784 ice_unwritable_timeout == o.ice_unwritable_timeout &&
785 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800786 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800787 stun_candidate_keepalive_interval ==
788 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200789 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800790 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800791 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700792 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700793 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700794 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700795 use_media_transport_for_data_channels ==
796 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100797 crypto_options == o.crypto_options &&
798 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800799}
800
801bool PeerConnectionInterface::RTCConfiguration::operator!=(
802 const PeerConnectionInterface::RTCConfiguration& o) const {
803 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800804}
805
zhihuang8f65cdf2016-05-06 18:40:30 -0700806// Generate a RTCP CNAME when a PeerConnection is created.
807std::string GenerateRtcpCname() {
808 std::string cname;
809 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100810 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800811 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700812 }
813 return cname;
814}
815
zhihuang1c378ed2017-08-17 14:10:50 -0700816bool ValidateOfferAnswerOptions(
817 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
818 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
819 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700820}
821
zhihuang1c378ed2017-08-17 14:10:50 -0700822// From |rtc_options|, fill parts of |session_options| shared by all generated
823// m= sections (in other words, nothing that involves a map/array).
824void ExtractSharedMediaSessionOptions(
825 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
826 cricket::MediaSessionOptions* session_options) {
827 session_options->vad_enabled = rtc_options.voice_activity_detection;
828 session_options->bundle_enabled = rtc_options.use_rtp_mux;
829}
zhihuanga77e6bb2017-08-14 18:17:48 -0700830
zhihuang38ede132017-06-15 12:52:32 -0700831PeerConnection::PeerConnection(PeerConnectionFactory* factory,
832 std::unique_ptr<RtcEventLog> event_log,
833 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700835 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700836 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700837 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700838 remote_streams_(StreamCollection::Create()),
839 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840
841PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100842 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800843 RTC_DCHECK_RUN_ON(signaling_thread());
844
Steve Anton8af21862017-12-15 11:20:13 -0800845 // Need to stop transceivers before destroying the stats collector because
846 // AudioRtpSender has a reference to the StatsCollector it will update when
847 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100848 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800849 transceiver->Stop();
850 }
Steve Anton4171afb2017-11-20 10:20:22 -0800851
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700852 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800853 if (stats_collector_) {
854 stats_collector_->WaitForPendingRequest();
855 stats_collector_ = nullptr;
856 }
Steve Anton75737c02017-11-06 10:37:17 -0800857
Steve Anton8af21862017-12-15 11:20:13 -0800858 // Don't destroy BaseChannels until after stats has been cleaned up so that
859 // the last stats request can still read from the channels.
860 DestroyAllChannels();
861
Mirko Bonadei675513b2017-11-09 11:09:25 +0100862 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800863
864 webrtc_session_desc_factory_.reset();
865 sctp_invoker_.reset();
866 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800867 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800868 transport_controller_.reset();
869
deadbeef91dd5672016-05-18 16:55:30 -0700870 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700871 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700872 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700873 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700874 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700875 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800876 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700877 event_log_.reset();
878 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879}
880
Steve Anton8af21862017-12-15 11:20:13 -0800881void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800882 // Destroy video channels first since they may have a pointer to a voice
883 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100884 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800885 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800886 DestroyTransceiverChannel(transceiver);
887 }
888 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100889 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800890 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800891 DestroyTransceiverChannel(transceiver);
892 }
893 }
894 DestroyDataChannel();
895}
896
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000898 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700899 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100900 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +0100901 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700902
903 RTCError config_error = ValidateConfiguration(configuration);
904 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100905 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700906 return false;
907 }
908
Benjamin Wrightcab58882018-05-02 15:12:47 -0700909 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100910 RTC_LOG(LS_ERROR)
911 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100912 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800913 return false;
914 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200915
Benjamin Wrightcab58882018-05-02 15:12:47 -0700916 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800917 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100918 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100919 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800920 return false;
921 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700922
Benjamin Wrightcab58882018-05-02 15:12:47 -0700923 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700924 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700925 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700926 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800927
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200928 cricket::ServerAddresses stun_servers;
929 std::vector<cricket::RelayServerConfig> turn_servers;
930
931 RTCErrorType parse_error =
932 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
933 if (parse_error != RTCErrorType::NONE) {
934 return false;
935 }
936
deadbeef91dd5672016-05-18 16:55:30 -0700937 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700938 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700939 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200940 RTC_FROM_HERE,
941 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
942 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 return false;
944 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200945 // If initialization was successful, note if STUN or TURN servers
946 // were supplied.
947 if (!stun_servers.empty()) {
948 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
949 }
950 if (!turn_servers.empty()) {
951 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
952 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700954 // Send information about IPv4/IPv6 status.
955 PeerConnectionAddressFamilyCounter address_family;
956 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
957 address_family = kPeerConnection_IPv6;
958 } else {
959 address_family = kPeerConnection_IPv4;
960 }
961 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
962 kPeerConnectionAddressFamilyCounter_Max);
963
Zhi Huange830e682018-03-30 10:48:35 -0700964 const PeerConnectionFactoryInterface::Options& options = factory_->options();
965
Steve Anton75737c02017-11-06 10:37:17 -0800966 // RFC 3264: The numeric value of the session id and version in the
967 // o line MUST be representable with a "64 bit signed integer".
968 // Due to this constraint session id |session_id_| is max limited to
969 // LLONG_MAX.
970 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700971 JsepTransportController::Config config;
972 config.redetermine_role_on_ice_restart =
973 configuration.redetermine_role_on_ice_restart;
974 config.ssl_max_version = factory_->options().ssl_max_version;
975 config.disable_encryption = options.disable_encryption;
976 config.bundle_policy = configuration.bundle_policy;
977 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700978 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
979 // stub.
980 config.crypto_options = configuration.crypto_options.has_value()
981 ? *configuration.crypto_options
982 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700983 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700984 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700985#if defined(ENABLE_EXTERNAL_AUTH)
986 config.enable_external_auth = true;
987#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700988 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700989
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700990 if (configuration.use_media_transport ||
991 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700992 if (!factory_->media_transport_factory()) {
993 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700994 << "PeerConnecton is initialized with use_media_transport = true or "
995 << "use_media_transport_for_data_channels = true "
996 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700997 return false;
998 }
999
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001000 config.use_media_transport_for_media = configuration.use_media_transport;
1001 config.use_media_transport_for_data_channels =
1002 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001003 config.media_transport_factory = factory_->media_transport_factory();
1004 }
1005
Zhi Huange830e682018-03-30 10:48:35 -07001006 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001007 signaling_thread(), network_thread(), port_allocator_.get(),
1008 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001009 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001010 this, &PeerConnection::OnTransportControllerConnectionState);
1011 transport_controller_->SignalStandardizedIceConnectionState.connect(
1012 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001013 transport_controller_->SignalConnectionState.connect(
1014 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001015 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001016 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001017 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001018 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001019 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001020 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1021 transport_controller_->SignalDtlsHandshakeError.connect(
1022 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1023
1024 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001025
deadbeefab9b2d12015-10-14 11:33:11 -07001026 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001027 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028
Steve Antonba818672017-11-06 10:21:57 -08001029 configuration_ = configuration;
1030
Steve Anton75737c02017-11-06 10:37:17 -08001031 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1032 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1033 if (!configuration.certificates.empty()) {
1034 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1035 // just picking the first one. The decision should be made based on the DTLS
1036 // handshake. The DTLS negotiations need to know about all certificates.
1037 certificate = configuration.certificates[0];
1038 }
1039
Steve Antond25da372017-11-06 14:50:29 -08001040 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001041
1042 if (options.disable_encryption) {
1043 dtls_enabled_ = false;
1044 } else {
1045 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001046 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001047 // |configuration| can override the default |dtls_enabled_| value.
1048 if (configuration.enable_dtls_srtp) {
1049 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1050 }
1051 }
1052
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001053 if (configuration.use_media_transport_for_data_channels) {
1054 if (configuration.enable_rtp_data_channel) {
1055 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1056 "use_media_transport_for_data_channels are "
1057 "incompatible and cannot both be set to true";
1058 return false;
1059 }
1060 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1061 } else if (configuration.enable_rtp_data_channel) {
1062 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1063 // set. It takes precendence over the disable_sctp_data_channels
1064 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001065 data_channel_type_ = cricket::DCT_RTP;
1066 } else {
1067 // DTLS has to be enabled to use SCTP.
1068 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1069 data_channel_type_ = cricket::DCT_SCTP;
1070 }
1071 }
1072
1073 video_options_.screencast_min_bitrate_kbps =
1074 configuration.screencast_min_bitrate;
1075 audio_options_.combined_audio_video_bwe =
1076 configuration.combined_audio_video_bwe;
1077
1078 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001079 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001080
1081 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001082 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001083
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001084 audio_options_.audio_jitter_buffer_min_delay_ms =
1085 configuration.audio_jitter_buffer_min_delay_ms;
1086
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001087 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1088 configuration.audio_jitter_buffer_enable_rtx_handling;
1089
Steve Anton75737c02017-11-06 10:37:17 -08001090 // Whether the certificate generator/certificate is null or not determines
1091 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1092 // the right instructions by clearing the variables if needed.
1093 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001094 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001095 certificate = nullptr;
1096 } else if (certificate) {
1097 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001098 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001099 }
1100
1101 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1102 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001103 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001104 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1105 this, &PeerConnection::OnCertificateReady);
1106
1107 if (options.disable_encryption) {
1108 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1109 }
1110
1111 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001112 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001113 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001114
Steve Anton4171afb2017-11-20 10:20:22 -08001115 // Add default audio/video transceivers for Plan B SDP.
1116 if (!IsUnifiedPlan()) {
1117 transceivers_.push_back(
1118 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1119 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1120 transceivers_.push_back(
1121 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1122 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1123 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001124 int delay_ms =
1125 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001126 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1127 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001128 return true;
1129}
1130
Steve Anton038834f2017-07-14 15:59:59 -07001131RTCError PeerConnection::ValidateConfiguration(
1132 const RTCConfiguration& config) const {
1133 if (config.ice_regather_interval_range &&
1134 config.continual_gathering_policy == GATHER_ONCE) {
1135 return RTCError(RTCErrorType::INVALID_PARAMETER,
1136 "ice_regather_interval_range specified but continual "
1137 "gathering policy is GATHER_ONCE");
1138 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001139 auto result =
1140 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1141 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001142}
1143
Yves Gerey665174f2018-06-19 15:03:05 +02001144rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001145 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1146 "Plan SdpSemantics. Please use GetSenders "
1147 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001148 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001149}
1150
Yves Gerey665174f2018-06-19 15:03:05 +02001151rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001152 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1153 "Plan SdpSemantics. Please use GetReceivers "
1154 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001155 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156}
1157
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001158bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001159 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001160 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1161 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001162 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 if (IsClosed()) {
1164 return false;
1165 }
deadbeefab9b2d12015-10-14 11:33:11 -07001166 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 return false;
1168 }
deadbeefab9b2d12015-10-14 11:33:11 -07001169
1170 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001171 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1172 observer->SignalAudioTrackAdded.connect(this,
1173 &PeerConnection::OnAudioTrackAdded);
1174 observer->SignalAudioTrackRemoved.connect(
1175 this, &PeerConnection::OnAudioTrackRemoved);
1176 observer->SignalVideoTrackAdded.connect(this,
1177 &PeerConnection::OnVideoTrackAdded);
1178 observer->SignalVideoTrackRemoved.connect(
1179 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001180 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001181
deadbeefab9b2d12015-10-14 11:33:11 -07001182 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001183 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001184 }
1185 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001186 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001187 }
1188
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001189 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001190 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 return true;
1192}
1193
1194void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001195 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001196 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1197 "Plan SdpSemantics. Please use RemoveTrack "
1198 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001199 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001200 if (!IsClosed()) {
1201 for (const auto& track : local_stream->GetAudioTracks()) {
1202 RemoveAudioTrack(track.get(), local_stream);
1203 }
1204 for (const auto& track : local_stream->GetVideoTracks()) {
1205 RemoveVideoTrack(track.get(), local_stream);
1206 }
deadbeefab9b2d12015-10-14 11:33:11 -07001207 }
deadbeefab9b2d12015-10-14 11:33:11 -07001208 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001209 stream_observers_.erase(
1210 std::remove_if(
1211 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001212 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001213 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001214 }),
1215 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001216
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 if (IsClosed()) {
1218 return;
1219 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001220 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221}
1222
Steve Anton2d6c76a2018-01-05 17:10:52 -08001223RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001224 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001225 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001226 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001227 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001228 if (!track) {
1229 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1230 }
1231 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1232 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1233 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1234 "Track has invalid kind: " + track->kind());
1235 }
Steve Antonf9381f02017-12-14 10:23:57 -08001236 if (IsClosed()) {
1237 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1238 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001239 }
Steve Anton4171afb2017-11-20 10:20:22 -08001240 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001241 LOG_AND_RETURN_ERROR(
1242 RTCErrorType::INVALID_PARAMETER,
1243 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001244 }
Steve Antonf9381f02017-12-14 10:23:57 -08001245 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001246 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1247 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001248 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001249 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001250 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001251 }
1252 return sender_or_error;
1253}
deadbeefe1f9d832016-01-14 15:35:42 -08001254
Steve Antonf9381f02017-12-14 10:23:57 -08001255RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1256PeerConnection::AddTrackPlanB(
1257 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001258 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001259 if (stream_ids.size() > 1u) {
1260 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1261 "AddTrack with more than one stream is not "
1262 "supported with Plan B semantics.");
1263 }
1264 std::vector<std::string> adjusted_stream_ids = stream_ids;
1265 if (adjusted_stream_ids.empty()) {
1266 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1267 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001268 cricket::MediaType media_type =
1269 (track->kind() == MediaStreamTrackInterface::kAudioKind
1270 ? cricket::MEDIA_TYPE_AUDIO
1271 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001272 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001273 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001274 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001275 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001276 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001277 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001278 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001279 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001280 if (sender_info) {
1281 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001282 }
Steve Antonf9381f02017-12-14 10:23:57 -08001283 } else {
1284 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001285 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001286 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001287 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001288 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001289 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001290 if (sender_info) {
1291 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001292 }
deadbeefe1f9d832016-01-14 15:35:42 -08001293 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001294 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001295}
deadbeefe1f9d832016-01-14 15:35:42 -08001296
Steve Antonf9381f02017-12-14 10:23:57 -08001297RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1298PeerConnection::AddTrackUnifiedPlan(
1299 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001300 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001301 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1302 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001303 RTC_LOG(LS_INFO) << "Reusing an existing "
1304 << cricket::MediaTypeToString(transceiver->media_type())
1305 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001306 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001307 transceiver->internal()->set_direction(
1308 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001309 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001310 transceiver->internal()->set_direction(
1311 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001312 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001313 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001314 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001315 } else {
1316 cricket::MediaType media_type =
1317 (track->kind() == MediaStreamTrackInterface::kAudioKind
1318 ? cricket::MEDIA_TYPE_AUDIO
1319 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001320 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1321 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001322 std::string sender_id = track->id();
1323 // Avoid creating a sender with an existing ID by generating a random ID.
1324 // This can happen if this is the second time AddTrack has created a sender
1325 // for this track.
1326 if (FindSenderById(sender_id)) {
1327 sender_id = rtc::CreateRandomUuid();
1328 }
Florent Castelli892acf02018-10-01 22:47:20 +02001329 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001330 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1331 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001332 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001333 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001334 }
Steve Antonf9381f02017-12-14 10:23:57 -08001335 return transceiver->sender();
1336}
1337
1338rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1339PeerConnection::FindFirstTransceiverForAddedTrack(
1340 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1341 RTC_DCHECK(track);
1342 for (auto transceiver : transceivers_) {
1343 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001344 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001345 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001346 !transceiver->internal()->has_ever_been_used_to_send() &&
1347 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001348 return transceiver;
1349 }
1350 }
1351 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001352}
1353
1354bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1355 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001356 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001357}
1358
Steve Anton24db5732018-07-23 10:27:33 -07001359RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001360 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001361 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001362 if (!sender) {
1363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1364 }
deadbeefe1f9d832016-01-14 15:35:42 -08001365 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001366 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1367 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001368 }
Steve Antonf9381f02017-12-14 10:23:57 -08001369 if (IsUnifiedPlan()) {
1370 auto transceiver = FindTransceiverBySender(sender);
1371 if (!transceiver || !sender->track()) {
1372 return RTCError::OK();
1373 }
1374 sender->SetTrack(nullptr);
1375 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001376 transceiver->internal()->set_direction(
1377 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001378 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001379 transceiver->internal()->set_direction(
1380 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001381 }
Steve Anton4171afb2017-11-20 10:20:22 -08001382 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001383 bool removed;
1384 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1385 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1386 } else {
1387 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1388 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1389 }
1390 if (!removed) {
1391 LOG_AND_RETURN_ERROR(
1392 RTCErrorType::INVALID_PARAMETER,
1393 "Couldn't find sender " + sender->id() + " to remove.");
1394 }
Steve Anton4171afb2017-11-20 10:20:22 -08001395 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001396 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001397 return RTCError::OK();
1398}
1399
1400rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1401PeerConnection::FindTransceiverBySender(
1402 rtc::scoped_refptr<RtpSenderInterface> sender) {
1403 for (auto transceiver : transceivers_) {
1404 if (transceiver->sender() == sender) {
1405 return transceiver;
1406 }
1407 }
1408 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001409}
1410
Steve Anton9158ef62017-11-27 13:01:52 -08001411RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1412PeerConnection::AddTransceiver(
1413 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1414 return AddTransceiver(track, RtpTransceiverInit());
1415}
1416
1417RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1418PeerConnection::AddTransceiver(
1419 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1420 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001421 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001422 RTC_CHECK(IsUnifiedPlan())
1423 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001424 if (!track) {
1425 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1426 }
1427 cricket::MediaType media_type;
1428 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1429 media_type = cricket::MEDIA_TYPE_AUDIO;
1430 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1431 media_type = cricket::MEDIA_TYPE_VIDEO;
1432 } else {
1433 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1434 "Track kind is not audio or video");
1435 }
1436 return AddTransceiver(media_type, track, init);
1437}
1438
1439RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1440PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1441 return AddTransceiver(media_type, RtpTransceiverInit());
1442}
1443
1444RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1445PeerConnection::AddTransceiver(cricket::MediaType media_type,
1446 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001447 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001448 RTC_CHECK(IsUnifiedPlan())
1449 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001450 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1451 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1452 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1453 "media type is not audio or video");
1454 }
1455 return AddTransceiver(media_type, nullptr, init);
1456}
1457
1458RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1459PeerConnection::AddTransceiver(
1460 cricket::MediaType media_type,
1461 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001462 const RtpTransceiverInit& init,
1463 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001464 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1465 media_type == cricket::MEDIA_TYPE_VIDEO));
1466 if (track) {
1467 RTC_DCHECK_EQ(media_type,
1468 (track->kind() == MediaStreamTrackInterface::kAudioKind
1469 ? cricket::MEDIA_TYPE_AUDIO
1470 : cricket::MEDIA_TYPE_VIDEO));
1471 }
1472
Amit Hilbuchaa584152019-02-06 17:09:52 -08001473 size_t num_rids = absl::c_count_if(init.send_encodings,
1474 [](const RtpEncodingParameters& encoding) {
1475 return !encoding.rid.empty();
1476 });
1477 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001478 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001479 RTCErrorType::INVALID_PARAMETER,
1480 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001481 }
1482
Amit Hilbuchaa584152019-02-06 17:09:52 -08001483 if (absl::c_any_of(init.send_encodings,
1484 [](const RtpEncodingParameters& encoding) {
1485 return encoding.ssrc.has_value();
1486 })) {
1487 LOG_AND_RETURN_ERROR(
1488 RTCErrorType::UNSUPPORTED_PARAMETER,
1489 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001490 }
1491
1492 RtpParameters parameters;
1493 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001494
1495 // Encodings are dropped from the tail if too many are provided.
1496 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1497 parameters.encodings.erase(
1498 parameters.encodings.begin() + kMaxSimulcastStreams,
1499 parameters.encodings.end());
1500 }
1501
1502 // Single RID should be removed.
1503 if (parameters.encodings.size() == 1 &&
1504 !parameters.encodings[0].rid.empty()) {
1505 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1506 parameters.encodings[0].rid.clear();
1507 }
1508
1509 // If RIDs were not provided, they are generated for simulcast scenario.
1510 if (parameters.encodings.size() > 1 && num_rids == 0) {
1511 rtc::UniqueStringGenerator rid_generator;
1512 for (RtpEncodingParameters& encoding : parameters.encodings) {
1513 encoding.rid = rid_generator();
1514 }
1515 }
1516
Florent Castelli892acf02018-10-01 22:47:20 +02001517 if (UnimplementedRtpParameterHasValue(parameters)) {
1518 LOG_AND_RETURN_ERROR(
1519 RTCErrorType::UNSUPPORTED_PARAMETER,
1520 "Attempted to set an unimplemented parameter of RtpParameters.");
1521 }
Steve Anton9158ef62017-11-27 13:01:52 -08001522
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001523 auto result = cricket::CheckRtpParametersValues(parameters);
1524 if (!result.ok()) {
1525 LOG_AND_RETURN_ERROR(result.type(), result.message());
1526 }
1527
Steve Anton3d954a62018-04-02 11:27:23 -07001528 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1529 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001530 // Set the sender ID equal to the track ID if the track is specified unless
1531 // that sender ID is already in use.
1532 std::string sender_id =
1533 (track && !FindSenderById(track->id()) ? track->id()
1534 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001535 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001536 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001537 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1538 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1539 transceiver->internal()->set_direction(init.direction);
1540
Steve Anton22da89f2018-01-25 13:58:07 -08001541 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001542 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001543 }
Steve Antonf9381f02017-12-14 10:23:57 -08001544
1545 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1546}
1547
Steve Anton02ee47c2018-01-10 16:26:06 -08001548rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1549PeerConnection::CreateSender(
1550 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001551 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001552 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001553 const std::vector<std::string>& stream_ids,
1554 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001555 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001556 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1557 RTC_DCHECK(!track ||
1558 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1559 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1560 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001561 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001562 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001563 } else {
1564 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1565 RTC_DCHECK(!track ||
1566 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1567 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001568 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001569 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001570 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001571 bool set_track_succeeded = sender->SetTrack(track);
1572 RTC_DCHECK(set_track_succeeded);
1573 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001574 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001575 return sender;
1576}
1577
1578rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1579PeerConnection::CreateReceiver(cricket::MediaType media_type,
1580 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001581 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1582 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001583 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001584 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001585 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1586 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001587 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001588 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001589 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001590 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001591 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1592 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001593 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001594 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001595 return receiver;
1596}
1597
1598rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1599PeerConnection::CreateAndAddTransceiver(
1600 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1601 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1602 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001603 // Ensure that the new sender does not have an ID that is already in use by
1604 // another sender.
1605 // Allow receiver IDs to conflict since those come from remote SDP (which
1606 // could be invalid, but should not cause a crash).
1607 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001608 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1609 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001610 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001611 transceiver->internal()->SignalNegotiationNeeded.connect(
1612 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001613 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001614}
1615
Steve Anton52d86772018-02-20 15:48:12 -08001616void PeerConnection::OnNegotiationNeeded() {
1617 RTC_DCHECK_RUN_ON(signaling_thread());
1618 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001619 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001620}
1621
deadbeeffac06552015-11-25 11:26:01 -08001622rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001623 const std::string& kind,
1624 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001625 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1626 "Plan SdpSemantics. Please use AddTransceiver "
1627 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001628 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001629 if (IsClosed()) {
1630 return nullptr;
1631 }
Steve Anton4171afb2017-11-20 10:20:22 -08001632
Seth Hampson5b4f0752018-04-02 16:31:36 -07001633 // Internally we need to have one stream with Plan B semantics, so we
1634 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001635 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001636 if (stream_id.empty()) {
1637 stream_ids.push_back(rtc::CreateRandomUuid());
1638 RTC_LOG(LS_INFO)
1639 << "No stream_id specified for sender. Generated stream ID: "
1640 << stream_ids[0];
1641 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001642 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001643 }
1644
Steve Anton4171afb2017-11-20 10:20:22 -08001645 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001646 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001647 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001648 auto* audio_sender = new AudioRtpSender(
1649 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001650 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001651 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001652 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001653 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001654 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001655 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001656 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001657 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001658 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001659 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001660 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001661 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001662 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001663 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001664 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001665 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001666
deadbeefe1f9d832016-01-14 15:35:42 -08001667 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001668}
1669
deadbeef70ab1a12015-09-28 16:53:55 -07001670std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1671 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001672 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001673 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001674 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001675 }
1676 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001677}
1678
Steve Anton4171afb2017-11-20 10:20:22 -08001679std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1680PeerConnection::GetSendersInternal() const {
1681 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1682 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001683 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001684 auto senders = transceiver->internal()->senders();
1685 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1686 }
1687 return all_senders;
1688}
1689
deadbeef70ab1a12015-09-28 16:53:55 -07001690std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1691PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001692 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001693 for (const auto& receiver : GetReceiversInternal()) {
1694 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001695 }
1696 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001697}
1698
Steve Anton4171afb2017-11-20 10:20:22 -08001699std::vector<
1700 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1701PeerConnection::GetReceiversInternal() const {
1702 std::vector<
1703 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1704 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001705 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001706 auto receivers = transceiver->internal()->receivers();
1707 all_receivers.insert(all_receivers.end(), receivers.begin(),
1708 receivers.end());
1709 }
1710 return all_receivers;
1711}
1712
Steve Anton9158ef62017-11-27 13:01:52 -08001713std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1714PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001715 RTC_CHECK(IsUnifiedPlan())
1716 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001717 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001718 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001719 all_transceivers.push_back(transceiver);
1720 }
1721 return all_transceivers;
1722}
1723
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001724bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001725 MediaStreamTrackInterface* track,
1726 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001727 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001728 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001729 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001730 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731 return false;
1732 }
1733
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001734 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001735 // The StatsCollector is used to tell if a track is valid because it may
1736 // remember tracks that the PeerConnection previously removed.
1737 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001738 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1739 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001740 return false;
1741 }
Steve Antonad182762018-09-05 20:22:40 +00001742 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1743 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744 return true;
1745}
1746
hbos74e1a4f2016-09-15 23:33:01 -07001747void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001748 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001749 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001750 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001751 stats_collector_->GetStatsReport(callback);
1752}
1753
Henrik Boström1df1bf82018-03-20 13:24:20 +01001754void PeerConnection::GetStats(
1755 rtc::scoped_refptr<RtpSenderInterface> selector,
1756 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1757 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1758 RTC_DCHECK(callback);
1759 RTC_DCHECK(stats_collector_);
1760 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1761 if (selector) {
1762 for (const auto& proxy_transceiver : transceivers_) {
1763 for (const auto& proxy_sender :
1764 proxy_transceiver->internal()->senders()) {
1765 if (proxy_sender == selector) {
1766 internal_sender = proxy_sender->internal();
1767 break;
1768 }
1769 }
1770 if (internal_sender)
1771 break;
1772 }
1773 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001774 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001775 // belong to the PeerConnection (in Plan B, senders can be removed from the
1776 // PeerConnection). This means that "all the stats objects representing the
1777 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1778 // produces an empty stats report.
1779 stats_collector_->GetStatsReport(internal_sender, callback);
1780}
1781
1782void PeerConnection::GetStats(
1783 rtc::scoped_refptr<RtpReceiverInterface> selector,
1784 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1785 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1786 RTC_DCHECK(callback);
1787 RTC_DCHECK(stats_collector_);
1788 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1789 if (selector) {
1790 for (const auto& proxy_transceiver : transceivers_) {
1791 for (const auto& proxy_receiver :
1792 proxy_transceiver->internal()->receivers()) {
1793 if (proxy_receiver == selector) {
1794 internal_receiver = proxy_receiver->internal();
1795 break;
1796 }
1797 }
1798 if (internal_receiver)
1799 break;
1800 }
1801 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001802 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001803 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1804 // the PeerConnection). This means that "all the stats objects representing
1805 // the selector" is an empty set. Invoking GetStatsReport() with a null
1806 // selector produces an empty stats report.
1807 stats_collector_->GetStatsReport(internal_receiver, callback);
1808}
1809
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1811 return signaling_state_;
1812}
1813
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814PeerConnectionInterface::IceConnectionState
1815PeerConnection::ice_connection_state() {
1816 return ice_connection_state_;
1817}
1818
Alex Loiko9289eda2018-11-23 16:18:59 +00001819PeerConnectionInterface::IceConnectionState
1820PeerConnection::standardized_ice_connection_state() {
1821 return standardized_ice_connection_state_;
1822}
1823
Jonas Olsson635474e2018-10-18 15:58:17 +02001824PeerConnectionInterface::PeerConnectionState
1825PeerConnection::peer_connection_state() {
1826 return connection_state_;
1827}
1828
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001829PeerConnectionInterface::IceGatheringState
1830PeerConnection::ice_gathering_state() {
1831 return ice_gathering_state_;
1832}
1833
Yves Gerey665174f2018-06-19 15:03:05 +02001834rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001835 const std::string& label,
1836 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001837 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001838 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001839
deadbeefab9b2d12015-10-14 11:33:11 -07001840 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001841
kwibergd1fe2812016-04-27 06:47:29 -07001842 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001843 if (config) {
1844 internal_config.reset(new InternalDataChannelInit(*config));
1845 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001846 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001847 InternalCreateDataChannel(label, internal_config.get()));
1848 if (!channel.get()) {
1849 return nullptr;
1850 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001851
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001852 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1853 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001854 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001855 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001856 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001857 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 return DataChannelProxy::Create(signaling_thread(), channel.get());
1859}
1860
1861void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001862 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001863 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001864
nisse7ce109a2017-01-31 00:57:56 -08001865 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001866 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001867 return;
1868 }
deadbeefab9b2d12015-10-14 11:33:11 -07001869
Steve Anton8d3444d2017-10-20 15:30:51 -07001870 if (IsClosed()) {
1871 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001872 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001873 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001874 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001875 return;
1876 }
1877
zhihuang1c378ed2017-08-17 14:10:50 -07001878 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001879 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001880 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001881 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001882 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001883 return;
1884 }
1885
Steve Anton22da89f2018-01-25 13:58:07 -08001886 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1887 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1888 if (IsUnifiedPlan()) {
1889 RTCError error = HandleLegacyOfferOptions(options);
1890 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001891 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001892 return;
1893 }
1894 }
1895
zhihuang1c378ed2017-08-17 14:10:50 -07001896 cricket::MediaSessionOptions session_options;
1897 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001898 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001899}
1900
Steve Anton22da89f2018-01-25 13:58:07 -08001901RTCError PeerConnection::HandleLegacyOfferOptions(
1902 const RTCOfferAnswerOptions& options) {
1903 RTC_DCHECK(IsUnifiedPlan());
1904
1905 if (options.offer_to_receive_audio == 0) {
1906 RemoveRecvDirectionFromReceivingTransceiversOfType(
1907 cricket::MEDIA_TYPE_AUDIO);
1908 } else if (options.offer_to_receive_audio == 1) {
1909 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1910 } else if (options.offer_to_receive_audio > 1) {
1911 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1912 "offer_to_receive_audio > 1 is not supported.");
1913 }
1914
1915 if (options.offer_to_receive_video == 0) {
1916 RemoveRecvDirectionFromReceivingTransceiversOfType(
1917 cricket::MEDIA_TYPE_VIDEO);
1918 } else if (options.offer_to_receive_video == 1) {
1919 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1920 } else if (options.offer_to_receive_video > 1) {
1921 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1922 "offer_to_receive_video > 1 is not supported.");
1923 }
1924
1925 return RTCError::OK();
1926}
1927
1928void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1929 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001930 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001931 RtpTransceiverDirection new_direction =
1932 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1933 if (new_direction != transceiver->direction()) {
1934 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1935 << " transceiver (MID="
1936 << transceiver->mid().value_or("<not set>") << ") from "
1937 << RtpTransceiverDirectionToString(
1938 transceiver->direction())
1939 << " to "
1940 << RtpTransceiverDirectionToString(new_direction)
1941 << " since CreateOffer specified offer_to_receive=0";
1942 transceiver->internal()->set_direction(new_direction);
1943 }
Steve Anton22da89f2018-01-25 13:58:07 -08001944 }
1945}
1946
1947void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1948 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001949 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08001950 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001951 RTC_LOG(LS_INFO)
1952 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1953 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001954 RtpTransceiverInit init;
1955 init.direction = RtpTransceiverDirection::kRecvOnly;
1956 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1957 }
1958}
1959
1960std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1961PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1962 std::vector<
1963 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1964 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001965 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001966 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001967 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1968 receiving_transceivers.push_back(transceiver);
1969 }
1970 }
1971 return receiving_transceivers;
1972}
1973
htaa2a49d92016-03-04 02:51:39 -08001974void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1975 const RTCOfferAnswerOptions& options) {
1976 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001977 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001978 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001979 return;
1980 }
1981
Steve Antondffead82018-02-06 10:31:29 -08001982 if (!(signaling_state_ == kHaveRemoteOffer ||
1983 signaling_state_ == kHaveLocalPrAnswer)) {
1984 std::string error =
1985 "PeerConnection cannot create an answer in a state other than "
1986 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001987 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001988 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001989 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001990 return;
1991 }
1992
Steve Antondffead82018-02-06 10:31:29 -08001993 // The remote description should be set if we're in the right state.
1994 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001995
Steve Anton22da89f2018-01-25 13:58:07 -08001996 if (IsUnifiedPlan()) {
1997 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1998 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1999 "supported with Unified Plan semantics. Use the "
2000 "RtpTransceiver API instead.";
2001 }
2002 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2003 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2004 "supported with Unified Plan semantics. Use the "
2005 "RtpTransceiver API instead.";
2006 }
2007 }
2008
htaa2a49d92016-03-04 02:51:39 -08002009 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002010 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002011
Steve Antond25da372017-11-06 14:50:29 -08002012 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013}
2014
2015void PeerConnection::SetLocalDescription(
2016 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002017 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002018 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002019
Steve Anton80dd7b52018-02-16 17:08:42 -08002020 // The SetLocalDescription contract is that we take ownership of the session
2021 // description regardless of the outcome, so wrap it in a unique_ptr right
2022 // away. Ideally, SetLocalDescription's signature will be changed to take the
2023 // description as a unique_ptr argument to formalize this agreement.
2024 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2025
nisse7ce109a2017-01-31 00:57:56 -08002026 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002027 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 return;
2029 }
Steve Anton8a006912017-12-04 15:25:56 -08002030
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002032 PostSetSessionDescriptionFailure(
2033 observer,
2034 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035 return;
2036 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002037
Steve Anton80dd7b52018-02-16 17:08:42 -08002038 // If a session error has occurred the PeerConnection is in a possibly
2039 // inconsistent state so fail right away.
2040 if (session_error() != SessionError::kNone) {
2041 std::string error_message = GetSessionErrorMsg();
2042 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002043 PostSetSessionDescriptionFailure(
2044 observer,
2045 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002046 return;
2047 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002048
Steve Anton80dd7b52018-02-16 17:08:42 -08002049 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2050 if (!error.ok()) {
2051 std::string error_message = GetSetDescriptionErrorMessage(
2052 cricket::CS_LOCAL, desc->GetType(), error);
2053 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002054 PostSetSessionDescriptionFailure(
2055 observer,
2056 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002057 return;
2058 }
2059
2060 // Grab the description type before moving ownership to ApplyLocalDescription,
2061 // which may destroy it before returning.
2062 const SdpType type = desc->GetType();
2063
2064 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002065 // |desc| may be destroyed at this point.
2066
2067 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002068 // If ApplyLocalDescription fails, the PeerConnection could be in an
2069 // inconsistent state, so act conservatively here and set the session error
2070 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2071 SetSessionError(SessionError::kContent, error.message());
2072 std::string error_message =
2073 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2074 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002075 PostSetSessionDescriptionFailure(
2076 observer,
2077 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002078 return;
2079 }
Steve Anton8a006912017-12-04 15:25:56 -08002080 RTC_DCHECK(local_description());
2081
2082 PostSetSessionDescriptionSuccess(observer);
2083
Steve Antonad182762018-09-05 20:22:40 +00002084 // MaybeStartGathering needs to be called after posting
2085 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2086 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002087 transport_controller_->MaybeStartGathering();
2088
Steve Antona3a92c22017-12-07 10:27:41 -08002089 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002090 // TODO(deadbeef): We already had to hop to the network thread for
2091 // MaybeStartGathering...
2092 network_thread()->Invoke<void>(
2093 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2094 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002095 // Make UMA notes about what was agreed to.
2096 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002097 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002098 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002099}
2100
2101RTCError PeerConnection::ApplyLocalDescription(
2102 std::unique_ptr<SessionDescriptionInterface> desc) {
2103 RTC_DCHECK_RUN_ON(signaling_thread());
2104 RTC_DCHECK(desc);
2105
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002106 // Update stats here so that we have the most recent stats for tracks and
2107 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002108 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002109
Steve Antondcc3c022017-12-22 16:02:54 -08002110 // Take a reference to the old local description since it's used below to
2111 // compare against the new local description. When setting the new local
2112 // description, grab ownership of the replaced session description in case it
2113 // is the same as |old_local_description|, to keep it alive for the duration
2114 // of the method.
2115 const SessionDescriptionInterface* old_local_description =
2116 local_description();
2117 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002118 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002119 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002120 replaced_local_description = pending_local_description_
2121 ? std::move(pending_local_description_)
2122 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002123 current_local_description_ = std::move(desc);
2124 pending_local_description_ = nullptr;
2125 current_remote_description_ = std::move(pending_remote_description_);
2126 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002127 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002128 pending_local_description_ = std::move(desc);
2129 }
2130 // The session description to apply now must be accessed by
2131 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002132 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002133
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002134 if (!is_caller_) {
2135 if (remote_description()) {
2136 // Remote description was applied first, so this PC is the callee.
2137 is_caller_ = false;
2138 } else {
2139 // Local description is applied first, so this PC is the caller.
2140 is_caller_ = true;
2141 }
2142 }
2143
Zhi Huange830e682018-03-30 10:48:35 -07002144 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2145 if (!error.ok()) {
2146 return error;
2147 }
2148
Steve Antondcc3c022017-12-22 16:02:54 -08002149 if (IsUnifiedPlan()) {
2150 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002151 cricket::CS_LOCAL, *local_description(), old_local_description,
2152 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002153 if (!error.ok()) {
2154 return error;
2155 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002156 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2157 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002158 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002159 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2160 // Note that code paths that don't set MID won't be able to use
2161 // information about DTLS transports.
2162 if (transceiver->mid()) {
2163 auto dtls_transport =
2164 LookupDtlsTransportByMidInternal(*transceiver->mid());
2165 transceiver->internal()->sender_internal()->set_transport(
2166 dtls_transport);
2167 transceiver->internal()->receiver_internal()->set_transport(
2168 dtls_transport);
2169 }
2170
Steve Antondcc3c022017-12-22 16:02:54 -08002171 const ContentInfo* content =
2172 FindMediaSectionForTransceiver(transceiver, local_description());
2173 if (!content) {
2174 continue;
2175 }
2176 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002177 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2178 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002179 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002180 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2181 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2182 // "recvonly", process the removal of a remote track for the media
2183 // description, given transceiver, removeList, and muteTracks.
2184 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2185 (transceiver->internal()->fired_direction() &&
2186 RtpTransceiverDirectionHasRecv(
2187 *transceiver->internal()->fired_direction()))) {
2188 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2189 &removed_streams);
2190 }
2191 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2192 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002193 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002194 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002195 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002196 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002197 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002198 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002199 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002200 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002201 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002202 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002203 }
2204 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002205 // Media channels will be created only when offer is set. These may use new
2206 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002207 if (type == SdpType::kOffer) {
2208 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2209 // description is applied. Restore back to old description.
2210 RTCError error = CreateChannels(*local_description()->description());
2211 if (!error.ok()) {
2212 return error;
2213 }
2214 }
Steve Antondcc3c022017-12-22 16:02:54 -08002215 // Remove unused channels if MediaContentDescription is rejected.
2216 RemoveUnusedChannels(local_description()->description());
2217 }
Steve Anton8a006912017-12-04 15:25:56 -08002218
Zhi Huange830e682018-03-30 10:48:35 -07002219 error = UpdateSessionState(type, cricket::CS_LOCAL,
2220 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002221 if (!error.ok()) {
2222 return error;
2223 }
Steve Antondcc3c022017-12-22 16:02:54 -08002224
Steve Anton8a006912017-12-04 15:25:56 -08002225 if (remote_description()) {
2226 // Now that we have a local description, we can push down remote candidates.
2227 UseCandidatesInSessionDescription(remote_description());
2228 }
2229
2230 pending_ice_restarts_.clear();
2231 if (session_error() != SessionError::kNone) {
2232 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2233 }
2234
deadbeefab9b2d12015-10-14 11:33:11 -07002235 // If setting the description decided our SSL role, allocate any necessary
2236 // SCTP sids.
2237 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002238 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002239 AllocateSctpSids(role);
2240 }
2241
Steve Antond3679212018-01-17 17:41:02 -08002242 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002243 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002244 const ContentInfo* content =
2245 FindMediaSectionForTransceiver(transceiver, local_description());
2246 if (!content) {
2247 continue;
2248 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002249 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2250 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002251 // 0 is a special value meaning "this sender has no associated send
2252 // stream". Need to call this so the sender won't attempt to configure
2253 // a no longer existing stream and run into DCHECKs in the lower
2254 // layers.
2255 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002256 } else {
2257 // Get the StreamParams from the channel which could generate SSRCs.
2258 const std::vector<StreamParams>& streams = channel->local_streams();
2259 transceiver->internal()->sender_internal()->set_stream_ids(
2260 streams[0].stream_ids());
2261 transceiver->internal()->sender_internal()->SetSsrc(
2262 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002263 }
2264 }
2265 } else {
2266 // Plan B semantics.
2267
Steve Antondcc3c022017-12-22 16:02:54 -08002268 // Update state and SSRC of local MediaStreams and DataChannels based on the
2269 // local session description.
2270 const cricket::ContentInfo* audio_content =
2271 GetFirstAudioContent(local_description()->description());
2272 if (audio_content) {
2273 if (audio_content->rejected) {
2274 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2275 } else {
2276 const cricket::AudioContentDescription* audio_desc =
2277 audio_content->media_description()->as_audio();
2278 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2279 }
deadbeeffaac4972015-11-12 15:33:07 -08002280 }
deadbeefab9b2d12015-10-14 11:33:11 -07002281
Steve Antondcc3c022017-12-22 16:02:54 -08002282 const cricket::ContentInfo* video_content =
2283 GetFirstVideoContent(local_description()->description());
2284 if (video_content) {
2285 if (video_content->rejected) {
2286 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2287 } else {
2288 const cricket::VideoContentDescription* video_desc =
2289 video_content->media_description()->as_video();
2290 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2291 }
deadbeeffaac4972015-11-12 15:33:07 -08002292 }
deadbeefab9b2d12015-10-14 11:33:11 -07002293 }
2294
2295 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002296 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002297 if (data_content) {
2298 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002299 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002300 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002301 cricket::kMediaProtocolRtpPrefix)) {
2302 UpdateLocalRtpDataChannels(data_desc->streams());
2303 }
2304 }
2305
Steve Anton8a006912017-12-04 15:25:56 -08002306 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307}
2308
Steve Anton06817cd2018-12-18 15:55:30 -08002309// The SDP parser used to populate these values by default for the 'content
2310// name' if an a=mid line was absent.
2311static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2312 switch (media_type) {
2313 case cricket::MEDIA_TYPE_AUDIO:
2314 return cricket::CN_AUDIO;
2315 case cricket::MEDIA_TYPE_VIDEO:
2316 return cricket::CN_VIDEO;
2317 case cricket::MEDIA_TYPE_DATA:
2318 return cricket::CN_DATA;
2319 }
2320 RTC_NOTREACHED();
2321 return "";
2322}
2323
2324void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002325 cricket::SessionDescription* new_remote_description) {
2326 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002327 const cricket::ContentInfos& local_contents =
2328 (local_description() ? local_description()->description()->contents()
2329 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002330 const cricket::ContentInfos& remote_contents =
2331 (remote_description() ? remote_description()->description()->contents()
2332 : cricket::ContentInfos());
2333 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2334 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002335 if (!content.name.empty()) {
2336 continue;
2337 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002338 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002339 absl::string_view source_explanation;
2340 if (IsUnifiedPlan()) {
2341 if (i < local_contents.size()) {
2342 new_mid = local_contents[i].name;
2343 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002344 } else if (i < remote_contents.size()) {
2345 new_mid = remote_contents[i].name;
2346 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002347 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002348 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002349 source_explanation = "generated just now";
2350 }
2351 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002352 new_mid = std::string(
2353 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002354 source_explanation = "to match pre-existing behavior";
2355 }
Steve Antond7180cc2019-02-07 10:44:53 -08002356 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002357 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002358 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002359 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2360 << " is missing an a=mid line. Filling in the value '"
2361 << new_mid << "' " << source_explanation << ".";
2362 }
2363}
2364
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002365void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002366 SetSessionDescriptionObserver* observer,
2367 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002368 SetRemoteDescription(
2369 std::unique_ptr<SessionDescriptionInterface>(desc),
2370 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2371 new SetRemoteDescriptionObserverAdapter(this, observer)));
2372}
2373
2374void PeerConnection::SetRemoteDescription(
2375 std::unique_ptr<SessionDescriptionInterface> desc,
2376 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002377 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002378
nisse7ce109a2017-01-31 00:57:56 -08002379 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002380 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002381 return;
2382 }
Steve Anton8a006912017-12-04 15:25:56 -08002383
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002384 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002385 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002386 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002387 return;
2388 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002389
Steve Anton80dd7b52018-02-16 17:08:42 -08002390 // If a session error has occurred the PeerConnection is in a possibly
2391 // inconsistent state so fail right away.
2392 if (session_error() != SessionError::kNone) {
2393 std::string error_message = GetSessionErrorMsg();
2394 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2395 observer->OnSetRemoteDescriptionComplete(
2396 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2397 return;
2398 }
Steve Anton71439a62018-02-15 11:53:06 -08002399
Steve Antonba42e992018-04-09 14:10:01 -07002400 if (desc->GetType() == SdpType::kOffer) {
2401 // Report to UMA the format of the received offer.
2402 ReportSdpFormatReceived(*desc);
2403 }
2404
Steve Anton06817cd2018-12-18 15:55:30 -08002405 // Handle remote descriptions missing a=mid lines for interop with legacy end
2406 // points.
2407 FillInMissingRemoteMids(desc->description());
2408
Steve Anton80dd7b52018-02-16 17:08:42 -08002409 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002410 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002411 std::string error_message = GetSetDescriptionErrorMessage(
2412 cricket::CS_REMOTE, desc->GetType(), error);
2413 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002414 observer->OnSetRemoteDescriptionComplete(
2415 RTCError(error.type(), std::move(error_message)));
2416 return;
2417 }
Steve Anton71439a62018-02-15 11:53:06 -08002418
Steve Anton80dd7b52018-02-16 17:08:42 -08002419 // Grab the description type before moving ownership to
2420 // ApplyRemoteDescription, which may destroy it before returning.
2421 const SdpType type = desc->GetType();
2422
2423 error = ApplyRemoteDescription(std::move(desc));
2424 // |desc| may be destroyed at this point.
2425
2426 if (!error.ok()) {
2427 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2428 // inconsistent state, so act conservatively here and set the session error
2429 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2430 SetSessionError(SessionError::kContent, error.message());
2431 std::string error_message =
2432 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2433 RTC_LOG(LS_ERROR) << error_message;
2434 observer->OnSetRemoteDescriptionComplete(
2435 RTCError(error.type(), std::move(error_message)));
2436 return;
2437 }
2438 RTC_DCHECK(remote_description());
2439
2440 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002441 // TODO(deadbeef): We already had to hop to the network thread for
2442 // MaybeStartGathering...
2443 network_thread()->Invoke<void>(
2444 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2445 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002446 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002447 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002448 }
2449
2450 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002451 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002452}
2453
2454RTCError PeerConnection::ApplyRemoteDescription(
2455 std::unique_ptr<SessionDescriptionInterface> desc) {
2456 RTC_DCHECK_RUN_ON(signaling_thread());
2457 RTC_DCHECK(desc);
2458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459 // Update stats here so that we have the most recent stats for tracks and
2460 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002461 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002462
Steve Antondcc3c022017-12-22 16:02:54 -08002463 // Take a reference to the old remote description since it's used below to
2464 // compare against the new remote description. When setting the new remote
2465 // description, grab ownership of the replaced session description in case it
2466 // is the same as |old_remote_description|, to keep it alive for the duration
2467 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002468 const SessionDescriptionInterface* old_remote_description =
2469 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002470 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002471 SdpType type = desc->GetType();
2472 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002473 replaced_remote_description = pending_remote_description_
2474 ? std::move(pending_remote_description_)
2475 : std::move(current_remote_description_);
2476 current_remote_description_ = std::move(desc);
2477 pending_remote_description_ = nullptr;
2478 current_local_description_ = std::move(pending_local_description_);
2479 } else {
2480 replaced_remote_description = std::move(pending_remote_description_);
2481 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002482 }
Steve Anton8a006912017-12-04 15:25:56 -08002483 // The session description to apply now must be accessed by
2484 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002485 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002486
Zhi Huange830e682018-03-30 10:48:35 -07002487 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2488 if (!error.ok()) {
2489 return error;
2490 }
Steve Anton8a006912017-12-04 15:25:56 -08002491 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002492 if (IsUnifiedPlan()) {
2493 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002494 cricket::CS_REMOTE, *remote_description(), local_description(),
2495 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002496 if (!error.ok()) {
2497 return error;
2498 }
Steve Antondcc3c022017-12-22 16:02:54 -08002499 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002500 // Media channels will be created only when offer is set. These may use new
2501 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002502 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002503 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002504 // description is applied. Restore back to old description.
2505 RTCError error = CreateChannels(*remote_description()->description());
2506 if (!error.ok()) {
2507 return error;
2508 }
2509 }
Steve Antondcc3c022017-12-22 16:02:54 -08002510 // Remove unused channels if MediaContentDescription is rejected.
2511 RemoveUnusedChannels(remote_description()->description());
2512 }
Steve Anton8a006912017-12-04 15:25:56 -08002513
Zhi Huange830e682018-03-30 10:48:35 -07002514 // NOTE: Candidates allocation will be initiated only when
2515 // SetLocalDescription is called.
2516 error = UpdateSessionState(type, cricket::CS_REMOTE,
2517 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002518 if (!error.ok()) {
2519 return error;
2520 }
2521
2522 if (local_description() &&
2523 !UseCandidatesInSessionDescription(remote_description())) {
2524 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2525 }
2526
2527 if (old_remote_description) {
2528 for (const cricket::ContentInfo& content :
2529 old_remote_description->description()->contents()) {
2530 // Check if this new SessionDescription contains new ICE ufrag and
2531 // password that indicates the remote peer requests an ICE restart.
2532 // TODO(deadbeef): When we start storing both the current and pending
2533 // remote description, this should reset pending_ice_restarts and compare
2534 // against the current description.
2535 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2536 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002537 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002538 pending_ice_restarts_.insert(content.name);
2539 }
2540 } else {
2541 // We retain all received candidates only if ICE is not restarted.
2542 // When ICE is restarted, all previous candidates belong to an old
2543 // generation and should not be kept.
2544 // TODO(deadbeef): This goes against the W3C spec which says the remote
2545 // description should only contain candidates from the last set remote
2546 // description plus any candidates added since then. We should remove
2547 // this once we're sure it won't break anything.
2548 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2549 old_remote_description, content.name, mutable_remote_description());
2550 }
2551 }
2552 }
2553
2554 if (session_error() != SessionError::kNone) {
2555 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2556 }
2557
2558 // Set the the ICE connection state to connecting since the connection may
2559 // become writable with peer reflexive candidates before any remote candidate
2560 // is signaled.
2561 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2562 // is to have a new signal the indicates a change in checking state from the
2563 // transport and expose a new checking() member from transport that can be
2564 // read to determine the current checking state. The existing SignalConnecting
2565 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002566 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002567 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002568 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2569 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2570 }
2571
deadbeefab9b2d12015-10-14 11:33:11 -07002572 // If setting the description decided our SSL role, allocate any necessary
2573 // SCTP sids.
2574 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002575 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002576 AllocateSctpSids(role);
2577 }
2578
Steve Antondcc3c022017-12-22 16:02:54 -08002579 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002580 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002581 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002582 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002583 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002584 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002585 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002586 const ContentInfo* content =
2587 FindMediaSectionForTransceiver(transceiver, remote_description());
2588 if (!content) {
2589 continue;
2590 }
2591 const MediaContentDescription* media_desc = content->media_description();
2592 RtpTransceiverDirection local_direction =
2593 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002594 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2595 // RTCSessionDescription: Set the associated remote streams given
2596 // transceiver.[[Receiver]], msids, addList, and removeList".
2597 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2598 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2599 std::vector<std::string> stream_ids;
2600 if (!media_desc->streams().empty()) {
2601 // The remote description has signaled the stream IDs.
2602 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002603 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002604 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2605 << " (" << GetStreamIdsString(stream_ids) << ").";
2606 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2607 stream_ids, &added_streams,
2608 &removed_streams);
2609 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2610 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2611 // and transceiver's current direction is neither sendrecv nor recvonly,
2612 // process the addition of a remote track for the media description.
2613 if (!transceiver->fired_direction() ||
2614 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2615 RTC_LOG(LS_INFO)
2616 << "Processing the addition of a remote track for MID="
2617 << content->name << ".";
2618 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002619 }
Steve Antondcc3c022017-12-22 16:02:54 -08002620 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002621 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002622 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2623 // removal of a remote track for the media description, given transceiver,
2624 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002625 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002626 (transceiver->fired_direction() &&
2627 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2628 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2629 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002630 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002631 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002632 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002633 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002634 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002635 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002636 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002637 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002638 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002639 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2640 if (transceiver->mid()) {
2641 auto dtls_transport =
2642 LookupDtlsTransportByMidInternal(*transceiver->mid());
2643 transceiver->internal()->sender_internal()->set_transport(
2644 dtls_transport);
2645 transceiver->internal()->receiver_internal()->set_transport(
2646 dtls_transport);
2647 }
Steve Antondcc3c022017-12-22 16:02:54 -08002648 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002649 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002650 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002651 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002652 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2653 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002654 transceiver->Stop();
2655 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002656 if (!content->rejected &&
2657 RtpTransceiverDirectionHasRecv(local_direction)) {
2658 // Set ssrc to 0 in the case of an unsignalled ssrc.
2659 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002660 if (!media_desc->streams().empty() &&
2661 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002662 ssrc = media_desc->streams()[0].first_ssrc();
2663 }
2664 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002665 }
Steve Antondcc3c022017-12-22 16:02:54 -08002666 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002667 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002668 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002669 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002670 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002671 observer->OnTrack(transceiver);
2672 observer->OnAddTrack(transceiver->receiver(),
2673 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002674 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002675 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002676 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002677 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002678 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002679 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002680 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002681 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002682 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002683 }
Steve Antondcc3c022017-12-22 16:02:54 -08002684 }
2685
Henrik Boströmfdb92012017-11-09 19:55:44 +01002686 const cricket::ContentInfo* audio_content =
2687 GetFirstAudioContent(remote_description()->description());
2688 const cricket::ContentInfo* video_content =
2689 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002690 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002691 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002692 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002693 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002694 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002695 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002696
2697 // Check if the descriptions include streams, just in case the peer supports
2698 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002699 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002700 (audio_desc && !audio_desc->streams().empty()) ||
2701 (video_desc && !video_desc->streams().empty())) {
2702 remote_peer_supports_msid_ = true;
2703 }
deadbeefab9b2d12015-10-14 11:33:11 -07002704
2705 // We wait to signal new streams until we finish processing the description,
2706 // since only at that point will new streams have all their tracks.
2707 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2708
Steve Antondcc3c022017-12-22 16:02:54 -08002709 if (!IsUnifiedPlan()) {
2710 // TODO(steveanton): When removing RTP senders/receivers in response to a
2711 // rejected media section, there is some cleanup logic that expects the
2712 // voice/ video channel to still be set. But in this method the voice/video
2713 // channel would have been destroyed by the SetRemoteDescription caller
2714 // above so the cleanup that relies on them fails to run. The RemoveSenders
2715 // calls should be moved to right before the DestroyChannel calls to fix
2716 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002717
Steve Antondcc3c022017-12-22 16:02:54 -08002718 // Find all audio rtp streams and create corresponding remote AudioTracks
2719 // and MediaStreams.
2720 if (audio_content) {
2721 if (audio_content->rejected) {
2722 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2723 } else {
2724 bool default_audio_track_needed =
2725 !remote_peer_supports_msid_ &&
2726 RtpTransceiverDirectionHasSend(audio_desc->direction());
2727 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2728 default_audio_track_needed, audio_desc->type(),
2729 new_streams);
2730 }
deadbeeffaac4972015-11-12 15:33:07 -08002731 }
deadbeefab9b2d12015-10-14 11:33:11 -07002732
Steve Antondcc3c022017-12-22 16:02:54 -08002733 // Find all video rtp streams and create corresponding remote VideoTracks
2734 // and MediaStreams.
2735 if (video_content) {
2736 if (video_content->rejected) {
2737 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2738 } else {
2739 bool default_video_track_needed =
2740 !remote_peer_supports_msid_ &&
2741 RtpTransceiverDirectionHasSend(video_desc->direction());
2742 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2743 default_video_track_needed, video_desc->type(),
2744 new_streams);
2745 }
deadbeeffaac4972015-11-12 15:33:07 -08002746 }
deadbeefab9b2d12015-10-14 11:33:11 -07002747
Steve Antondcc3c022017-12-22 16:02:54 -08002748 // Update the DataChannels with the information from the remote peer.
2749 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002750 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002751 cricket::kMediaProtocolRtpPrefix)) {
2752 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2753 }
deadbeefab9b2d12015-10-14 11:33:11 -07002754 }
deadbeefab9b2d12015-10-14 11:33:11 -07002755
Steve Antondcc3c022017-12-22 16:02:54 -08002756 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002757 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002758 for (size_t i = 0; i < new_streams->count(); ++i) {
2759 MediaStreamInterface* new_stream = new_streams->at(i);
2760 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002761 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002762 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2763 }
deadbeefab9b2d12015-10-14 11:33:11 -07002764
Steve Antondcc3c022017-12-22 16:02:54 -08002765 UpdateEndedRemoteMediaStreams();
2766 }
deadbeefab9b2d12015-10-14 11:33:11 -07002767
Steve Anton8a006912017-12-04 15:25:56 -08002768 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002769}
2770
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002771void PeerConnection::SetAssociatedRemoteStreams(
2772 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2773 const std::vector<std::string>& stream_ids,
2774 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2775 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2776 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2777 for (const std::string& stream_id : stream_ids) {
2778 rtc::scoped_refptr<MediaStreamInterface> stream =
2779 remote_streams_->find(stream_id);
2780 if (!stream) {
2781 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2782 MediaStream::Create(stream_id));
2783 remote_streams_->AddStream(stream);
2784 added_streams->push_back(stream);
2785 }
2786 media_streams.push_back(stream);
2787 }
2788 // Special case: "a=msid" missing, use random stream ID.
2789 if (media_streams.empty() &&
2790 !(remote_description()->description()->msid_signaling() &
2791 cricket::kMsidSignalingMediaSection)) {
2792 if (!missing_msid_default_stream_) {
2793 missing_msid_default_stream_ = MediaStreamProxy::Create(
2794 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2795 added_streams->push_back(missing_msid_default_stream_);
2796 }
2797 media_streams.push_back(missing_msid_default_stream_);
2798 }
2799 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2800 receiver->streams();
2801 // SetStreams() will add/remove the receiver's track to/from the streams. This
2802 // differs from the spec - the spec uses an "addList" and "removeList" to
2803 // update the stream-track relationships in a later step. We do this earlier,
2804 // changing the order of things, but the end-result is the same.
2805 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2806 // instead. https://crbug.com/webrtc/9480
2807 receiver->SetStreams(media_streams);
2808 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2809}
2810
Steve Anton0f5400a2018-07-17 14:25:36 -07002811void PeerConnection::ProcessRemovalOfRemoteTrack(
2812 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2813 transceiver,
2814 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2815 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2816 RTC_DCHECK(transceiver->mid());
2817 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2818 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002819 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002820 transceiver->internal()->receiver_internal()->streams();
2821 // This will remove the remote track from the streams.
2822 transceiver->internal()->receiver_internal()->set_stream_ids({});
2823 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002824 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2825}
2826
2827void PeerConnection::RemoveRemoteStreamsIfEmpty(
2828 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2829 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2830 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2831 // streams, see if the stream was removed by checking if this was the last
2832 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002833 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002834 if (remote_stream->GetAudioTracks().empty() &&
2835 remote_stream->GetVideoTracks().empty()) {
2836 remote_streams_->RemoveStream(remote_stream);
2837 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002838 }
2839 }
2840}
2841
Steve Antondcc3c022017-12-22 16:02:54 -08002842RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2843 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002844 const SessionDescriptionInterface& new_session,
2845 const SessionDescriptionInterface* old_local_description,
2846 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002847 RTC_DCHECK(IsUnifiedPlan());
2848
Steve Anton7464fca2018-01-19 11:10:37 -08002849 const cricket::ContentGroup* bundle_group = nullptr;
2850 if (new_session.GetType() == SdpType::kOffer) {
2851 auto bundle_group_or_error =
2852 GetEarlyBundleGroup(*new_session.description());
2853 if (!bundle_group_or_error.ok()) {
2854 return bundle_group_or_error.MoveError();
2855 }
2856 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002857 }
Steve Antondcc3c022017-12-22 16:02:54 -08002858
Steve Antondcc3c022017-12-22 16:02:54 -08002859 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002860 for (size_t i = 0; i < new_contents.size(); ++i) {
2861 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002862 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002863 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002864 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2865 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002866 const cricket::ContentInfo* old_local_content = nullptr;
2867 if (old_local_description &&
2868 i < old_local_description->description()->contents().size()) {
2869 old_local_content =
2870 &old_local_description->description()->contents()[i];
2871 }
2872 const cricket::ContentInfo* old_remote_content = nullptr;
2873 if (old_remote_description &&
2874 i < old_remote_description->description()->contents().size()) {
2875 old_remote_content =
2876 &old_remote_description->description()->contents()[i];
2877 }
Steve Antondcc3c022017-12-22 16:02:54 -08002878 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002879 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2880 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002881 if (!transceiver_or_error.ok()) {
2882 return transceiver_or_error.MoveError();
2883 }
2884 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002885 RTCError error =
2886 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2887 if (!error.ok()) {
2888 return error;
2889 }
2890 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002891 if (GetDataMid() && new_content.name != *GetDataMid()) {
2892 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002893 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2894 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002895 continue;
2896 }
2897 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2898 if (!error.ok()) {
2899 return error;
2900 }
Steve Antondcc3c022017-12-22 16:02:54 -08002901 } else {
2902 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2903 "Unknown section type.");
2904 }
2905 }
2906
2907 return RTCError::OK();
2908}
2909
2910RTCError PeerConnection::UpdateTransceiverChannel(
2911 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2912 transceiver,
2913 const cricket::ContentInfo& content,
2914 const cricket::ContentGroup* bundle_group) {
2915 RTC_DCHECK(IsUnifiedPlan());
2916 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002917 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002918 if (content.rejected) {
2919 if (channel) {
2920 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002921 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002922 }
2923 } else {
2924 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002925 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002926 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002927 } else {
Steve Anton69470252018-02-09 11:43:08 -08002928 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002929 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002930 }
2931 if (!channel) {
2932 LOG_AND_RETURN_ERROR(
2933 RTCErrorType::INTERNAL_ERROR,
2934 "Failed to create channel for mid=" + content.name);
2935 }
2936 transceiver->internal()->SetChannel(channel);
2937 }
2938 }
2939 return RTCError::OK();
2940}
2941
Steve Antonfa2260d2017-12-28 16:38:23 -08002942RTCError PeerConnection::UpdateDataChannel(
2943 cricket::ContentSource source,
2944 const cricket::ContentInfo& content,
2945 const cricket::ContentGroup* bundle_group) {
2946 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002947 // If data channels are disabled, ignore this media section. CreateAnswer
2948 // will take care of rejecting it.
2949 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002950 }
2951 if (content.rejected) {
2952 DestroyDataChannel();
2953 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002954 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002955 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002956 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2957 "Failed to create data channel.");
2958 }
2959 }
2960 if (source == cricket::CS_REMOTE) {
2961 const MediaContentDescription* data_desc = content.media_description();
2962 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2963 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2964 }
2965 }
2966 }
2967 return RTCError::OK();
2968}
2969
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002970// This method will extract any send encodings that were sent by the remote
2971// connection. This is currently only relevant for Simulcast scenario (where
2972// the number of layers may be communicated by the server).
2973static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2974 const MediaContentDescription& desc) {
2975 if (!desc.HasSimulcast()) {
2976 return {};
2977 }
2978 std::vector<RtpEncodingParameters> result;
2979 const SimulcastDescription& simulcast = desc.simulcast_description();
2980
2981 // This is a remote description, the parameters we are after should appear
2982 // as receive streams.
2983 for (const auto& alternatives : simulcast.receive_layers()) {
2984 RTC_DCHECK(!alternatives.empty());
2985 // There is currently no way to specify or choose from alternatives.
2986 // We will always use the first alternative, which is the most preferred.
2987 const SimulcastLayer& layer = alternatives[0];
2988 RtpEncodingParameters parameters;
2989 parameters.rid = layer.rid;
2990 parameters.active = !layer.is_paused;
2991 result.push_back(parameters);
2992 }
2993
2994 return result;
2995}
2996
2997static RTCError UpdateSimulcastLayerStatusInSender(
2998 const std::vector<SimulcastLayer>& layers,
2999 RtpSenderInterface* sender) {
3000 RTC_DCHECK(sender);
3001 RtpParameters parameters = sender->GetParameters();
3002
3003 // The simulcast envelope cannot be changed, only the status of the streams.
3004 // So we will iterate over the send encodings rather than the layers.
3005 for (RtpEncodingParameters& encoding : parameters.encodings) {
3006 auto iter = std::find_if(layers.begin(), layers.end(),
3007 [&encoding](const SimulcastLayer& layer) {
3008 return layer.rid == encoding.rid;
3009 });
3010 // A layer that cannot be found may have been removed by the remote party.
3011 encoding.active = iter != layers.end() && !iter->is_paused;
3012 }
3013
3014 return sender->SetParameters(parameters);
3015}
3016
3017static RTCError DisableSimulcastInSender(RtpSenderInterface* sender) {
3018 RTC_DCHECK(sender);
3019 RtpParameters parameters = sender->GetParameters();
3020 if (parameters.encodings.empty()) {
3021 return RTCError::OK();
3022 }
3023
3024 bool first_layer_status = parameters.encodings[0].active;
3025 for (RtpEncodingParameters& encoding : parameters.encodings) {
3026 // TODO(bugs.webrtc.org/10251): Active does not really disable the layer.
3027 // The user might enable it at a later point in time even though it was
3028 // rejected.
3029 encoding.active = false;
3030 }
3031 parameters.encodings[0].active = first_layer_status;
3032
3033 return sender->SetParameters(parameters);
3034}
3035
Steve Antondcc3c022017-12-22 16:02:54 -08003036RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3037PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003038 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003039 size_t mline_index,
3040 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003041 const ContentInfo* old_local_content,
3042 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003043 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003044 // If this is an offer then the m= section might be recycled. If the m=
3045 // section is being recycled (defined as: rejected in the current local or
3046 // remote description and not rejected in new description), dissociate the
3047 // currently associated RtpTransceiver by setting its mid property to null,
3048 // and discard the mapping between the transceiver and its m= section index.
3049 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3050 old_remote_content)) {
3051 // We want to dissociate the transceiver that has the rejected mid.
3052 const std::string& old_mid =
3053 (old_local_content && old_local_content->rejected)
3054 ? old_local_content->name
3055 : old_remote_content->name;
3056 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003057 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003058 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3059 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003060 old_transceiver->internal()->set_mid(absl::nullopt);
3061 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003062 }
3063 }
3064 const MediaContentDescription* media_desc = content.media_description();
3065 auto transceiver = GetAssociatedTransceiver(content.name);
3066 if (source == cricket::CS_LOCAL) {
3067 // Find the RtpTransceiver that corresponds to this m= section, using the
3068 // mapping between transceivers and m= section indices established when
3069 // creating the offer.
3070 if (!transceiver) {
3071 transceiver = GetTransceiverByMLineIndex(mline_index);
3072 }
3073 if (!transceiver) {
3074 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3075 "Unknown transceiver");
3076 }
3077 } else {
3078 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3079 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3080 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003081 // When simulcast is requested, a transceiver cannot be associated because
3082 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003083 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003084 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3085 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003086 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3087 }
3088 // If no RtpTransceiver was found in the previous step, create one with a
3089 // recvonly direction.
3090 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003091 RTC_LOG(LS_INFO) << "Adding "
3092 << cricket::MediaTypeToString(media_desc->type())
3093 << " transceiver for MID=" << content.name
3094 << " at i=" << mline_index
3095 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003096 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003097 std::vector<RtpEncodingParameters> send_encodings =
3098 GetSendEncodingsFromRemoteDescription(*media_desc);
3099 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3100 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003101 std::string receiver_id;
3102 if (!media_desc->streams().empty()) {
3103 receiver_id = media_desc->streams()[0].id;
3104 } else {
3105 receiver_id = rtc::CreateRandomUuid();
3106 }
3107 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003108 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003109 transceiver->internal()->set_direction(
3110 RtpTransceiverDirection::kRecvOnly);
3111 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003112
3113 // Check if the offer indicated simulcast but the answer rejected it.
3114 // This can happen when simulcast is not supported on the remote party.
3115 // This check can be simplified to comparing the number of send encodings,
3116 // but that might break legacy implementation in which simulcast is not
3117 // signaled in the remote description.
3118 if (old_local_content && old_local_content->media_description() &&
3119 old_local_content->media_description()->HasSimulcast() &&
3120 !media_desc->HasSimulcast()) {
3121 RTCError error =
3122 DisableSimulcastInSender(transceiver->internal()->sender());
3123 if (!error.ok()) {
3124 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3125 return std::move(error);
3126 }
3127 }
Steve Antondcc3c022017-12-22 16:02:54 -08003128 }
3129 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003130 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003131 LOG_AND_RETURN_ERROR(
3132 RTCErrorType::INVALID_PARAMETER,
3133 "Transceiver type does not match media description type.");
3134 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003135 if (media_desc->HasSimulcast()) {
3136 std::vector<SimulcastLayer> layers =
3137 source == cricket::CS_LOCAL
3138 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3139 : media_desc->simulcast_description()
3140 .receive_layers()
3141 .GetAllLayers();
3142 RTCError error = UpdateSimulcastLayerStatusInSender(
3143 layers, transceiver->internal()->sender());
3144 if (!error.ok()) {
3145 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3146 return std::move(error);
3147 }
3148 }
Steve Antondcc3c022017-12-22 16:02:54 -08003149 // Associate the found or created RtpTransceiver with the m= section by
3150 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3151 // section, and establish a mapping between the transceiver and the index of
3152 // the m= section.
3153 transceiver->internal()->set_mid(content.name);
3154 transceiver->internal()->set_mline_index(mline_index);
3155 return std::move(transceiver);
3156}
3157
3158rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3159PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3160 RTC_DCHECK(IsUnifiedPlan());
3161 for (auto transceiver : transceivers_) {
3162 if (transceiver->mid() == mid) {
3163 return transceiver;
3164 }
3165 }
3166 return nullptr;
3167}
3168
3169rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3170PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3171 RTC_DCHECK(IsUnifiedPlan());
3172 for (auto transceiver : transceivers_) {
3173 if (transceiver->internal()->mline_index() == mline_index) {
3174 return transceiver;
3175 }
3176 }
3177 return nullptr;
3178}
3179
3180rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3181PeerConnection::FindAvailableTransceiverToReceive(
3182 cricket::MediaType media_type) const {
3183 RTC_DCHECK(IsUnifiedPlan());
3184 // From JSEP section 5.10 (Applying a Remote Description):
3185 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3186 // the same type that were added to the PeerConnection by addTrack and are not
3187 // associated with any m= section and are not stopped, find the first such
3188 // RtpTransceiver.
3189 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003190 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003191 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3192 !transceiver->stopped()) {
3193 return transceiver;
3194 }
3195 }
3196 return nullptr;
3197}
3198
Steve Antoned10bd92017-12-05 10:52:59 -08003199const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3200 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3201 transceiver,
3202 const SessionDescriptionInterface* sdesc) const {
3203 RTC_DCHECK(transceiver);
3204 RTC_DCHECK(sdesc);
3205 if (IsUnifiedPlan()) {
3206 if (!transceiver->internal()->mid()) {
3207 // This transceiver is not associated with a media section yet.
3208 return nullptr;
3209 }
3210 return sdesc->description()->GetContentByName(
3211 *transceiver->internal()->mid());
3212 } else {
3213 // Plan B only allows at most one audio and one video section, so use the
3214 // first media section of that type.
3215 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003216 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003217 }
3218}
3219
deadbeef46c73892016-11-16 19:42:04 -08003220PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3221 return configuration_;
3222}
3223
deadbeef293e9262017-01-11 12:28:30 -08003224bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3225 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003226 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003227 if (IsClosed()) {
3228 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3229 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3230 }
3231
Qingsi Wanga2d60672018-04-11 16:57:45 -07003232 // According to JSEP, after setLocalDescription, changing the candidate pool
3233 // size is not allowed, and changing the set of ICE servers will not result
3234 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003235 if (local_description() && configuration.ice_candidate_pool_size !=
3236 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003237 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3238 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003239 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003240 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003241
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003242 if (local_description() &&
3243 configuration.use_media_transport != configuration_.use_media_transport) {
3244 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3245 "SetLocalDescription.";
3246 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3247 }
3248
3249 if (remote_description() &&
3250 configuration.use_media_transport != configuration_.use_media_transport) {
3251 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3252 "SetRemoteDescription.";
3253 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3254 }
3255
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003256 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003257 configuration.use_media_transport_for_data_channels !=
3258 configuration_.use_media_transport_for_data_channels) {
3259 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3260 "after calling SetLocalDescription.";
3261 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3262 }
3263
3264 if (remote_description() &&
3265 configuration.use_media_transport_for_data_channels !=
3266 configuration_.use_media_transport_for_data_channels) {
3267 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3268 "after calling SetRemoteDescription.";
3269 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3270 }
3271
3272 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003273 configuration.crypto_options != configuration_.crypto_options) {
3274 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3275 "SetLocalDescription.";
3276 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3277 }
3278
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003279 if (configuration.use_media_transport_for_data_channels ||
3280 configuration.use_media_transport) {
3281 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3282 << "Media transport requires MaxBundle policy.";
3283 }
3284
deadbeef293e9262017-01-11 12:28:30 -08003285 // The simplest (and most future-compatible) way to tell if the config was
3286 // modified in an invalid way is to copy each property we do support
3287 // modifying, then use operator==. There are far more properties we don't
3288 // support modifying than those we do, and more could be added.
3289 RTCConfiguration modified_config = configuration_;
3290 modified_config.servers = configuration.servers;
3291 modified_config.type = configuration.type;
3292 modified_config.ice_candidate_pool_size =
3293 configuration.ice_candidate_pool_size;
3294 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003295 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003296 modified_config.ice_check_interval_strong_connectivity =
3297 configuration.ice_check_interval_strong_connectivity;
3298 modified_config.ice_check_interval_weak_connectivity =
3299 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003300 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3301 modified_config.ice_unwritable_min_checks =
3302 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003303 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003304 modified_config.stun_candidate_keepalive_interval =
3305 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003306 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003307 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003308 modified_config.active_reset_srtp_params =
3309 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003310 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003311 modified_config.use_media_transport_for_data_channels =
3312 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003313 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003314 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003315 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3316 }
3317
Steve Anton038834f2017-07-14 15:59:59 -07003318 // Validate the modified configuration.
3319 RTCError validate_error = ValidateConfiguration(modified_config);
3320 if (!validate_error.ok()) {
3321 return SafeSetError(std::move(validate_error), error);
3322 }
3323
deadbeef293e9262017-01-11 12:28:30 -08003324 // Note that this isn't possible through chromium, since it's an unsigned
3325 // short in WebIDL.
3326 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003327 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003328 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3329 }
3330
3331 // Parse ICE servers before hopping to network thread.
3332 cricket::ServerAddresses stun_servers;
3333 std::vector<cricket::RelayServerConfig> turn_servers;
3334 RTCErrorType parse_error =
3335 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3336 if (parse_error != RTCErrorType::NONE) {
3337 return SafeSetError(parse_error, error);
3338 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003339 // Note if STUN or TURN servers were supplied.
3340 if (!stun_servers.empty()) {
3341 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3342 }
3343 if (!turn_servers.empty()) {
3344 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3345 }
deadbeef293e9262017-01-11 12:28:30 -08003346
3347 // In theory this shouldn't fail.
3348 if (!network_thread()->Invoke<bool>(
3349 RTC_FROM_HERE,
3350 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3351 stun_servers, turn_servers, modified_config.type,
3352 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003353 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003354 modified_config.turn_customizer,
3355 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003356 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003357 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3358 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003359
deadbeefd1a38b52016-12-10 13:15:33 -08003360 // As described in JSEP, calling setConfiguration with new ICE servers or
3361 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3362 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003363 if (modified_config.servers != configuration_.servers ||
3364 modified_config.type != configuration_.type ||
3365 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003366 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003367 }
skvladd1f5fda2017-02-03 16:54:05 -08003368
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003369 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003370 transport_controller_->SetMediaTransportSettings(
3371 modified_config.use_media_transport,
3372 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003373
Zhi Huangb57e1692018-06-12 11:41:11 -07003374 if (configuration_.active_reset_srtp_params !=
3375 modified_config.active_reset_srtp_params) {
3376 transport_controller_->SetActiveResetSrtpParams(
3377 modified_config.active_reset_srtp_params);
3378 }
3379
deadbeef293e9262017-01-11 12:28:30 -08003380 configuration_ = modified_config;
3381 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003382}
3383
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003384bool PeerConnection::AddIceCandidate(
3385 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003386 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003387 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003388 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003389 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003390 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003391 return false;
3392 }
Steve Antond25da372017-11-06 14:50:29 -08003393
3394 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003395 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003396 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003397 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003398 return false;
3399 }
3400
3401 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003402 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003403 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003404 return false;
3405 }
3406
3407 bool valid = false;
3408 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3409 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003410 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003411 return false;
3412 }
3413
3414 // Add this candidate to the remote session description.
3415 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003416 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003417 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003418 return false;
3419 }
3420
3421 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003422 bool result = UseCandidate(ice_candidate);
3423 if (result) {
3424 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3425 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3426 } else {
3427 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3428 }
3429 return result;
Steve Antond25da372017-11-06 14:50:29 -08003430 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003431 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003432 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003433 return true;
3434 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435}
3436
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003437bool PeerConnection::RemoveIceCandidates(
3438 const std::vector<cricket::Candidate>& candidates) {
3439 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003440 if (IsClosed()) {
3441 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3442 return false;
3443 }
3444
Steve Antond25da372017-11-06 14:50:29 -08003445 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003446 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3447 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003448 return false;
3449 }
3450
3451 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003452 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003453 return false;
3454 }
3455
3456 size_t number_removed =
3457 mutable_remote_description()->RemoveCandidates(candidates);
3458 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003459 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003460 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003461 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003462 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003463 }
3464
3465 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003466 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3467 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003468 RTC_LOG(LS_ERROR)
3469 << "RemoveIceCandidates: Error when removing remote candidates: "
3470 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003471 }
3472 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003473}
3474
Niels Möller0c4f7be2018-05-07 14:01:37 +02003475RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003476 if (!worker_thread()->IsCurrent()) {
3477 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003478 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003479 }
3480
Niels Möller0c4f7be2018-05-07 14:01:37 +02003481 const bool has_min = bitrate.min_bitrate_bps.has_value();
3482 const bool has_start = bitrate.start_bitrate_bps.has_value();
3483 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003484 if (has_min && *bitrate.min_bitrate_bps < 0) {
3485 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3486 "min_bitrate_bps <= 0");
3487 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003488 if (has_start) {
3489 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003490 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003491 "start_bitrate_bps < min_bitrate_bps");
3492 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3494 "curent_bitrate_bps < 0");
3495 }
3496 }
3497 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003498 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003499 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003500 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003501 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3502 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3503 "max_bitrate_bps < min_bitrate_bps");
3504 } else if (*bitrate.max_bitrate_bps < 0) {
3505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3506 "max_bitrate_bps < 0");
3507 }
3508 }
3509
zstein4b979802017-06-02 14:37:37 -07003510 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003511 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003512
3513 return RTCError::OK();
3514}
3515
Alex Narest78609d52017-10-20 10:37:47 +02003516void PeerConnection::SetBitrateAllocationStrategy(
3517 std::unique_ptr<rtc::BitrateAllocationStrategy>
3518 bitrate_allocation_strategy) {
3519 rtc::Thread* worker_thread = factory_->worker_thread();
3520 if (!worker_thread->IsCurrent()) {
3521 rtc::BitrateAllocationStrategy* strategy_raw =
3522 bitrate_allocation_strategy.release();
3523 auto functor = [this, strategy_raw]() {
3524 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003525 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003526 };
3527 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3528 return;
3529 }
3530 RTC_DCHECK(call_.get());
3531 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3532}
3533
henrika5f6bf242017-11-01 11:06:56 +01003534void PeerConnection::SetAudioPlayout(bool playout) {
3535 if (!worker_thread()->IsCurrent()) {
3536 worker_thread()->Invoke<void>(
3537 RTC_FROM_HERE,
3538 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3539 return;
3540 }
3541 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003542 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003543 audio_state->SetPlayout(playout);
3544}
3545
3546void PeerConnection::SetAudioRecording(bool recording) {
3547 if (!worker_thread()->IsCurrent()) {
3548 worker_thread()->Invoke<void>(
3549 RTC_FROM_HERE,
3550 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3551 return;
3552 }
3553 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003554 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003555 audio_state->SetRecording(recording);
3556}
3557
Steve Anton8c0f7a72017-10-03 10:03:10 -07003558std::unique_ptr<rtc::SSLCertificate>
3559PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003560 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3561 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003562 return nullptr;
3563 }
Steve Antonf25303e2018-10-16 15:23:31 -07003564 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003565}
3566
Zhi Huang70b820f2018-01-27 14:16:15 -08003567std::unique_ptr<rtc::SSLCertChain>
3568PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003569 auto audio_transceiver = GetFirstAudioTransceiver();
3570 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003571 return nullptr;
3572 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003573 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003574 audio_transceiver->internal()->channel()->transport_name());
3575}
3576
3577rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3578PeerConnection::GetFirstAudioTransceiver() const {
3579 for (auto transceiver : transceivers_) {
3580 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3581 return transceiver;
3582 }
3583 }
3584 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003585}
3586
ivoc14d5dbe2016-07-04 07:06:55 -07003587bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3588 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003589 // TODO(eladalon): It would be better to not allow negative values into PC.
3590 const size_t max_size = (max_size_bytes < 0)
3591 ? RtcEventLog::kUnlimitedOutput
3592 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003593 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3594 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3595 output_period_ms = 5000;
3596 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003597 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003598 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003599 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003600}
3601
Bjorn Tereliusde939432017-11-20 17:38:14 +01003602bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3603 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003604 // TODO(eladalon): In C++14, this can be done with a lambda.
3605 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003606 bool operator()() {
3607 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3608 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003609 PeerConnection* const pc;
3610 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003611 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003612 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003613 return worker_thread()->Invoke<bool>(
3614 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003615}
3616
3617void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003618 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003619 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3620}
3621
Harald Alvestrandad88c882018-11-28 16:47:46 +01003622rtc::scoped_refptr<DtlsTransportInterface>
3623PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3624 return transport_controller_->LookupDtlsTransportByMid(mid);
3625}
3626
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003627rtc::scoped_refptr<DtlsTransport>
3628PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3629 return transport_controller_->LookupDtlsTransportByMid(mid);
3630}
3631
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003632const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003633 return pending_local_description_ ? pending_local_description_.get()
3634 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003635}
3636
3637const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003638 return pending_remote_description_ ? pending_remote_description_.get()
3639 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003640}
3641
deadbeeffe4a8a42016-12-20 17:56:17 -08003642const SessionDescriptionInterface* PeerConnection::current_local_description()
3643 const {
Steve Anton75737c02017-11-06 10:37:17 -08003644 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003645}
3646
3647const SessionDescriptionInterface* PeerConnection::current_remote_description()
3648 const {
Steve Anton75737c02017-11-06 10:37:17 -08003649 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003650}
3651
3652const SessionDescriptionInterface* PeerConnection::pending_local_description()
3653 const {
Steve Anton75737c02017-11-06 10:37:17 -08003654 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003655}
3656
3657const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3658 const {
Steve Anton75737c02017-11-06 10:37:17 -08003659 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003660}
3661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003662void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003663 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003664 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003665 // Update stats here so that we have the most recent stats for tracks and
3666 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003667 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003668
Steve Anton75737c02017-11-06 10:37:17 -08003669 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003670 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003671
Mirko Bonadei739baf02019-01-27 17:29:42 +01003672 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003673 transceiver->Stop();
3674 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003675
3676 // Ensure that all asynchronous stats requests are completed before destroying
3677 // the transport controller below.
3678 if (stats_collector_) {
3679 stats_collector_->WaitForPendingRequest();
3680 }
3681
3682 // Don't destroy BaseChannels until after stats has been cleaned up so that
3683 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003684 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003685
Qingsi Wang93a84392018-01-30 17:13:09 -08003686 // The event log is used in the transport controller, which must be outlived
3687 // by the former. CreateOffer by the peer connection is implemented
3688 // asynchronously and if the peer connection is closed without resetting the
3689 // WebRTC session description factory, the session description factory would
3690 // call the transport controller.
3691 webrtc_session_desc_factory_.reset();
3692 transport_controller_.reset();
3693
deadbeef42a42632017-03-10 15:18:00 -08003694 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003695 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3696 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003697
Steve Anton978b8762017-09-29 12:15:02 -07003698 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003699 call_.reset();
3700 // The event log must outlive call (and any other object that uses it).
3701 event_log_.reset();
3702 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003703 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003704 // The .h file says that observer can be discarded after close() returns.
3705 // Make sure this is true.
3706 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003707}
3708
Steve Antonad182762018-09-05 20:22:40 +00003709void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003710 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003711 switch (msg->message_id) {
3712 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3713 SetSessionDescriptionMsg* param =
3714 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3715 param->observer->OnSuccess();
3716 delete param;
3717 break;
3718 }
3719 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3720 SetSessionDescriptionMsg* param =
3721 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3722 param->observer->OnFailure(std::move(param->error));
3723 delete param;
3724 break;
3725 }
3726 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3727 CreateSessionDescriptionMsg* param =
3728 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3729 param->observer->OnFailure(std::move(param->error));
3730 delete param;
3731 break;
3732 }
3733 case MSG_GETSTATS: {
3734 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3735 StatsReports reports;
3736 stats_->GetStats(param->track, &reports);
3737 param->observer->OnComplete(reports);
3738 delete param;
3739 break;
3740 }
3741 case MSG_FREE_DATACHANNELS: {
3742 sctp_data_channels_to_free_.clear();
3743 break;
3744 }
3745 case MSG_REPORT_USAGE_PATTERN: {
3746 ReportUsagePattern();
3747 break;
3748 }
3749 default:
3750 RTC_NOTREACHED() << "Not implemented";
3751 break;
3752 }
3753}
3754
Steve Antonafb0bb72018-02-20 11:35:37 -08003755cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3756 RTC_DCHECK(!IsUnifiedPlan());
3757 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3758 GetAudioTransceiver()->internal()->channel());
3759 if (voice_channel) {
3760 return voice_channel->media_channel();
3761 } else {
3762 return nullptr;
3763 }
3764}
3765
3766cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3767 RTC_DCHECK(!IsUnifiedPlan());
3768 auto* video_channel = static_cast<cricket::VideoChannel*>(
3769 GetVideoTransceiver()->internal()->channel());
3770 if (video_channel) {
3771 return video_channel->media_channel();
3772 } else {
3773 return nullptr;
3774 }
3775}
3776
Steve Anton4171afb2017-11-20 10:20:22 -08003777void PeerConnection::CreateAudioReceiver(
3778 MediaStreamInterface* stream,
3779 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003780 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3781 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003782 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3783 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003784 auto* audio_receiver = new AudioRtpReceiver(
3785 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003786 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003787 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3788 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3789 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003790 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003791 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003792 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003793}
3794
Steve Anton4171afb2017-11-20 10:20:22 -08003795void PeerConnection::CreateVideoReceiver(
3796 MediaStreamInterface* stream,
3797 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003798 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3799 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003800 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3801 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003802 auto* video_receiver = new VideoRtpReceiver(
3803 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003804 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003805 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3806 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3807 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003808 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003809 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003810 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003811}
3812
deadbeef70ab1a12015-09-28 16:53:55 -07003813// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3814// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003815rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003816 const RtpSenderInfo& remote_sender_info) {
3817 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3818 if (!receiver) {
3819 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3820 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003821 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003822 }
Steve Anton4171afb2017-11-20 10:20:22 -08003823 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3824 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3825 } else {
3826 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3827 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003828 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003829}
3830
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003831void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3832 MediaStreamInterface* stream) {
3833 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003834 RTC_DCHECK(track);
3835 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003836 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003837 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003838 // We already have a sender for this track, so just change the stream_id
3839 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003840 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003841 return;
3842 }
3843
3844 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003845 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003846 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003847 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003848 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003849 // If the sender has already been configured in SDP, we call SetSsrc,
3850 // which will connect the sender to the underlying transport. This can
3851 // occur if a local session description that contains the ID of the sender
3852 // is set before AddStream is called. It can also occur if the local
3853 // session description is not changed and RemoveStream is called, and
3854 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003855 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003856 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003857 if (sender_info) {
3858 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003859 }
3860}
3861
3862// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3863// indefinitely, when we have unified plan SDP.
3864void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3865 MediaStreamInterface* stream) {
3866 RTC_DCHECK(!IsClosed());
3867 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003868 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003869 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3870 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003871 return;
3872 }
Steve Anton4171afb2017-11-20 10:20:22 -08003873 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003874}
3875
3876void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3877 MediaStreamInterface* stream) {
3878 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003879 RTC_DCHECK(track);
3880 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003881 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003882 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003883 // We already have a sender for this track, so just change the stream_id
3884 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003885 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003886 return;
3887 }
3888
3889 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003890 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003891 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003892 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003893 GetVideoTransceiver()->internal()->AddSender(new_sender);
3894 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003895 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003896 if (sender_info) {
3897 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003898 }
3899}
3900
3901void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3902 MediaStreamInterface* stream) {
3903 RTC_DCHECK(!IsClosed());
3904 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003905 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003906 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3907 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003908 return;
3909 }
Steve Anton4171afb2017-11-20 10:20:22 -08003910 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003911}
3912
Steve Antonba818672017-11-06 10:21:57 -08003913void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08003914 if (ice_connection_state_ == new_state) {
3915 return;
3916 }
3917
deadbeefcbecd352015-09-23 11:50:27 -07003918 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003919 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003920 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003921 return;
3922 }
Steve Antonba818672017-11-06 10:21:57 -08003923
Mirko Bonadei675513b2017-11-09 11:09:25 +01003924 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3925 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003926 RTC_DCHECK(ice_connection_state_ !=
3927 PeerConnectionInterface::kIceConnectionClosed);
3928
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003929 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003930 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003931}
3932
Alex Loiko9289eda2018-11-23 16:18:59 +00003933void PeerConnection::SetStandardizedIceConnectionState(
3934 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00003935 if (standardized_ice_connection_state_ == new_state)
3936 return;
3937 if (IsClosed())
3938 return;
3939 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003940 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003941}
3942
Jonas Olsson635474e2018-10-18 15:58:17 +02003943void PeerConnection::SetConnectionState(
3944 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02003945 if (connection_state_ == new_state)
3946 return;
3947 if (IsClosed())
3948 return;
3949 connection_state_ = new_state;
3950 Observer()->OnConnectionChange(new_state);
3951}
3952
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003953void PeerConnection::OnIceGatheringChange(
3954 PeerConnectionInterface::IceGatheringState new_state) {
3955 if (IsClosed()) {
3956 return;
3957 }
3958 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003959 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003960}
3961
jbauch81bf7b02017-03-25 08:31:12 -07003962void PeerConnection::OnIceCandidate(
3963 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07003964 if (IsClosed()) {
3965 return;
3966 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003967 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003968 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3969 candidate->candidate().address().IsPrivateIP()) {
3970 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3971 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003972 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003973}
3974
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003975void PeerConnection::OnIceCandidatesRemoved(
3976 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07003977 if (IsClosed()) {
3978 return;
3979 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003980 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003981}
3982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003983void PeerConnection::ChangeSignalingState(
3984 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003985 if (signaling_state_ == signaling_state) {
3986 return;
3987 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003988 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3989 << GetSignalingStateString(signaling_state_)
3990 << " New state: "
3991 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003992 signaling_state_ = signaling_state;
3993 if (signaling_state == kClosed) {
3994 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003995 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003996 standardized_ice_connection_state_ =
3997 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003998 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3999 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004000 if (ice_gathering_state_ != kIceGatheringComplete) {
4001 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004002 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004003 }
4004 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004005 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004006}
4007
deadbeefeb459812015-12-15 19:24:43 -08004008void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4009 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004010 if (IsClosed()) {
4011 return;
4012 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004013 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004014 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004015}
4016
deadbeefeb459812015-12-15 19:24:43 -08004017void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4018 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004019 if (IsClosed()) {
4020 return;
4021 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004022 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004023 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004024}
4025
4026void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4027 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004028 if (IsClosed()) {
4029 return;
4030 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004031 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004032 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004033}
4034
4035void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4036 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004037 if (IsClosed()) {
4038 return;
4039 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004040 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004041 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004042}
4043
Henrik Boström31638672017-11-23 17:48:32 +01004044void PeerConnection::PostSetSessionDescriptionSuccess(
4045 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004046 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4047 signaling_thread()->Post(RTC_FROM_HERE, this,
4048 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004049}
4050
deadbeefab9b2d12015-10-14 11:33:11 -07004051void PeerConnection::PostSetSessionDescriptionFailure(
4052 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004053 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004054 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004055 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4056 msg->error = std::move(error);
4057 signaling_thread()->Post(RTC_FROM_HERE, this,
4058 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004059}
4060
4061void PeerConnection::PostCreateSessionDescriptionFailure(
4062 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004063 RTCError error) {
4064 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004065 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4066 msg->error = std::move(error);
4067 signaling_thread()->Post(RTC_FROM_HERE, this,
4068 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004069}
4070
zhihuang1c378ed2017-08-17 14:10:50 -07004071void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004072 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004073 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004074 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004075
Steve Antondcc3c022017-12-22 16:02:54 -08004076 if (IsUnifiedPlan()) {
4077 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4078 } else {
4079 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4080 }
4081
Steve Antonfa2260d2017-12-28 16:38:23 -08004082 // Intentionally unset the data channel type for RTP data channel with the
4083 // second condition. Otherwise the RTP data channels would be successfully
4084 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4085 // when building with chromium. We want to leave RTP data channels broken, so
4086 // people won't try to use them.
4087 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4088 session_options->data_channel_type = data_channel_type();
4089 }
4090
Steve Antondcc3c022017-12-22 16:02:54 -08004091 // Apply ICE restart flag and renomination flag.
4092 for (auto& options : session_options->media_description_options) {
4093 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4094 options.transport_options.enable_ice_renomination =
4095 configuration_.enable_ice_renomination;
4096 }
4097
4098 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004099 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004100 session_options->pooled_ice_credentials =
4101 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4102 RTC_FROM_HERE,
4103 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4104 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004105 session_options->offer_extmap_allow_mixed =
4106 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004107}
4108
4109void PeerConnection::GetOptionsForPlanBOffer(
4110 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4111 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004112 // Figure out transceiver directional preferences.
4113 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4114 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4115
4116 // By default, generate sendrecv/recvonly m= sections.
4117 bool recv_audio = true;
4118 bool recv_video = true;
4119
4120 // By default, only offer a new m= section if we have media to send with it.
4121 bool offer_new_audio_description = send_audio;
4122 bool offer_new_video_description = send_video;
4123 bool offer_new_data_description = HasDataChannels();
4124
4125 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004126 if (offer_answer_options.offer_to_receive_audio !=
4127 RTCOfferAnswerOptions::kUndefined) {
4128 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004129 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004130 offer_new_audio_description ||
4131 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004132 }
Steve Antondcc3c022017-12-22 16:02:54 -08004133 if (offer_answer_options.offer_to_receive_video !=
4134 RTCOfferAnswerOptions::kUndefined) {
4135 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004136 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004137 offer_new_video_description ||
4138 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004139 }
4140
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004141 absl::optional<size_t> audio_index;
4142 absl::optional<size_t> video_index;
4143 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004144 // If a current description exists, generate m= sections in the same order,
4145 // using the first audio/video/data section that appears and rejecting
4146 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004147 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004148 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004149 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004150 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4151 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4152 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004153 }
4154
zhihuang1c378ed2017-08-17 14:10:50 -07004155 // Add audio/video/data m= sections to the end if needed.
4156 if (!audio_index && offer_new_audio_description) {
4157 session_options->media_description_options.push_back(
4158 cricket::MediaDescriptionOptions(
4159 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004160 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4161 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004162 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004163 }
zhihuang1c378ed2017-08-17 14:10:50 -07004164 if (!video_index && offer_new_video_description) {
4165 session_options->media_description_options.push_back(
4166 cricket::MediaDescriptionOptions(
4167 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004168 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4169 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004170 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004171 }
zhihuang1c378ed2017-08-17 14:10:50 -07004172 if (!data_index && offer_new_data_description) {
4173 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004174 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004175 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004176 }
4177
4178 cricket::MediaDescriptionOptions* audio_media_description_options =
4179 !audio_index ? nullptr
4180 : &session_options->media_description_options[*audio_index];
4181 cricket::MediaDescriptionOptions* video_media_description_options =
4182 !video_index ? nullptr
4183 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004184
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004185 AddPlanBRtpSenderOptions(GetSendersInternal(),
4186 audio_media_description_options,
4187 video_media_description_options,
4188 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004189}
4190
Steve Antondcc3c022017-12-22 16:02:54 -08004191static cricket::MediaDescriptionOptions
4192GetMediaDescriptionOptionsForTransceiver(
4193 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4194 transceiver,
4195 const std::string& mid) {
4196 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004197 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004198 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004199 // This behavior is specified in JSEP. The gist is that:
4200 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4201 // sendrecv.
4202 // 2. If the MSID is included, then it must be included in any subsequent
4203 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004204 if (transceiver->stopped() ||
4205 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4206 !transceiver->internal()->has_ever_been_used_to_send())) {
4207 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004208 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004209
4210 cricket::SenderOptions sender_options;
4211 sender_options.track_id = transceiver->sender()->id();
4212 sender_options.stream_ids = transceiver->sender()->stream_ids();
4213
4214 // The following sets up RIDs and Simulcast.
4215 // RIDs are included if Simulcast is requested or if any RID was specified.
4216 RtpParameters send_parameters = transceiver->sender()->GetParameters();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004217 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4218 send_parameters.encodings.end(),
4219 [](const RtpEncodingParameters& encoding) {
4220 return !encoding.rid.empty();
4221 });
4222
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004223 std::vector<RidDescription> send_rids;
4224 SimulcastLayerList send_layers;
4225 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4226 if (encoding.rid.empty()) {
4227 continue;
4228 }
4229 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4230 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4231 }
4232
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004233 if (has_rids) {
4234 sender_options.rids = send_rids;
4235 }
4236
4237 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004238 // When RIDs are configured, we must set num_sim_layers to 0 to.
4239 // Otherwise, num_sim_layers must be 1 because either there is no
4240 // simulcast, or simulcast is acheived by munging the SDP.
4241 sender_options.num_sim_layers = has_rids ? 0 : 1;
4242 media_description_options.sender_options.push_back(sender_options);
4243
Steve Antondcc3c022017-12-22 16:02:54 -08004244 return media_description_options;
4245}
4246
Steve Anton5c72e712018-12-10 14:25:30 -08004247// Returns the ContentInfo at mline index |i|, or null if none exists.
4248static const ContentInfo* GetContentByIndex(
4249 const SessionDescriptionInterface* sdesc,
4250 size_t i) {
4251 if (!sdesc) {
4252 return nullptr;
4253 }
4254 const ContentInfos& contents = sdesc->description()->contents();
4255 return (i < contents.size() ? &contents[i] : nullptr);
4256}
4257
Steve Antondcc3c022017-12-22 16:02:54 -08004258void PeerConnection::GetOptionsForUnifiedPlanOffer(
4259 const RTCOfferAnswerOptions& offer_answer_options,
4260 cricket::MediaSessionOptions* session_options) {
4261 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4262 // Offers) and 5.2.2 (Subsequent Offers).
4263 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4264 const ContentInfos& local_contents =
4265 (local_description() ? local_description()->description()->contents()
4266 : ContentInfos());
4267 const ContentInfos& remote_contents =
4268 (remote_description() ? remote_description()->description()->contents()
4269 : ContentInfos());
4270 // The mline indices that can be recycled. New transceivers should reuse these
4271 // slots first.
4272 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004273 // First, go through each media section that exists in either the local or
4274 // remote description and generate a media section in this offer for the
4275 // associated transceiver. If a media section can be recycled, generate a
4276 // default, rejected media section here that can be later overwritten.
4277 for (size_t i = 0;
4278 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4279 // Either |local_content| or |remote_content| is non-null.
4280 const ContentInfo* local_content =
4281 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004282 const ContentInfo* current_local_content =
4283 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004284 const ContentInfo* remote_content =
4285 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004286 const ContentInfo* current_remote_content =
4287 GetContentByIndex(current_remote_description(), i);
4288 bool had_been_rejected =
4289 (current_local_content && current_local_content->rejected) ||
4290 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004291 const std::string& mid =
4292 (local_content ? local_content->name : remote_content->name);
4293 cricket::MediaType media_type =
4294 (local_content ? local_content->media_description()->type()
4295 : remote_content->media_description()->type());
4296 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4297 media_type == cricket::MEDIA_TYPE_VIDEO) {
4298 auto transceiver = GetAssociatedTransceiver(mid);
4299 RTC_CHECK(transceiver);
4300 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004301 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004302 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004303 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004304 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4305 RtpTransceiverDirection::kInactive,
4306 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004307 recycleable_mline_indices.push(i);
4308 } else {
4309 session_options->media_description_options.push_back(
4310 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4311 // CreateOffer shouldn't really cause any state changes in
4312 // PeerConnection, but we need a way to match new transceivers to new
4313 // media sections in SetLocalDescription and JSEP specifies this is done
4314 // by recording the index of the media section generated for the
4315 // transceiver in the offer.
4316 transceiver->internal()->set_mline_index(i);
4317 }
4318 } else {
4319 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004320 RTC_CHECK(GetDataMid());
4321 if (had_been_rejected || mid != *GetDataMid()) {
4322 session_options->media_description_options.push_back(
4323 GetMediaDescriptionOptionsForRejectedData(mid));
4324 } else {
4325 session_options->media_description_options.push_back(
4326 GetMediaDescriptionOptionsForActiveData(mid));
4327 }
Steve Antondcc3c022017-12-22 16:02:54 -08004328 }
4329 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004330
Steve Antondcc3c022017-12-22 16:02:54 -08004331 // Next, look for transceivers that are newly added (that is, are not stopped
4332 // and not associated). Reuse media sections marked as recyclable first,
4333 // otherwise append to the end of the offer. New media sections should be
4334 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004335 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004336 if (transceiver->mid() || transceiver->stopped()) {
4337 continue;
4338 }
4339 size_t mline_index;
4340 if (!recycleable_mline_indices.empty()) {
4341 mline_index = recycleable_mline_indices.front();
4342 recycleable_mline_indices.pop();
4343 session_options->media_description_options[mline_index] =
4344 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004345 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004346 } else {
4347 mline_index = session_options->media_description_options.size();
4348 session_options->media_description_options.push_back(
4349 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004350 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004351 }
4352 // See comment above for why CreateOffer changes the transceiver's state.
4353 transceiver->internal()->set_mline_index(mline_index);
4354 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004355 // Lastly, add a m-section if we have local data channels and an m section
4356 // does not already exist.
4357 if (!GetDataMid() && HasDataChannels()) {
4358 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004359 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004360 }
Steve Antondcc3c022017-12-22 16:02:54 -08004361}
4362
4363void PeerConnection::GetOptionsForAnswer(
4364 const RTCOfferAnswerOptions& offer_answer_options,
4365 cricket::MediaSessionOptions* session_options) {
4366 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4367
4368 if (IsUnifiedPlan()) {
4369 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4370 } else {
4371 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4372 }
4373
Steve Antonfa2260d2017-12-28 16:38:23 -08004374 // Intentionally unset the data channel type for RTP data channel. Otherwise
4375 // the RTP data channels would be successfully negotiated by default and the
4376 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4377 // We want to leave RTP data channels broken, so people won't try to use them.
4378 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4379 session_options->data_channel_type = data_channel_type();
4380 }
4381
Steve Antondcc3c022017-12-22 16:02:54 -08004382 // Apply ICE renomination flag.
4383 for (auto& options : session_options->media_description_options) {
4384 options.transport_options.enable_ice_renomination =
4385 configuration_.enable_ice_renomination;
4386 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004387
4388 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004389 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004390 session_options->pooled_ice_credentials =
4391 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4392 RTC_FROM_HERE,
4393 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4394 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004395}
4396
Steve Antondcc3c022017-12-22 16:02:54 -08004397void PeerConnection::GetOptionsForPlanBAnswer(
4398 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004399 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004400 // Figure out transceiver directional preferences.
4401 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4402 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4403
4404 // By default, generate sendrecv/recvonly m= sections. The direction is also
4405 // restricted by the direction in the offer.
4406 bool recv_audio = true;
4407 bool recv_video = true;
4408
4409 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004410 if (offer_answer_options.offer_to_receive_audio !=
4411 RTCOfferAnswerOptions::kUndefined) {
4412 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004413 }
Steve Antondcc3c022017-12-22 16:02:54 -08004414 if (offer_answer_options.offer_to_receive_video !=
4415 RTCOfferAnswerOptions::kUndefined) {
4416 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004417 }
4418
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004419 absl::optional<size_t> audio_index;
4420 absl::optional<size_t> video_index;
4421 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004422
4423 // Generate m= sections that match those in the offer.
4424 // Note that mediasession.cc will handle intersection our preferred
4425 // direction with the offered direction.
4426 GenerateMediaDescriptionOptions(
4427 remote_description(),
4428 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4429 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4430 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004431
4432 cricket::MediaDescriptionOptions* audio_media_description_options =
4433 !audio_index ? nullptr
4434 : &session_options->media_description_options[*audio_index];
4435 cricket::MediaDescriptionOptions* video_media_description_options =
4436 !video_index ? nullptr
4437 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004438
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004439 AddPlanBRtpSenderOptions(GetSendersInternal(),
4440 audio_media_description_options,
4441 video_media_description_options,
4442 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004443}
zhihuangaf388472016-11-02 16:49:48 -07004444
Steve Antondcc3c022017-12-22 16:02:54 -08004445void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4446 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4447 cricket::MediaSessionOptions* session_options) {
4448 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4449 // Answers) and 5.3.2 (Subsequent Answers).
4450 RTC_DCHECK(remote_description());
4451 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4452 for (const ContentInfo& content :
4453 remote_description()->description()->contents()) {
4454 cricket::MediaType media_type = content.media_description()->type();
4455 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4456 media_type == cricket::MEDIA_TYPE_VIDEO) {
4457 auto transceiver = GetAssociatedTransceiver(content.name);
4458 RTC_CHECK(transceiver);
4459 session_options->media_description_options.push_back(
4460 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4461 } else {
4462 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004463 // Reject all data sections if data channels are disabled.
4464 // Reject a data section if it has already been rejected.
4465 // Reject all data sections except for the first one.
4466 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4467 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004468 session_options->media_description_options.push_back(
4469 GetMediaDescriptionOptionsForRejectedData(content.name));
4470 } else {
4471 session_options->media_description_options.push_back(
4472 GetMediaDescriptionOptionsForActiveData(content.name));
4473 }
Steve Antondcc3c022017-12-22 16:02:54 -08004474 }
4475 }
htaa2a49d92016-03-04 02:51:39 -08004476}
4477
zhihuang1c378ed2017-08-17 14:10:50 -07004478void PeerConnection::GenerateMediaDescriptionOptions(
4479 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004480 RtpTransceiverDirection audio_direction,
4481 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004482 absl::optional<size_t>* audio_index,
4483 absl::optional<size_t>* video_index,
4484 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004485 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004486 for (const cricket::ContentInfo& content :
4487 session_desc->description()->contents()) {
4488 if (IsAudioContent(&content)) {
4489 // If we already have an audio m= section, reject this extra one.
4490 if (*audio_index) {
4491 session_options->media_description_options.push_back(
4492 cricket::MediaDescriptionOptions(
4493 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004494 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004495 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004496 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004497 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004498 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4499 content.name, audio_direction,
4500 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004501 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004502 }
4503 } else if (IsVideoContent(&content)) {
4504 // If we already have an video m= section, reject this extra one.
4505 if (*video_index) {
4506 session_options->media_description_options.push_back(
4507 cricket::MediaDescriptionOptions(
4508 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004509 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004510 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004511 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004512 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004513 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4514 content.name, video_direction,
4515 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004516 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004517 }
4518 } else {
4519 RTC_DCHECK(IsDataContent(&content));
4520 // If we already have an data m= section, reject this extra one.
4521 if (*data_index) {
4522 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004523 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004524 } else {
4525 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004526 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004527 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004528 }
4529 }
htaa2a49d92016-03-04 02:51:39 -08004530 }
deadbeefab9b2d12015-10-14 11:33:11 -07004531}
4532
Steve Antonfa2260d2017-12-28 16:38:23 -08004533cricket::MediaDescriptionOptions
4534PeerConnection::GetMediaDescriptionOptionsForActiveData(
4535 const std::string& mid) const {
4536 // Direction for data sections is meaningless, but legacy endpoints might
4537 // expect sendrecv.
4538 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4539 RtpTransceiverDirection::kSendRecv,
4540 /*stopped=*/false);
4541 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4542 return options;
4543}
4544
4545cricket::MediaDescriptionOptions
4546PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4547 const std::string& mid) const {
4548 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4549 RtpTransceiverDirection::kInactive,
4550 /*stopped=*/true);
4551 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4552 return options;
4553}
4554
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004555absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004556 switch (data_channel_type_) {
4557 case cricket::DCT_RTP:
4558 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004559 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004560 }
4561 return rtp_data_channel_->content_name();
4562 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004563 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004564 case cricket::DCT_MEDIA_TRANSPORT:
4565 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004566 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004567 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004568 }
4569}
4570
Steve Anton4171afb2017-11-20 10:20:22 -08004571void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4572 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4573 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004574 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004575}
4576
Steve Anton4171afb2017-11-20 10:20:22 -08004577void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004578 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004579 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004580 cricket::MediaType media_type,
4581 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004582 RTC_DCHECK(!IsUnifiedPlan());
4583
Steve Anton4171afb2017-11-20 10:20:22 -08004584 std::vector<RtpSenderInfo>* current_senders =
4585 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004586
Steve Anton4171afb2017-11-20 10:20:22 -08004587 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004588 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004589 for (auto sender_it = current_senders->begin();
4590 sender_it != current_senders->end();
4591 /* incremented manually */) {
4592 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004593 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004594 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004595 std::string params_stream_id;
4596 if (params) {
4597 params_stream_id =
4598 (!params->first_stream_id().empty() ? params->first_stream_id()
4599 : kDefaultStreamId);
4600 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004601 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004602 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004603 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004604 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004605 sender_exists) {
4606 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004607 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004608 OnRemoteSenderRemoved(info, media_type);
4609 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004610 }
4611 }
4612
Steve Anton4171afb2017-11-20 10:20:22 -08004613 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004614 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004615 if (!params.has_ssrcs()) {
4616 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4617 // sender, this means it is coming from a Unified Plan endpoint,so we just
4618 // create a default.
4619 default_sender_needed = true;
4620 break;
4621 }
4622
Seth Hampson845e8782018-03-02 11:34:10 -08004623 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004624 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004625 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4626 // not supported in Plan B, we just take the first here and create the
4627 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004628 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004629 (!params.first_stream_id().empty() ? params.first_stream_id()
4630 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004631 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004632 uint32_t ssrc = params.first_ssrc();
4633
4634 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004635 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004636 if (!stream) {
4637 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004638 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004639 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004640 remote_streams_->AddStream(stream);
4641 new_streams->AddStream(stream);
4642 }
4643
Steve Anton4171afb2017-11-20 10:20:22 -08004644 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004645 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004646 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004647 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004648 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004649 }
4650 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004651
Steve Anton4171afb2017-11-20 10:20:22 -08004652 // Add default sender if necessary.
4653 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004654 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004655 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004656 if (!default_stream) {
4657 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004658 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004659 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004660 remote_streams_->AddStream(default_stream);
4661 new_streams->AddStream(default_stream);
4662 }
Steve Anton4171afb2017-11-20 10:20:22 -08004663 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4664 ? kDefaultAudioSenderId
4665 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004666 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004667 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004668 if (!default_sender_info) {
4669 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004670 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004671 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004672 }
4673 }
deadbeefab9b2d12015-10-14 11:33:11 -07004674}
4675
Steve Anton4171afb2017-11-20 10:20:22 -08004676void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4677 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004678 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4679 << " receiver for track_id=" << sender_info.sender_id
4680 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004681
Steve Anton3d954a62018-04-02 11:27:23 -07004682 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004683 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004684 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004685 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004686 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004687 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004688 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004689 }
4690}
4691
Steve Anton4171afb2017-11-20 10:20:22 -08004692void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4693 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004694 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4695 << " receiver for track_id=" << sender_info.sender_id
4696 << " and stream_id=" << sender_info.stream_id;
4697
Seth Hampson845e8782018-03-02 11:34:10 -08004698 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004699
Henrik Boström933d8b02017-10-10 10:05:16 -07004700 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004701 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004702 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4703 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004704 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004705 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004706 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004707 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004708 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004709 }
4710 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004711 // Stopping or destroying a VideoRtpReceiver will end the
4712 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004713 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004714 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004715 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004716 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004717 // There's no guarantee the track is still available, e.g. the track may
4718 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004719 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004720 }
4721 } else {
nisseede5da42017-01-12 05:15:36 -08004722 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004723 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004724 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004725 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004726 }
deadbeefab9b2d12015-10-14 11:33:11 -07004727}
4728
4729void PeerConnection::UpdateEndedRemoteMediaStreams() {
4730 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4731 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4732 MediaStreamInterface* stream = remote_streams_->at(i);
4733 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4734 streams_to_remove.push_back(stream);
4735 }
4736 }
4737
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004738 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004739 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004740 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004741 }
4742}
4743
Steve Anton4171afb2017-11-20 10:20:22 -08004744void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004745 const std::vector<cricket::StreamParams>& streams,
4746 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004747 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004748
Seth Hampson845e8782018-03-02 11:34:10 -08004749 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004750 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004751 for (auto sender_it = current_senders->begin();
4752 sender_it != current_senders->end();
4753 /* incremented manually */) {
4754 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004755 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004756 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4757 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004758 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004759 OnLocalSenderRemoved(info, media_type);
4760 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004761 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004762 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004763 }
4764 }
4765
Steve Anton4171afb2017-11-20 10:20:22 -08004766 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004767 for (const cricket::StreamParams& params : streams) {
4768 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004769 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004770 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004771 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004772 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004773 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004774 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004775 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004776 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004777 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004778 }
4779 }
4780}
4781
Steve Anton4171afb2017-11-20 10:20:22 -08004782void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4783 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004784 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004785 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004786 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004787 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4788 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004789 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004790 return;
4791 }
4792
deadbeeffac06552015-11-25 11:26:01 -08004793 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004794 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004795 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004796 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004797 }
deadbeeffac06552015-11-25 11:26:01 -08004798
Seth Hampson5b4f0752018-04-02 16:31:36 -07004799 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004800 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004801}
4802
Steve Anton4171afb2017-11-20 10:20:22 -08004803void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4804 cricket::MediaType media_type) {
4805 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004806 if (!sender) {
4807 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004808 // SessionDescriptions has been renegotiated.
4809 return;
4810 }
deadbeeffac06552015-11-25 11:26:01 -08004811
4812 // A sender has been removed from the SessionDescription but it's still
4813 // associated with the PeerConnection. This only occurs if the SDP doesn't
4814 // match with the calls to CreateSender, AddStream and RemoveStream.
4815 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004816 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004817 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004818 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004819 }
deadbeeffac06552015-11-25 11:26:01 -08004820
Steve Anton4171afb2017-11-20 10:20:22 -08004821 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004822}
4823
4824void PeerConnection::UpdateLocalRtpDataChannels(
4825 const cricket::StreamParamsVec& streams) {
4826 std::vector<std::string> existing_channels;
4827
4828 // Find new and active data channels.
4829 for (const cricket::StreamParams& params : streams) {
4830 // |it->sync_label| is actually the data channel label. The reason is that
4831 // we use the same naming of data channels as we do for
4832 // MediaStreams and Tracks.
4833 // For MediaStreams, the sync_label is the MediaStream label and the
4834 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004835 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004836 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004837 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004838 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004839 continue;
4840 }
4841 // Set the SSRC the data channel should use for sending.
4842 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4843 existing_channels.push_back(data_channel_it->first);
4844 }
4845
4846 UpdateClosingRtpDataChannels(existing_channels, true);
4847}
4848
4849void PeerConnection::UpdateRemoteRtpDataChannels(
4850 const cricket::StreamParamsVec& streams) {
4851 std::vector<std::string> existing_channels;
4852
4853 // Find new and active data channels.
4854 for (const cricket::StreamParams& params : streams) {
4855 // The data channel label is either the mslabel or the SSRC if the mslabel
4856 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004857 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004858 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004859 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004860 auto data_channel_it = rtp_data_channels_.find(label);
4861 if (data_channel_it == rtp_data_channels_.end()) {
4862 // This is a new data channel.
4863 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4864 } else {
4865 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4866 }
4867 existing_channels.push_back(label);
4868 }
4869
4870 UpdateClosingRtpDataChannels(existing_channels, false);
4871}
4872
4873void PeerConnection::UpdateClosingRtpDataChannels(
4874 const std::vector<std::string>& active_channels,
4875 bool is_local_update) {
4876 auto it = rtp_data_channels_.begin();
4877 while (it != rtp_data_channels_.end()) {
4878 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004879 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004880 ++it;
4881 continue;
4882 }
4883
4884 if (is_local_update) {
4885 data_channel->SetSendSsrc(0);
4886 } else {
4887 data_channel->RemotePeerRequestClose();
4888 }
4889
4890 if (data_channel->state() == DataChannel::kClosed) {
4891 rtp_data_channels_.erase(it);
4892 it = rtp_data_channels_.begin();
4893 } else {
4894 ++it;
4895 }
4896 }
4897}
4898
4899void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4900 uint32_t remote_ssrc) {
4901 rtc::scoped_refptr<DataChannel> channel(
4902 InternalCreateDataChannel(label, nullptr));
4903 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004904 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004905 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004906 return;
4907 }
4908 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004909 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4910 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004911 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004912}
4913
4914rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4915 const std::string& label,
4916 const InternalDataChannelInit* config) {
4917 if (IsClosed()) {
4918 return nullptr;
4919 }
Steve Anton75737c02017-11-06 10:37:17 -08004920 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004921 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004922 << "InternalCreateDataChannel: Data is not supported in this call.";
4923 return nullptr;
4924 }
4925 InternalDataChannelInit new_config =
4926 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004927 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004928 if (new_config.id < 0) {
4929 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004930 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004931 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004932 RTC_LOG(LS_ERROR)
4933 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004934 return nullptr;
4935 }
4936 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004937 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004938 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004939 return nullptr;
4940 }
4941 }
4942
Steve Anton75737c02017-11-06 10:37:17 -08004943 rtc::scoped_refptr<DataChannel> channel(
4944 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004945 if (!channel) {
4946 sid_allocator_.ReleaseSid(new_config.id);
4947 return nullptr;
4948 }
4949
4950 if (channel->data_channel_type() == cricket::DCT_RTP) {
4951 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004952 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4953 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004954 return nullptr;
4955 }
4956 rtp_data_channels_[channel->label()] = channel;
4957 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004958 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004959 sctp_data_channels_.push_back(channel);
4960 channel->SignalClosed.connect(this,
4961 &PeerConnection::OnSctpDataChannelClosed);
4962 }
4963
Steve Anton2d8609c2018-01-23 16:38:46 -08004964 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004965 return channel;
4966}
4967
4968bool PeerConnection::HasDataChannels() const {
4969 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4970}
4971
4972void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4973 for (const auto& channel : sctp_data_channels_) {
4974 if (channel->id() < 0) {
4975 int sid;
4976 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004977 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004978 continue;
4979 }
4980 channel->SetSctpSid(sid);
4981 }
4982 }
4983}
4984
4985void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004986 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004987 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4988 ++it) {
4989 if (it->get() == channel) {
4990 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004991 // After the closing procedure is done, it's safe to use this ID for
4992 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004993 sid_allocator_.ReleaseSid(channel->id());
4994 }
deadbeefbd292462015-12-14 18:15:29 -08004995 // Since this method is triggered by a signal from the DataChannel,
4996 // we can't free it directly here; we need to free it asynchronously.
4997 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004998 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004999 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5000 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005001 return;
5002 }
5003 }
5004}
5005
deadbeefab9b2d12015-10-14 11:33:11 -07005006void PeerConnection::OnDataChannelDestroyed() {
5007 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5008 // DataChannel may callback to us and try to modify the list.
5009 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5010 temp_rtp_dcs.swap(rtp_data_channels_);
5011 for (const auto& kv : temp_rtp_dcs) {
5012 kv.second->OnTransportChannelDestroyed();
5013 }
5014
5015 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5016 temp_sctp_dcs.swap(sctp_data_channels_);
5017 for (const auto& channel : temp_sctp_dcs) {
5018 channel->OnTransportChannelDestroyed();
5019 }
5020}
5021
5022void PeerConnection::OnDataChannelOpenMessage(
5023 const std::string& label,
5024 const InternalDataChannelInit& config) {
5025 rtc::scoped_refptr<DataChannel> channel(
5026 InternalCreateDataChannel(label, &config));
5027 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005028 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005029 return;
5030 }
5031
deadbeefa601f5c2016-06-06 14:27:39 -07005032 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5033 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005034 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005035 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005036}
5037
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005038bool PeerConnection::HandleOpenMessage_s(
5039 const cricket::ReceiveDataParams& params,
5040 const rtc::CopyOnWriteBuffer& buffer) {
5041 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5042 // Received OPEN message; parse and signal that a new data channel should
5043 // be created.
5044 std::string label;
5045 InternalDataChannelInit config;
5046 config.id = params.ssrc;
5047 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5048 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5049 << params.ssrc;
5050 return true;
5051 }
5052 config.open_handshake_role = InternalDataChannelInit::kAcker;
5053 OnDataChannelOpenMessage(label, config);
5054 return true;
5055 }
5056 return false;
5057}
5058
Steve Anton4171afb2017-11-20 10:20:22 -08005059rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5060PeerConnection::GetAudioTransceiver() const {
5061 // This method only works with Plan B SDP, where there is a single
5062 // audio/video transceiver.
5063 RTC_DCHECK(!IsUnifiedPlan());
5064 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005065 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005066 return transceiver;
5067 }
5068 }
5069 RTC_NOTREACHED();
5070 return nullptr;
5071}
5072
5073rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5074PeerConnection::GetVideoTransceiver() const {
5075 // This method only works with Plan B SDP, where there is a single
5076 // audio/video transceiver.
5077 RTC_DCHECK(!IsUnifiedPlan());
5078 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005079 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005080 return transceiver;
5081 }
5082 }
5083 RTC_NOTREACHED();
5084 return nullptr;
5085}
5086
5087// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5088// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005089bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005090 switch (type) {
5091 case cricket::MEDIA_TYPE_AUDIO:
5092 return !GetAudioTransceiver()->internal()->senders().empty();
5093 case cricket::MEDIA_TYPE_VIDEO:
5094 return !GetVideoTransceiver()->internal()->senders().empty();
5095 case cricket::MEDIA_TYPE_DATA:
5096 return false;
5097 }
5098 RTC_NOTREACHED();
5099 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005100}
5101
Steve Anton4171afb2017-11-20 10:20:22 -08005102rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5103PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005104 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005105 for (auto sender : transceiver->internal()->senders()) {
5106 if (sender->track() == track) {
5107 return sender;
5108 }
5109 }
5110 }
5111 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005112}
5113
Steve Anton4171afb2017-11-20 10:20:22 -08005114rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5115PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005116 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005117 for (auto sender : transceiver->internal()->senders()) {
5118 if (sender->id() == sender_id) {
5119 return sender;
5120 }
5121 }
5122 }
5123 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005124}
5125
Steve Anton4171afb2017-11-20 10:20:22 -08005126rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5127PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005128 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005129 for (auto receiver : transceiver->internal()->receivers()) {
5130 if (receiver->id() == receiver_id) {
5131 return receiver;
5132 }
5133 }
5134 }
5135 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005136}
5137
Steve Anton4171afb2017-11-20 10:20:22 -08005138std::vector<PeerConnection::RtpSenderInfo>*
5139PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5140 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5141 media_type == cricket::MEDIA_TYPE_VIDEO);
5142 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5143 ? &remote_audio_sender_infos_
5144 : &remote_video_sender_infos_;
5145}
5146
5147std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005148 cricket::MediaType media_type) {
5149 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5150 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005151 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5152 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005153}
5154
Steve Anton4171afb2017-11-20 10:20:22 -08005155const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5156 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005157 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005158 const std::string sender_id) const {
5159 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005160 if (sender_info.stream_id == stream_id &&
5161 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005162 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005163 }
5164 }
5165 return nullptr;
5166}
5167
5168DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5169 for (const auto& channel : sctp_data_channels_) {
5170 if (channel->id() == sid) {
5171 return channel;
5172 }
5173 }
5174 return nullptr;
5175}
5176
deadbeef91dd5672016-05-18 16:55:30 -07005177bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005178 const cricket::ServerAddresses& stun_servers,
5179 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005180 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005181 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005182 // To handle both internal and externally created port allocator, we will
5183 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005184 port_allocator_flags_ = port_allocator_->flags();
5185 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5186 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5187 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005188 // If the disable-IPv6 flag was specified, we'll not override it
5189 // by experiment.
5190 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005191 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005192 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5193 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005194 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005195 }
5196
zhihuangb09b3f92017-03-07 14:40:51 -08005197 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005198 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005199 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005200 }
5201
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005202 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005203 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005204 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005205 }
5206
honghaiz60347052016-05-31 18:29:12 -07005207 if (configuration.candidate_network_policy ==
5208 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005209 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005210 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005211 }
5212
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005213 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005214 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005215 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5216 }
5217
Qingsi Wanga2d60672018-04-11 16:57:45 -07005218 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005219 // No step delay is used while allocating ports.
5220 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5221 port_allocator_->set_candidate_filter(
5222 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005223 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005224
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005225 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005226 for (auto& turn_server : turn_servers_copy) {
5227 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005228 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005229 // Call this last since it may create pooled allocator sessions using the
5230 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005231 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005232 stun_servers, std::move(turn_servers_copy),
5233 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5234 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005235 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005236 return true;
5237}
5238
deadbeef91dd5672016-05-18 16:55:30 -07005239bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005240 const cricket::ServerAddresses& stun_servers,
5241 const std::vector<cricket::RelayServerConfig>& turn_servers,
5242 IceTransportsType type,
5243 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005244 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005245 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005246 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005247 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005248 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005249 // According to JSEP, after setLocalDescription, changing the candidate pool
5250 // size is not allowed, and changing the set of ICE servers will not result
5251 // in new candidates being gathered.
5252 if (local_description()) {
5253 port_allocator_->FreezeCandidatePool();
5254 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005255 // Add the custom tls turn servers if they exist.
5256 auto turn_servers_copy = turn_servers;
5257 for (auto& turn_server : turn_servers_copy) {
5258 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5259 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005260 // Call this last since it may create pooled allocator sessions using the
5261 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005262 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005263 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5264 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005265}
5266
Steve Antonba818672017-11-06 10:21:57 -08005267cricket::ChannelManager* PeerConnection::channel_manager() const {
5268 return factory_->channel_manager();
5269}
5270
Elad Alon99c3fe52017-10-13 16:29:40 +02005271bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005272 std::unique_ptr<RtcEventLogOutput> output,
5273 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005274 if (!event_log_) {
5275 return false;
5276 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005277 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005278}
5279
5280void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005281 if (event_log_) {
5282 event_log_->StopLogging();
5283 }
ivoc14d5dbe2016-07-04 07:06:55 -07005284}
nisseeaabdf62017-05-05 02:23:02 -07005285
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005286cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005287 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005288 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005289 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005290 if (channel && channel->content_name() == content_name) {
5291 return channel;
5292 }
Steve Anton75737c02017-11-06 10:37:17 -08005293 }
5294 if (rtp_data_channel() &&
5295 rtp_data_channel()->content_name() == content_name) {
5296 return rtp_data_channel();
5297 }
5298 return nullptr;
5299}
5300
5301bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005302 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005303 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005304 RTC_LOG(LS_INFO)
5305 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005306 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005307 return false;
5308 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005309 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005310 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed 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 }
5314
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005315 absl::optional<rtc::SSLRole> dtls_role;
5316 if (sctp_mid_) {
5317 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5318 } else if (is_caller_) {
5319 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5320 }
Zhi Huange830e682018-03-30 10:48:35 -07005321 if (dtls_role) {
5322 *role = *dtls_role;
5323 return true;
5324 }
5325 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005326}
5327
5328bool PeerConnection::GetSslRole(const std::string& content_name,
5329 rtc::SSLRole* role) {
5330 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005331 RTC_LOG(LS_INFO)
5332 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005333 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005334 return false;
5335 }
5336
Zhi Huange830e682018-03-30 10:48:35 -07005337 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5338 if (dtls_role) {
5339 *role = *dtls_role;
5340 return true;
5341 }
5342 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005343}
5344
Steve Antonf8470812017-12-04 10:46:21 -08005345void PeerConnection::SetSessionError(SessionError error,
5346 const std::string& error_desc) {
5347 RTC_DCHECK_RUN_ON(signaling_thread());
5348 if (error != session_error_) {
5349 session_error_ = error;
5350 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005351 }
5352}
5353
Zhi Huange830e682018-03-30 10:48:35 -07005354RTCError PeerConnection::UpdateSessionState(
5355 SdpType type,
5356 cricket::ContentSource source,
5357 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005358 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005359
5360 // If there's already a pending error then no state transition should happen.
5361 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005362 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005363
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005364 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005365 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005366 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005367 }
5368
5369 // Update the signaling state according to the specified state machine (see
5370 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005371 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005372 ChangeSignalingState(source == cricket::CS_LOCAL
5373 ? PeerConnectionInterface::kHaveLocalOffer
5374 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005375 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005376 ChangeSignalingState(source == cricket::CS_LOCAL
5377 ? PeerConnectionInterface::kHaveLocalPrAnswer
5378 : PeerConnectionInterface::kHaveRemotePrAnswer);
5379 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005380 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005381 ChangeSignalingState(PeerConnectionInterface::kStable);
5382 }
5383
5384 // Update internal objects according to the session description's media
5385 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005386 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005387 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005388 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005389 }
5390
Steve Anton8a006912017-12-04 15:25:56 -08005391 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005392}
5393
Steve Anton8a006912017-12-04 15:25:56 -08005394RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005395 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005396 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005397 const SessionDescriptionInterface* sdesc =
5398 (source == cricket::CS_LOCAL ? local_description()
5399 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005400 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005401
5402 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005403 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005404 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005405 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005406 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005407 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005408 continue;
5409 }
5410 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005411 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005412 if (!content_desc) {
5413 continue;
5414 }
5415 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005416 bool success = (source == cricket::CS_LOCAL)
5417 ? channel->SetLocalContent(content_desc, type, &error)
5418 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005419 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005420 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005421 }
5422 }
5423
5424 // If using the RtpDataChannel, push down the new SDP section for it too.
5425 if (rtp_data_channel_) {
5426 const ContentInfo* data_content =
5427 cricket::GetFirstDataContent(sdesc->description());
5428 if (data_content && !data_content->rejected) {
5429 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005430 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005431 if (data_desc) {
5432 std::string error;
5433 bool success =
5434 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005435 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005436 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005437 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005438 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005439 }
Steve Anton75737c02017-11-06 10:37:17 -08005440 }
5441 }
5442 }
Steve Antoned10bd92017-12-05 10:52:59 -08005443
Steve Anton75737c02017-11-06 10:37:17 -08005444 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5445 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5446 if (sctp_transport_ && local_description() && remote_description() &&
5447 cricket::GetFirstDataContent(local_description()->description()) &&
5448 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005449 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005450 RTC_FROM_HERE,
5451 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005452 if (!success) {
5453 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5454 "Failed to push down SCTP parameters.");
5455 }
Steve Anton75737c02017-11-06 10:37:17 -08005456 }
Steve Antoned10bd92017-12-05 10:52:59 -08005457
Steve Anton8a006912017-12-04 15:25:56 -08005458 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005459}
5460
5461bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5462 RTC_DCHECK(network_thread()->IsCurrent());
5463 RTC_DCHECK(local_description());
5464 RTC_DCHECK(remote_description());
5465 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5466 // When we support "max-message-size", that would also be pushed down here.
5467 return sctp_transport_->Start(
5468 GetSctpPort(local_description()->description()),
5469 GetSctpPort(remote_description()->description()));
5470}
5471
Steve Anton8a006912017-12-04 15:25:56 -08005472RTCError PeerConnection::PushdownTransportDescription(
5473 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005474 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005475 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005476
Zhi Huange830e682018-03-30 10:48:35 -07005477 if (source == cricket::CS_LOCAL) {
5478 const SessionDescriptionInterface* sdesc = local_description();
5479 RTC_DCHECK(sdesc);
5480 return transport_controller_->SetLocalDescription(type,
5481 sdesc->description());
5482 } else {
5483 const SessionDescriptionInterface* sdesc = remote_description();
5484 RTC_DCHECK(sdesc);
5485 return transport_controller_->SetRemoteDescription(type,
5486 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005487 }
Steve Anton75737c02017-11-06 10:37:17 -08005488}
5489
5490bool PeerConnection::GetTransportDescription(
5491 const SessionDescription* description,
5492 const std::string& content_name,
5493 cricket::TransportDescription* tdesc) {
5494 if (!description || !tdesc) {
5495 return false;
5496 }
5497 const TransportInfo* transport_info =
5498 description->GetTransportInfoByName(content_name);
5499 if (!transport_info) {
5500 return false;
5501 }
5502 *tdesc = transport_info->description;
5503 return true;
5504}
5505
Steve Anton75737c02017-11-06 10:37:17 -08005506cricket::IceConfig PeerConnection::ParseIceConfig(
5507 const PeerConnectionInterface::RTCConfiguration& config) const {
5508 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005509 switch (config.continual_gathering_policy) {
5510 case PeerConnectionInterface::GATHER_ONCE:
5511 gathering_policy = cricket::GATHER_ONCE;
5512 break;
5513 case PeerConnectionInterface::GATHER_CONTINUALLY:
5514 gathering_policy = cricket::GATHER_CONTINUALLY;
5515 break;
5516 default:
5517 RTC_NOTREACHED();
5518 gathering_policy = cricket::GATHER_ONCE;
5519 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005520
Steve Anton75737c02017-11-06 10:37:17 -08005521 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005522 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5523 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005524 ice_config.prioritize_most_likely_candidate_pairs =
5525 config.prioritize_most_likely_ice_candidate_pairs;
5526 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005527 RTCConfigurationToIceConfigOptionalInt(
5528 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005529 ice_config.continual_gathering_policy = gathering_policy;
5530 ice_config.presume_writable_when_fully_relayed =
5531 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005532 ice_config.ice_check_interval_strong_connectivity =
5533 config.ice_check_interval_strong_connectivity;
5534 ice_config.ice_check_interval_weak_connectivity =
5535 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005536 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005537 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5538 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005539 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005540 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005541 ice_config.regather_all_networks_interval_range =
5542 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005543 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005544 return ice_config;
5545}
5546
Steve Antona41959e2018-11-28 11:15:33 -08005547static absl::string_view GetTrackIdBySsrc(
5548 const SessionDescriptionInterface* session_description,
5549 uint32_t ssrc) {
5550 if (!session_description) {
5551 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005552 }
Steve Antona41959e2018-11-28 11:15:33 -08005553 for (const cricket::ContentInfo& content :
5554 session_description->description()->contents()) {
5555 const cricket::MediaContentDescription& media =
5556 *content.media_description();
5557 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5558 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5559 const cricket::StreamParams* stream_params =
5560 cricket::GetStreamBySsrc(media.streams(), ssrc);
5561 if (stream_params) {
5562 return stream_params->id;
5563 }
5564 }
5565 }
5566 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005567}
5568
Steve Antona41959e2018-11-28 11:15:33 -08005569absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5570 return GetTrackIdBySsrc(local_description(), ssrc);
5571}
5572
5573absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5574 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005575}
5576
5577bool PeerConnection::SendData(const cricket::SendDataParams& params,
5578 const rtc::CopyOnWriteBuffer& payload,
5579 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005580 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5581 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5582 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005583 return false;
5584 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005585 if (media_transport_) {
5586 SendDataParams send_params;
5587 send_params.type = ToWebrtcDataMessageType(params.type);
5588 send_params.ordered = params.ordered;
5589 if (params.max_rtx_count >= 0) {
5590 send_params.max_rtx_count = params.max_rtx_count;
5591 } else if (params.max_rtx_ms >= 0) {
5592 send_params.max_rtx_ms = params.max_rtx_ms;
5593 }
5594 return media_transport_->SendData(params.sid, send_params, payload).ok();
5595 }
Steve Anton75737c02017-11-06 10:37:17 -08005596 return rtp_data_channel_
5597 ? rtp_data_channel_->SendData(params, payload, result)
5598 : network_thread()->Invoke<bool>(
5599 RTC_FROM_HERE,
5600 Bind(&cricket::SctpTransportInternal::SendData,
5601 sctp_transport_.get(), params, payload, result));
5602}
5603
5604bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005605 RTC_DCHECK_RUN_ON(signaling_thread());
5606 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005607 // Don't log an error here, because DataChannels are expected to call
5608 // ConnectDataChannel in this state. It's the only way to initially tell
5609 // whether or not the underlying transport is ready.
5610 return false;
5611 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005612 if (media_transport_) {
5613 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5614 &DataChannel::OnChannelReady);
5615 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5616 &DataChannel::OnDataReceived);
5617 SignalMediaTransportChannelClosing_s.connect(
5618 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5619 SignalMediaTransportChannelClosed_s.connect(
5620 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5621 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005622 rtp_data_channel_->SignalReadyToSendData.connect(
5623 webrtc_data_channel, &DataChannel::OnChannelReady);
5624 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5625 &DataChannel::OnDataReceived);
5626 } else {
5627 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5628 &DataChannel::OnChannelReady);
5629 SignalSctpDataReceived.connect(webrtc_data_channel,
5630 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005631 SignalSctpClosingProcedureStartedRemotely.connect(
5632 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5633 SignalSctpClosingProcedureComplete.connect(
5634 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005635 }
5636 return true;
5637}
5638
5639void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005640 RTC_DCHECK_RUN_ON(signaling_thread());
5641 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005642 RTC_LOG(LS_ERROR)
5643 << "DisconnectDataChannel called when rtp_data_channel_ and "
5644 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005645 return;
5646 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005647 if (media_transport_) {
5648 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5649 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5650 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5651 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5652 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005653 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5654 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5655 } else {
5656 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5657 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005658 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5659 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005660 }
5661}
5662
5663void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005664 if (media_transport_) {
5665 // No-op. Media transport does not need to add streams.
5666 return;
5667 }
Steve Anton75737c02017-11-06 10:37:17 -08005668 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005669 RTC_LOG(LS_ERROR)
5670 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005671 return;
5672 }
5673 network_thread()->Invoke<void>(
5674 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5675 sctp_transport_.get(), sid));
5676}
5677
5678void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005679 if (media_transport_) {
5680 media_transport_->CloseChannel(sid);
5681 return;
5682 }
Steve Anton75737c02017-11-06 10:37:17 -08005683 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005684 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005685 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005686 return;
5687 }
5688 network_thread()->Invoke<void>(
5689 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5690 sctp_transport_.get(), sid));
5691}
5692
5693bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005694 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005695 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005696 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005697 sctp_ready_to_send_data_;
5698}
5699
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005700void PeerConnection::OnDataReceived(int channel_id,
5701 DataMessageType type,
5702 const rtc::CopyOnWriteBuffer& buffer) {
5703 cricket::ReceiveDataParams params;
5704 params.sid = channel_id;
5705 params.type = ToCricketDataMessageType(type);
5706 media_transport_invoker_->AsyncInvoke<void>(
5707 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5708 RTC_DCHECK_RUN_ON(signaling_thread());
5709 if (!HandleOpenMessage_s(params, buffer)) {
5710 SignalMediaTransportReceivedData_s(params, buffer);
5711 }
5712 });
5713}
5714
5715void PeerConnection::OnChannelClosing(int channel_id) {
5716 media_transport_invoker_->AsyncInvoke<void>(
5717 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5718 RTC_DCHECK_RUN_ON(signaling_thread());
5719 SignalMediaTransportChannelClosing_s(channel_id);
5720 });
5721}
5722
5723void PeerConnection::OnChannelClosed(int channel_id) {
5724 media_transport_invoker_->AsyncInvoke<void>(
5725 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5726 RTC_DCHECK_RUN_ON(signaling_thread());
5727 SignalMediaTransportChannelClosed_s(channel_id);
5728 });
5729}
5730
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005731absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005732 if (sctp_mid_ && transport_controller_) {
5733 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5734 if (dtls_transport) {
5735 return dtls_transport->transport_name();
5736 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005737 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005738 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005739 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005740}
5741
Qingsi Wang72a43a12018-02-20 16:03:18 -08005742cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5743 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005744 network_thread()->Invoke<void>(
5745 RTC_FROM_HERE,
5746 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5747 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005748 return candidate_states_list;
5749}
5750
Steve Anton5dfde182018-02-06 10:34:40 -08005751std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5752 const {
5753 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005754 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005755 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005756 if (channel) {
5757 transport_names_by_mid[channel->content_name()] =
5758 channel->transport_name();
5759 }
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
Steve Anton5dfde182018-02-06 10:34:40 -08005761 if (rtp_data_channel_) {
5762 transport_names_by_mid[rtp_data_channel_->content_name()] =
5763 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005764 }
5765 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005766 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005767 RTC_DCHECK(transport_name);
5768 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
Steve Anton5dfde182018-02-06 10:34:40 -08005770 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005771}
5772
Steve Anton5dfde182018-02-06 10:34:40 -08005773std::map<std::string, cricket::TransportStats>
5774PeerConnection::GetTransportStatsByNames(
5775 const std::set<std::string>& transport_names) {
5776 if (!network_thread()->IsCurrent()) {
5777 return network_thread()
5778 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5779 RTC_FROM_HERE,
5780 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005781 }
Steve Anton5dfde182018-02-06 10:34:40 -08005782 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5783 for (const std::string& transport_name : transport_names) {
5784 cricket::TransportStats transport_stats;
5785 bool success =
5786 transport_controller_->GetStats(transport_name, &transport_stats);
5787 if (success) {
5788 transport_stats_by_name[transport_name] = std::move(transport_stats);
5789 } else {
5790 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5791 << transport_name;
5792 }
5793 }
5794 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005795}
5796
5797bool PeerConnection::GetLocalCertificate(
5798 const std::string& transport_name,
5799 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005800 if (!certificate) {
5801 return false;
5802 }
5803 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5804 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005805}
5806
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005807std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005808 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005809 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005810}
5811
5812cricket::DataChannelType PeerConnection::data_channel_type() const {
5813 return data_channel_type_;
5814}
5815
5816bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5817 return pending_ice_restarts_.find(content_name) !=
5818 pending_ice_restarts_.end();
5819}
5820
Steve Anton75737c02017-11-06 10:37:17 -08005821bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5822 return transport_controller_->NeedsIceRestart(content_name);
5823}
5824
5825void PeerConnection::OnCertificateReady(
5826 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5827 transport_controller_->SetLocalCertificate(certificate);
5828}
5829
5830void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005831 SetSessionError(SessionError::kTransport,
5832 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005833}
5834
Alex Loiko9289eda2018-11-23 16:18:59 +00005835void PeerConnection::OnTransportControllerConnectionState(
5836 cricket::IceConnectionState state) {
5837 switch (state) {
5838 case cricket::kIceConnectionConnecting:
5839 // If the current state is Connected or Completed, then there were
5840 // writable channels but now there are not, so the next state must
5841 // be Disconnected.
5842 // kIceConnectionConnecting is currently used as the default,
5843 // un-connected state by the TransportController, so its only use is
5844 // detecting disconnections.
5845 if (ice_connection_state_ ==
5846 PeerConnectionInterface::kIceConnectionConnected ||
5847 ice_connection_state_ ==
5848 PeerConnectionInterface::kIceConnectionCompleted) {
5849 SetIceConnectionState(
5850 PeerConnectionInterface::kIceConnectionDisconnected);
5851 }
5852 break;
5853 case cricket::kIceConnectionFailed:
5854 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5855 break;
5856 case cricket::kIceConnectionConnected:
5857 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5858 "all transports are writable.";
5859 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5860 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5861 break;
5862 case cricket::kIceConnectionCompleted:
5863 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5864 "all transports are complete.";
5865 if (ice_connection_state_ !=
5866 PeerConnectionInterface::kIceConnectionConnected) {
5867 // If jumping directly from "checking" to "connected",
5868 // signal "connected" first.
5869 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5870 }
5871 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5872 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5873 ReportTransportStats();
5874 break;
5875 default:
5876 RTC_NOTREACHED();
5877 }
5878}
5879
Steve Anton75737c02017-11-06 10:37:17 -08005880void PeerConnection::OnTransportControllerCandidatesGathered(
5881 const std::string& transport_name,
5882 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005883 int sdp_mline_index;
5884 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005885 RTC_LOG(LS_ERROR)
5886 << "OnTransportControllerCandidatesGathered: content name "
5887 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005888 return;
5889 }
5890
5891 for (cricket::Candidates::const_iterator citer = candidates.begin();
5892 citer != candidates.end(); ++citer) {
5893 // Use transport_name as the candidate media id.
5894 std::unique_ptr<JsepIceCandidate> candidate(
5895 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5896 if (local_description()) {
5897 mutable_local_description()->AddCandidate(candidate.get());
5898 }
5899 OnIceCandidate(std::move(candidate));
5900 }
5901}
5902
5903void PeerConnection::OnTransportControllerCandidatesRemoved(
5904 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005905 // Sanity check.
5906 for (const cricket::Candidate& candidate : candidates) {
5907 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005908 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005909 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005910 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005911 return;
5912 }
5913 }
5914
5915 if (local_description()) {
5916 mutable_local_description()->RemoveCandidates(candidates);
5917 }
5918 OnIceCandidatesRemoved(candidates);
5919}
5920
5921void PeerConnection::OnTransportControllerDtlsHandshakeError(
5922 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005923 RTC_HISTOGRAM_ENUMERATION(
5924 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5925 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005926}
5927
Steve Antoned10bd92017-12-05 10:52:59 -08005928void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005929 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005930 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005931 if (channel && !channel->enabled()) {
5932 channel->Enable(true);
5933 }
Steve Anton75737c02017-11-06 10:37:17 -08005934 }
5935
Steve Anton4171afb2017-11-20 10:20:22 -08005936 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005937 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005938 }
Steve Anton75737c02017-11-06 10:37:17 -08005939}
5940
5941// Returns the media index for a local ice candidate given the content name.
5942bool PeerConnection::GetLocalCandidateMediaIndex(
5943 const std::string& content_name,
5944 int* sdp_mline_index) {
5945 if (!local_description() || !sdp_mline_index) {
5946 return false;
5947 }
5948
5949 bool content_found = false;
5950 const ContentInfos& contents = local_description()->description()->contents();
5951 for (size_t index = 0; index < contents.size(); ++index) {
5952 if (contents[index].name == content_name) {
5953 *sdp_mline_index = static_cast<int>(index);
5954 content_found = true;
5955 break;
5956 }
5957 }
5958 return content_found;
5959}
5960
5961bool PeerConnection::UseCandidatesInSessionDescription(
5962 const SessionDescriptionInterface* remote_desc) {
5963 if (!remote_desc) {
5964 return true;
5965 }
5966 bool ret = true;
5967
5968 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5969 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5970 for (size_t n = 0; n < candidates->count(); ++n) {
5971 const IceCandidateInterface* candidate = candidates->at(n);
5972 bool valid = false;
5973 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5974 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005975 RTC_LOG(LS_INFO)
5976 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005977 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005978 }
5979 continue;
5980 }
5981 ret = UseCandidate(candidate);
5982 if (!ret) {
5983 break;
5984 }
5985 }
5986 }
5987 return ret;
5988}
5989
5990bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5991 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5992 size_t remote_content_size =
5993 remote_description()->description()->contents().size();
5994 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005995 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005996 return false;
5997 }
5998
5999 cricket::ContentInfo content =
6000 remote_description()->description()->contents()[mediacontent_index];
6001 std::vector<cricket::Candidate> candidates;
6002 candidates.push_back(candidate->candidate());
6003 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006004 RTCError error =
6005 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006006 if (error.ok()) {
6007 // Candidates successfully submitted for checking.
6008 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6009 ice_connection_state_ ==
6010 PeerConnectionInterface::kIceConnectionDisconnected) {
6011 // If state is New, then the session has just gotten its first remote ICE
6012 // candidates, so go to Checking.
6013 // If state is Disconnected, the session is re-using old candidates or
6014 // receiving additional ones, so go to Checking.
6015 // If state is Connected, stay Connected.
6016 // TODO(bemasc): If state is Connected, and the new candidates are for a
6017 // newly added transport, then the state actually _should_ move to
6018 // checking. Add a way to distinguish that case.
6019 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6020 }
6021 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006022 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006023 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006024 }
6025 return true;
6026}
6027
6028void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006029 // Destroy video channel first since it may have a pointer to the
6030 // voice channel.
6031 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006032 if (!video_info || video_info->rejected) {
6033 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006034 }
6035
Steve Anton6fec8802017-12-04 10:37:29 -08006036 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6037 if (!audio_info || audio_info->rejected) {
6038 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006039 }
6040
6041 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6042 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006043 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006044 }
6045}
6046
Steve Antondcc3c022017-12-22 16:02:54 -08006047RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6048 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006049 const cricket::ContentGroup* bundle_group = nullptr;
6050 if (configuration_.bundle_policy ==
6051 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006052 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006053 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006054 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6055 "max-bundle configured but session description "
6056 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006057 }
6058 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006059 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006060}
6061
6062RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006063 // Creating the media channels. Transports should already have been created
6064 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006065 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006066 if (voice && !voice->rejected &&
6067 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006068 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006069 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006070 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6071 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006072 }
6073 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6074 }
6075
Steve Antondcc3c022017-12-22 16:02:54 -08006076 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006077 if (video && !video->rejected &&
6078 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006079 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006080 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006081 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6082 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006083 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006084 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006085 }
6086
Steve Antondcc3c022017-12-22 16:02:54 -08006087 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006088 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006089 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006090 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006091 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6092 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006093 }
6094 }
6095
Steve Anton8a006912017-12-04 15:25:56 -08006096 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006097}
6098
Steve Anton4171afb2017-11-20 10:20:22 -08006099// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006100cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006101 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006102 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006103 MediaTransportInterface* media_transport = nullptr;
6104 if (configuration_.use_media_transport) {
6105 media_transport = GetMediaTransport(mid);
6106 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006107
Steve Anton75737c02017-11-06 10:37:17 -08006108 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006109 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006110 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006111 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006112 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006113 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006114 }
Steve Anton75737c02017-11-06 10:37:17 -08006115 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6116 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006117 voice_channel->SignalSentPacket.connect(this,
6118 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006119 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006120
Steve Antoneda6ccd2017-12-04 10:21:55 -08006121 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006122}
6123
Steve Anton4171afb2017-11-20 10:20:22 -08006124// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006125cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006126 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006127 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006128 MediaTransportInterface* media_transport = nullptr;
6129 if (configuration_.use_media_transport) {
6130 media_transport = GetMediaTransport(mid);
6131 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006132
Steve Anton75737c02017-11-06 10:37:17 -08006133 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006134 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006135 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006136 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006137 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006138 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006139 }
Steve Anton75737c02017-11-06 10:37:17 -08006140 video_channel->SignalDtlsSrtpSetupFailure.connect(
6141 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006142 video_channel->SignalSentPacket.connect(this,
6143 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006144 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006145
Steve Antoneda6ccd2017-12-04 10:21:55 -08006146 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006147}
6148
Zhi Huange830e682018-03-30 10:48:35 -07006149bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006150 switch (data_channel_type_) {
6151 case cricket::DCT_MEDIA_TRANSPORT:
6152 if (network_thread()->Invoke<bool>(
6153 RTC_FROM_HERE,
6154 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6155 this, mid))) {
6156 for (const auto& channel : sctp_data_channels_) {
6157 channel->OnTransportChannelCreated();
6158 }
6159 return true;
6160 }
Steve Anton75737c02017-11-06 10:37:17 -08006161 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006162 case cricket::DCT_SCTP:
6163 if (!sctp_factory_) {
6164 RTC_LOG(LS_ERROR)
6165 << "Trying to create SCTP transport, but didn't compile with "
6166 "SCTP support (HAVE_SCTP)";
6167 return false;
6168 }
6169 if (!network_thread()->Invoke<bool>(
6170 RTC_FROM_HERE,
6171 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6172 return false;
6173 }
6174 for (const auto& channel : sctp_data_channels_) {
6175 channel->OnTransportChannelCreated();
6176 }
6177 return true;
6178 case cricket::DCT_RTP:
6179 default:
6180 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6181 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6182 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006183 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006184 if (!rtp_data_channel_) {
6185 return false;
6186 }
6187 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6188 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6189 rtp_data_channel_->SignalSentPacket.connect(
6190 this, &PeerConnection::OnSentPacket_w);
6191 rtp_data_channel_->SetRtpTransport(rtp_transport);
6192 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006193 }
6194
Steve Anton75737c02017-11-06 10:37:17 -08006195 return true;
6196}
6197
6198Call::Stats PeerConnection::GetCallStats() {
6199 if (!worker_thread()->IsCurrent()) {
6200 return worker_thread()->Invoke<Call::Stats>(
6201 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6202 }
6203 if (call_) {
6204 return call_->GetStats();
6205 } else {
6206 return Call::Stats();
6207 }
6208}
6209
Zhi Huange830e682018-03-30 10:48:35 -07006210bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006211 RTC_DCHECK(network_thread()->IsCurrent());
6212 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006213 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006214 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006215 RTC_DCHECK(dtls_transport);
6216 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006217 RTC_DCHECK(sctp_transport_);
6218 sctp_invoker_.reset(new rtc::AsyncInvoker());
6219 sctp_transport_->SignalReadyToSendData.connect(
6220 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6221 sctp_transport_->SignalDataReceived.connect(
6222 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006223 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6224 // another thread. Would be nice if there was a helper class similar to
6225 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6226 // code.
6227 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6228 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6229 sctp_transport_->SignalClosingProcedureComplete.connect(
6230 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006231 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006232 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006233 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006234}
6235
6236void PeerConnection::DestroySctpTransport_n() {
6237 RTC_DCHECK(network_thread()->IsCurrent());
6238 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006239 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006240 sctp_invoker_.reset(nullptr);
6241 sctp_ready_to_send_data_ = false;
6242}
6243
6244void PeerConnection::OnSctpTransportReadyToSendData_n() {
6245 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6246 RTC_DCHECK(network_thread()->IsCurrent());
6247 // Note: Cannot use rtc::Bind here because it will grab a reference to
6248 // PeerConnection and potentially cause PeerConnection to live longer than
6249 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6250 // be destroyed before PeerConnection is destroyed, and at that point all
6251 // pending tasks will be cleared.
6252 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6253 OnSctpTransportReadyToSendData_s(true);
6254 });
6255}
6256
6257void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6258 RTC_DCHECK(signaling_thread()->IsCurrent());
6259 sctp_ready_to_send_data_ = ready;
6260 SignalSctpReadyToSendData(ready);
6261}
6262
6263void PeerConnection::OnSctpTransportDataReceived_n(
6264 const cricket::ReceiveDataParams& params,
6265 const rtc::CopyOnWriteBuffer& payload) {
6266 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6267 RTC_DCHECK(network_thread()->IsCurrent());
6268 // Note: Cannot use rtc::Bind here because it will grab a reference to
6269 // PeerConnection and potentially cause PeerConnection to live longer than
6270 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6271 // be destroyed before PeerConnection is destroyed, and at that point all
6272 // pending tasks will be cleared.
6273 sctp_invoker_->AsyncInvoke<void>(
6274 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6275 OnSctpTransportDataReceived_s(params, payload);
6276 });
6277}
6278
6279void PeerConnection::OnSctpTransportDataReceived_s(
6280 const cricket::ReceiveDataParams& params,
6281 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006282 RTC_DCHECK_RUN_ON(signaling_thread());
6283 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006284 SignalSctpDataReceived(params, payload);
6285 }
6286}
6287
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006288void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006289 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6290 RTC_DCHECK(network_thread()->IsCurrent());
6291 sctp_invoker_->AsyncInvoke<void>(
6292 RTC_FROM_HERE, signaling_thread(),
6293 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006294 &SignalSctpClosingProcedureStartedRemotely, sid));
6295}
6296
6297void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6298 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6299 RTC_DCHECK(network_thread()->IsCurrent());
6300 sctp_invoker_->AsyncInvoke<void>(
6301 RTC_FROM_HERE, signaling_thread(),
6302 rtc::Bind(&sigslot::signal1<int>::operator(),
6303 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006304}
6305
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006306bool PeerConnection::SetupMediaTransportForDataChannels_n(
6307 const std::string& mid) {
6308 media_transport_ = transport_controller_->GetMediaTransport(mid);
6309 if (!media_transport_) {
6310 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6311 return false;
6312 }
6313
6314 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6315 media_transport_->SetDataSink(this);
6316 media_transport_data_mid_ = mid;
6317 transport_controller_->SignalMediaTransportStateChanged.connect(
6318 this, &PeerConnection::OnMediaTransportStateChanged_n);
6319 // Check the initial state right away, in case transport is already writable.
6320 OnMediaTransportStateChanged_n();
6321 return true;
6322}
6323
6324void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6325 if (!media_transport_) {
6326 return;
6327 }
6328 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6329 media_transport_data_mid_.reset();
6330 media_transport_->SetDataSink(nullptr);
6331 media_transport_invoker_ = nullptr;
6332 media_transport_ = nullptr;
6333}
6334
6335void PeerConnection::OnMediaTransportStateChanged_n() {
6336 if (!media_transport_data_mid_ ||
6337 transport_controller_->GetMediaTransportState(
6338 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6339 return;
6340 }
6341 media_transport_invoker_->AsyncInvoke<void>(
6342 RTC_FROM_HERE, signaling_thread(), [this] {
6343 RTC_DCHECK_RUN_ON(signaling_thread());
6344 media_transport_ready_to_send_data_ = true;
6345 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6346 });
6347}
6348
Steve Anton75737c02017-11-06 10:37:17 -08006349// Returns false if bundle is enabled and rtcp_mux is disabled.
6350bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6351 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6352 if (!bundle_enabled)
6353 return true;
6354
6355 const cricket::ContentGroup* bundle_group =
6356 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6357 RTC_DCHECK(bundle_group != NULL);
6358
6359 const cricket::ContentInfos& contents = desc->contents();
6360 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6361 citer != contents.end(); ++citer) {
6362 const cricket::ContentInfo* content = (&*citer);
6363 RTC_DCHECK(content != NULL);
6364 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006365 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006366 if (!HasRtcpMuxEnabled(content))
6367 return false;
6368 }
6369 }
6370 // RTCP-MUX is enabled in all the contents.
6371 return true;
6372}
6373
6374bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006375 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006376}
6377
Steve Anton06817cd2018-12-18 15:55:30 -08006378static RTCError ValidateMids(const cricket::SessionDescription& description) {
6379 std::set<std::string> mids;
6380 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006381 if (content.name.empty()) {
6382 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6383 "A media section is missing a MID attribute.");
6384 }
Steve Anton06817cd2018-12-18 15:55:30 -08006385 if (!mids.insert(content.name).second) {
6386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6387 "Duplicate a=mid value '" + content.name + "'.");
6388 }
6389 }
6390 return RTCError::OK();
6391}
6392
Steve Anton8a006912017-12-04 15:25:56 -08006393RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006394 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006395 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006396 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006397 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006398 }
6399
6400 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006401 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006402 }
6403
Steve Anton3828c062017-12-06 10:34:51 -08006404 SdpType type = sdesc->GetType();
6405 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6406 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006407 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006408 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006409 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006410 }
6411
Steve Anton06817cd2018-12-18 15:55:30 -08006412 RTCError error = ValidateMids(*sdesc->description());
6413 if (!error.ok()) {
6414 return error;
6415 }
6416
Steve Anton75737c02017-11-06 10:37:17 -08006417 // Verify crypto settings.
6418 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006419 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6420 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006421 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006422 if (!crypto_error.ok()) {
6423 return crypto_error;
6424 }
Steve Anton75737c02017-11-06 10:37:17 -08006425 }
6426
6427 // Verify ice-ufrag and ice-pwd.
6428 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006429 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6430 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006431 }
6432
6433 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006434 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6435 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006436 }
6437
6438 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6439 // m-lines that do not rtcp-mux enabled.
6440
6441 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006442 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006443 // With an answer we want to compare the new answer session description with
6444 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006445 const cricket::SessionDescription* offer_desc =
6446 (source == cricket::CS_LOCAL) ? remote_description()->description()
6447 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006448 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6449 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6450 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6452 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006453 }
6454 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006455 // The re-offers should respect the order of m= sections in current
6456 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006457 // With a re-offer, either the current local or current remote descriptions
6458 // could be the most up to date, so we would like to check against both of
6459 // them if they exist. It could be the case that one of them has a 0 port
6460 // for a media section, but the other does not. This is important to check
6461 // against in the case that we are recycling an m= section.
6462 const cricket::SessionDescription* current_desc = nullptr;
6463 const cricket::SessionDescription* secondary_current_desc = nullptr;
6464 if (local_description()) {
6465 current_desc = local_description()->description();
6466 if (remote_description()) {
6467 secondary_current_desc = remote_description()->description();
6468 }
6469 } else if (remote_description()) {
6470 current_desc = remote_description()->description();
6471 }
Steve Anton75737c02017-11-06 10:37:17 -08006472 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006473 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6474 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006475 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6476 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006477 }
6478 }
6479
Steve Antonba42e992018-04-09 14:10:01 -07006480 if (IsUnifiedPlan()) {
6481 // Ensure that each audio and video media section has at most one
6482 // "StreamParams". This will return an error if receiving a session
6483 // description from a "Plan B" endpoint which adds multiple tracks of the
6484 // same type. With Unified Plan, there can only be at most one track per
6485 // media section.
6486 for (const ContentInfo& content : sdesc->description()->contents()) {
6487 const MediaContentDescription& desc = *content.description;
6488 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6489 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6490 desc.streams().size() > 1u) {
6491 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6492 "Media section has more than one track specified "
6493 "with a=ssrc lines which is not supported with "
6494 "Unified Plan.");
6495 }
6496 }
6497 }
6498
Steve Anton8a006912017-12-04 15:25:56 -08006499 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006500}
6501
Steve Anton3828c062017-12-06 10:34:51 -08006502bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006503 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006504 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006505 return (state == PeerConnectionInterface::kStable) ||
6506 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006507 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006508 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006509 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6510 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6511 }
6512}
6513
Steve Anton3828c062017-12-06 10:34:51 -08006514bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006515 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006516 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006517 return (state == PeerConnectionInterface::kStable) ||
6518 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006519 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006520 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006521 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6522 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6523 }
6524}
6525
Steve Antonf8470812017-12-04 10:46:21 -08006526const char* PeerConnection::SessionErrorToString(SessionError error) const {
6527 switch (error) {
6528 case SessionError::kNone:
6529 return "ERROR_NONE";
6530 case SessionError::kContent:
6531 return "ERROR_CONTENT";
6532 case SessionError::kTransport:
6533 return "ERROR_TRANSPORT";
6534 }
6535 RTC_NOTREACHED();
6536 return "";
6537}
6538
Steve Anton75737c02017-11-06 10:37:17 -08006539std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006540 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006541 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6542 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006543 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006544}
6545
Steve Anton8e20f172018-03-06 10:55:04 -08006546void PeerConnection::ReportSdpFormatReceived(
6547 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006548 int num_audio_mlines = 0;
6549 int num_video_mlines = 0;
6550 int num_audio_tracks = 0;
6551 int num_video_tracks = 0;
6552 for (const ContentInfo& content : remote_offer.description()->contents()) {
6553 cricket::MediaType media_type = content.media_description()->type();
6554 int num_tracks = std::max(
6555 1, static_cast<int>(content.media_description()->streams().size()));
6556 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6557 num_audio_mlines += 1;
6558 num_audio_tracks += num_tracks;
6559 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6560 num_video_mlines += 1;
6561 num_video_tracks += num_tracks;
6562 }
6563 }
6564 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6565 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6566 format = kSdpFormatReceivedComplexUnifiedPlan;
6567 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6568 format = kSdpFormatReceivedComplexPlanB;
6569 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6570 format = kSdpFormatReceivedSimple;
6571 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006572 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6573 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006574}
6575
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006576void PeerConnection::NoteUsageEvent(UsageEvent event) {
6577 RTC_DCHECK_RUN_ON(signaling_thread());
6578 usage_event_accumulator_ |= static_cast<int>(event);
6579}
6580
6581void PeerConnection::ReportUsagePattern() const {
6582 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006583 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6584 usage_event_accumulator_,
6585 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006586 const int bad_bits =
6587 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6588 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6589 const int good_bits =
6590 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6591 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6592 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6593 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6594 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006595 // If called after close(), we can't report, because observer may have
6596 // been deallocated, and therefore pointer is null. Write to log instead.
6597 if (observer_) {
6598 Observer()->OnInterestingUsage(usage_event_accumulator_);
6599 } else {
6600 RTC_LOG(LS_INFO) << "Interesting usage signature "
6601 << usage_event_accumulator_
6602 << " observed after observer shutdown";
6603 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006604 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006605}
6606
Steve Anton0ffaaa22018-02-23 10:31:30 -08006607void PeerConnection::ReportNegotiatedSdpSemantics(
6608 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006609 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006610 switch (answer.description()->msid_signaling()) {
6611 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006612 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006613 break;
6614 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006615 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006616 break;
6617 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006618 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006619 break;
6620 case cricket::kMsidSignalingMediaSection |
6621 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006622 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006623 break;
6624 default:
6625 RTC_NOTREACHED();
6626 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006627 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6628 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006629}
6630
Steve Anton75737c02017-11-06 10:37:17 -08006631// We need to check the local/remote description for the Transport instead of
6632// the session, because a new Transport added during renegotiation may have
6633// them unset while the session has them set from the previous negotiation.
6634// Not doing so may trigger the auto generation of transport description and
6635// mess up DTLS identity information, ICE credential, etc.
6636bool PeerConnection::ReadyToUseRemoteCandidate(
6637 const IceCandidateInterface* candidate,
6638 const SessionDescriptionInterface* remote_desc,
6639 bool* valid) {
6640 *valid = true;
6641
6642 const SessionDescriptionInterface* current_remote_desc =
6643 remote_desc ? remote_desc : remote_description();
6644
6645 if (!current_remote_desc) {
6646 return false;
6647 }
6648
6649 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6650 size_t remote_content_size =
6651 current_remote_desc->description()->contents().size();
6652 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006653 RTC_LOG(LS_ERROR)
6654 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6655 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006656
6657 *valid = false;
6658 return false;
6659 }
6660
6661 cricket::ContentInfo content =
6662 current_remote_desc->description()->contents()[mediacontent_index];
6663
6664 const std::string transport_name = GetTransportName(content.name);
6665 if (transport_name.empty()) {
6666 return false;
6667 }
Zhi Huange830e682018-03-30 10:48:35 -07006668 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006669}
6670
6671bool PeerConnection::SrtpRequired() const {
6672 return dtls_enabled_ ||
6673 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6674}
6675
6676void PeerConnection::OnTransportControllerGatheringState(
6677 cricket::IceGatheringState state) {
6678 RTC_DCHECK(signaling_thread()->IsCurrent());
6679 if (state == cricket::kIceGatheringGathering) {
6680 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6681 } else if (state == cricket::kIceGatheringComplete) {
6682 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6683 }
6684}
6685
6686void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006687 std::map<std::string, std::set<cricket::MediaType>>
6688 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006689 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006690 if (transceiver->internal()->channel()) {
6691 const std::string& transport_name =
6692 transceiver->internal()->channel()->transport_name();
6693 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006694 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006695 }
Steve Anton75737c02017-11-06 10:37:17 -08006696 }
6697 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006698 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6699 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006700 }
Zhi Huange830e682018-03-30 10:48:35 -07006701
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006702 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006703 if (transport_name) {
6704 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006705 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006706 }
Zhi Huange830e682018-03-30 10:48:35 -07006707
Steve Antonc7b964c2018-02-01 14:39:45 -08006708 for (const auto& entry : media_types_by_transport_name) {
6709 const std::string& transport_name = entry.first;
6710 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006711 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006712 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006713 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006714 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006715 }
6716 }
6717}
6718// Walk through the ConnectionInfos to gather best connection usage
6719// for IPv4 and IPv6.
6720void PeerConnection::ReportBestConnectionState(
6721 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006722 for (const cricket::TransportChannelStats& channel_stats :
6723 stats.channel_stats) {
6724 for (const cricket::ConnectionInfo& connection_info :
6725 channel_stats.connection_infos) {
6726 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006727 continue;
6728 }
6729
Steve Antonc7b964c2018-02-01 14:39:45 -08006730 const cricket::Candidate& local = connection_info.local_candidate;
6731 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006732
6733 // Increment the counter for IceCandidatePairType.
6734 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6735 (local.type() == RELAY_PORT_TYPE &&
6736 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006737 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6738 GetIceCandidatePairCounter(local, remote),
6739 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006740 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006741 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6742 GetIceCandidatePairCounter(local, remote),
6743 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006744 } else {
6745 RTC_CHECK(0);
6746 }
Steve Anton75737c02017-11-06 10:37:17 -08006747
6748 // Increment the counter for IP type.
6749 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006750 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6751 kBestConnections_IPv4,
6752 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006753 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006754 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6755 kBestConnections_IPv6,
6756 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006757 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006758 RTC_CHECK(!local.address().hostname().empty() &&
6759 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006760 }
6761
6762 return;
6763 }
6764 }
6765}
6766
6767void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006768 const cricket::TransportStats& stats,
6769 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006770 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6771 return;
6772 }
6773
6774 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6775 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6776 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6777 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6778 return;
6779 }
6780
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006781 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6782 for (cricket::MediaType media_type : media_types) {
6783 switch (media_type) {
6784 case cricket::MEDIA_TYPE_AUDIO:
6785 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6786 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6787 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6788 break;
6789 case cricket::MEDIA_TYPE_VIDEO:
6790 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6791 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6792 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6793 break;
6794 case cricket::MEDIA_TYPE_DATA:
6795 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6796 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6797 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6798 break;
6799 default:
6800 RTC_NOTREACHED();
6801 continue;
6802 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006803 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006804 }
6805
6806 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6807 for (cricket::MediaType media_type : media_types) {
6808 switch (media_type) {
6809 case cricket::MEDIA_TYPE_AUDIO:
6810 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6811 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6812 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6813 break;
6814 case cricket::MEDIA_TYPE_VIDEO:
6815 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6816 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6817 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6818 break;
6819 case cricket::MEDIA_TYPE_DATA:
6820 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6821 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6822 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6823 break;
6824 default:
6825 RTC_NOTREACHED();
6826 continue;
6827 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006828 }
Steve Anton75737c02017-11-06 10:37:17 -08006829 }
6830}
6831
6832void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6833 RTC_DCHECK(worker_thread()->IsCurrent());
6834 RTC_DCHECK(call_);
6835 call_->OnSentPacket(sent_packet);
6836}
6837
6838const std::string PeerConnection::GetTransportName(
6839 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006840 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006841 if (channel) {
6842 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006843 }
Steve Anton6fec8802017-12-04 10:37:29 -08006844 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006845 RTC_DCHECK(sctp_mid_);
6846 if (content_name == *sctp_mid_) {
6847 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006848 }
6849 }
6850 // Return an empty string if failed to retrieve the transport name.
6851 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006852}
6853
Steve Anton6fec8802017-12-04 10:37:29 -08006854void PeerConnection::DestroyTransceiverChannel(
6855 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6856 transceiver) {
6857 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006858
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006859 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006860 if (channel) {
6861 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006862 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006863 }
6864}
6865
6866void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006867 if (rtp_data_channel_) {
6868 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006869 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006870 rtp_data_channel_ = nullptr;
6871 }
6872
6873 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6874 // grab a reference to this PeerConnection. If this is called from the
6875 // PeerConnection destructor, the RefCountedObject vtable will have already
6876 // been destroyed (since it is a subclass of PeerConnection) and using
6877 // rtc::Bind will cause "Pure virtual function called" error to appear.
6878
6879 if (sctp_transport_) {
6880 OnDataChannelDestroyed();
6881 network_thread()->Invoke<void>(RTC_FROM_HERE,
6882 [this] { DestroySctpTransport_n(); });
6883 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006884
6885 if (media_transport_) {
6886 OnDataChannelDestroyed();
6887 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6888 RTC_DCHECK_RUN_ON(network_thread());
6889 TeardownMediaTransportForDataChannels_n();
6890 });
6891 }
Steve Anton6fec8802017-12-04 10:37:29 -08006892}
6893
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006894void PeerConnection::DestroyChannelInterface(
6895 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006896 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006897 switch (channel->media_type()) {
6898 case cricket::MEDIA_TYPE_AUDIO:
6899 channel_manager()->DestroyVoiceChannel(
6900 static_cast<cricket::VoiceChannel*>(channel));
6901 break;
6902 case cricket::MEDIA_TYPE_VIDEO:
6903 channel_manager()->DestroyVideoChannel(
6904 static_cast<cricket::VideoChannel*>(channel));
6905 break;
6906 case cricket::MEDIA_TYPE_DATA:
6907 channel_manager()->DestroyRtpDataChannel(
6908 static_cast<cricket::RtpDataChannel*>(channel));
6909 break;
6910 default:
6911 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6912 break;
6913 }
Zhi Huange830e682018-03-30 10:48:35 -07006914}
Steve Anton6fec8802017-12-04 10:37:29 -08006915
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006916bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006917 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006918 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006919 cricket::DtlsTransportInternal* dtls_transport,
6920 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006921 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006922 auto base_channel = GetChannel(mid);
6923 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006924 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006925 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006926 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006927 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006928 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006929
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006930 if (configuration_.use_media_transport) {
6931 // Only pass media transport to call object if media transport is used
6932 // for media (and not data channel).
6933 call_->MediaTransportChange(media_transport);
6934 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006935
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006936 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006937}
6938
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006939PeerConnectionObserver* PeerConnection::Observer() const {
6940 // In earlier production code, the pointer was not cleared on close,
6941 // which might have led to undefined behavior if the observer was not
6942 // deallocated, or strange crashes if it was.
6943 // We use CHECK in order to catch such behavior if it exists.
6944 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6945 RTC_CHECK(observer_);
6946 return observer_;
6947}
6948
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006949CryptoOptions PeerConnection::GetCryptoOptions() {
6950 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6951 // after it has been removed.
6952 return configuration_.crypto_options.has_value()
6953 ? *configuration_.crypto_options
6954 : factory_->options().crypto_options;
6955}
6956
Harald Alvestrand89061872018-01-02 14:08:34 +01006957void PeerConnection::ClearStatsCache() {
6958 if (stats_collector_) {
6959 stats_collector_->ClearCachedStatsReport();
6960 }
6961}
6962
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006963void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006964 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6965 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006966}
6967
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006968} // namespace webrtc