blob: 8ac1e8354332e71afeb12996488742ce2d630908 [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"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
28#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020032#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070034#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010036#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080037#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080038#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "pc/channel_manager.h"
40#include "pc/dtmf_sender.h"
41#include "pc/media_stream.h"
42#include "pc/media_stream_observer.h"
43#include "pc/remote_audio_source.h"
44#include "pc/rtp_media_utils.h"
45#include "pc/rtp_receiver.h"
46#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010047#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "pc/sctp_utils.h"
49#include "pc/sdp_utils.h"
50#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010051#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080052#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#include "rtc_base/bind.h"
54#include "rtc_base/checks.h"
55#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010056#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070062#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080073using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080074using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080075using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
78using cricket::STUN_PORT_TYPE;
79using cricket::RELAY_PORT_TYPE;
80using cricket::PRFLX_PORT_TYPE;
81
Steve Antonba818672017-11-06 10:21:57 -080082namespace webrtc {
83
Steve Anton75737c02017-11-06 10:37:17 -080084// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080088const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080096const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
Steve Anton75737c02017-11-06 10:37:17 -0800108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800110// UMA metric names.
111const char kSimulcastVersionApplyLocalDescription[] =
112 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
113const char kSimulcastVersionApplyRemoteDescription[] =
114 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
115const char kSimulcastNumberOfEncodings[] =
116 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
117const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
118
Seth Hampson845e8782018-03-02 11:34:10 -0800119static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800120static const char kDefaultAudioSenderId[] = "defaulta0";
121static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700122
zhihuang8f65cdf2016-05-06 18:40:30 -0700123// The length of RTCP CNAMEs.
124static const int kRtcpCnameLength = 16;
125
Steve Antonad182762018-09-05 20:22:40 +0000126enum {
127 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
128 MSG_SET_SESSIONDESCRIPTION_FAILED,
129 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
130 MSG_GETSTATS,
131 MSG_FREE_DATACHANNELS,
132 MSG_REPORT_USAGE_PATTERN,
133};
134
Harald Alvestrand19793842018-06-25 12:03:50 +0200135static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
136
Steve Antonad182762018-09-05 20:22:40 +0000137struct SetSessionDescriptionMsg : public rtc::MessageData {
138 explicit SetSessionDescriptionMsg(
139 webrtc::SetSessionDescriptionObserver* observer)
140 : observer(observer) {}
141
142 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
143 RTCError error;
144};
145
146struct CreateSessionDescriptionMsg : public rtc::MessageData {
147 explicit CreateSessionDescriptionMsg(
148 webrtc::CreateSessionDescriptionObserver* observer)
149 : observer(observer) {}
150
151 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
152 RTCError error;
153};
154
155struct GetStatsMsg : public rtc::MessageData {
156 GetStatsMsg(webrtc::StatsObserver* observer,
157 webrtc::MediaStreamTrackInterface* track)
158 : observer(observer), track(track) {}
159 rtc::scoped_refptr<webrtc::StatsObserver> observer;
160 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
161};
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163// Check if we can send |new_stream| on a PeerConnection.
164bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
165 webrtc::MediaStreamInterface* new_stream) {
166 if (!new_stream || !current_streams) {
167 return false;
168 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700169 if (current_streams->find(new_stream->id()) != nullptr) {
170 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100171 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700172 return false;
173 }
174 return true;
175}
176
deadbeef5e97fb52015-10-15 12:49:08 -0700177// If the direction is "recvonly" or "inactive", treat the description
178// as containing no streams.
179// See: https://code.google.com/p/webrtc/issues/detail?id=5054
180std::vector<cricket::StreamParams> GetActiveStreams(
181 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800182 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700183 ? desc->streams()
184 : std::vector<cricket::StreamParams>();
185}
186
deadbeefab9b2d12015-10-14 11:33:11 -0700187bool IsValidOfferToReceiveMedia(int value) {
188 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
189 return (value >= Options::kUndefined) &&
190 (value <= Options::kMaxOfferToReceiveMedia);
191}
192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800194void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700195 const std::vector<rtc::scoped_refptr<
196 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700197 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200198 cricket::MediaDescriptionOptions* video_media_description_options,
199 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700200 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700201 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
202 if (audio_media_description_options) {
203 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700204 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700205 }
206 } else {
207 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
208 if (video_media_description_options) {
209 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800210 sender->id(), sender->internal()->stream_ids(), {},
211 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700212 }
213 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700214 }
zhihuang1c378ed2017-08-17 14:10:50 -0700215}
olka3c747662017-08-17 06:50:32 -0700216
zhihuang1c378ed2017-08-17 14:10:50 -0700217// Add options to |session_options| from |rtp_data_channels|.
218void AddRtpDataChannelOptions(
219 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
220 rtp_data_channels,
221 cricket::MediaDescriptionOptions* data_media_description_options) {
222 if (!data_media_description_options) {
223 return;
224 }
deadbeefab9b2d12015-10-14 11:33:11 -0700225 // Check for data channels.
226 for (const auto& kv : rtp_data_channels) {
227 const DataChannel* channel = kv.second;
228 if (channel->state() == DataChannel::kConnecting ||
229 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700230 // Legacy RTP data channels are signaled with the track/stream ID set to
231 // the data channel's label.
232 data_media_description_options->AddRtpDataChannel(channel->label(),
233 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700234 }
235 }
236}
237
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238uint32_t ConvertIceTransportTypeToCandidateFilter(
239 PeerConnectionInterface::IceTransportsType type) {
240 switch (type) {
241 case PeerConnectionInterface::kNone:
242 return cricket::CF_NONE;
243 case PeerConnectionInterface::kRelay:
244 return cricket::CF_RELAY;
245 case PeerConnectionInterface::kNoHost:
246 return (cricket::CF_ALL & ~cricket::CF_HOST);
247 case PeerConnectionInterface::kAll:
248 return cricket::CF_ALL;
249 default:
nissec80e7412017-01-11 05:56:46 -0800250 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700251 }
252 return cricket::CF_NONE;
253}
254
deadbeef293e9262017-01-11 12:28:30 -0800255// Helper to set an error and return from a method.
256bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
257 if (error) {
258 error->set_type(type);
259 }
260 return type == webrtc::RTCErrorType::NONE;
261}
262
Steve Anton038834f2017-07-14 15:59:59 -0700263bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700264 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700265 if (error_out) {
266 *error_out = std::move(error);
267 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700269}
270
Steve Antonba818672017-11-06 10:21:57 -0800271std::string GetSignalingStateString(
272 PeerConnectionInterface::SignalingState state) {
273 switch (state) {
274 case PeerConnectionInterface::kStable:
275 return "kStable";
276 case PeerConnectionInterface::kHaveLocalOffer:
277 return "kHaveLocalOffer";
278 case PeerConnectionInterface::kHaveLocalPrAnswer:
279 return "kHavePrAnswer";
280 case PeerConnectionInterface::kHaveRemoteOffer:
281 return "kHaveRemoteOffer";
282 case PeerConnectionInterface::kHaveRemotePrAnswer:
283 return "kHaveRemotePrAnswer";
284 case PeerConnectionInterface::kClosed:
285 return "kClosed";
286 }
287 RTC_NOTREACHED();
288 return "";
289}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290
Steve Anton75737c02017-11-06 10:37:17 -0800291IceCandidatePairType GetIceCandidatePairCounter(
292 const cricket::Candidate& local,
293 const cricket::Candidate& remote) {
294 const auto& l = local.type();
295 const auto& r = remote.type();
296 const auto& host = LOCAL_PORT_TYPE;
297 const auto& srflx = STUN_PORT_TYPE;
298 const auto& relay = RELAY_PORT_TYPE;
299 const auto& prflx = PRFLX_PORT_TYPE;
300 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800301 bool local_hostname =
302 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
303 bool remote_hostname = !remote.address().hostname().empty() &&
304 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800305 bool local_private = IPIsPrivate(local.address().ipaddr());
306 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800307 if (local_hostname) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostNameHostName;
310 } else if (remote_private) {
311 return kIceCandidatePairHostNameHostPrivate;
312 } else {
313 return kIceCandidatePairHostNameHostPublic;
314 }
315 } else if (local_private) {
316 if (remote_hostname) {
317 return kIceCandidatePairHostPrivateHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPrivateHostPrivate;
320 } else {
321 return kIceCandidatePairHostPrivateHostPublic;
322 }
323 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800324 if (remote_hostname) {
325 return kIceCandidatePairHostPublicHostName;
326 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800327 return kIceCandidatePairHostPublicHostPrivate;
328 } else {
329 return kIceCandidatePairHostPublicHostPublic;
330 }
331 }
332 }
333 if (l == host && r == srflx)
334 return kIceCandidatePairHostSrflx;
335 if (l == host && r == relay)
336 return kIceCandidatePairHostRelay;
337 if (l == host && r == prflx)
338 return kIceCandidatePairHostPrflx;
339 if (l == srflx && r == host)
340 return kIceCandidatePairSrflxHost;
341 if (l == srflx && r == srflx)
342 return kIceCandidatePairSrflxSrflx;
343 if (l == srflx && r == relay)
344 return kIceCandidatePairSrflxRelay;
345 if (l == srflx && r == prflx)
346 return kIceCandidatePairSrflxPrflx;
347 if (l == relay && r == host)
348 return kIceCandidatePairRelayHost;
349 if (l == relay && r == srflx)
350 return kIceCandidatePairRelaySrflx;
351 if (l == relay && r == relay)
352 return kIceCandidatePairRelayRelay;
353 if (l == relay && r == prflx)
354 return kIceCandidatePairRelayPrflx;
355 if (l == prflx && r == host)
356 return kIceCandidatePairPrflxHost;
357 if (l == prflx && r == srflx)
358 return kIceCandidatePairPrflxSrflx;
359 if (l == prflx && r == relay)
360 return kIceCandidatePairPrflxRelay;
361 return kIceCandidatePairMax;
362}
363
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800364// Logic to decide if an m= section can be recycled. This means that the new
365// m= section is not rejected, but the old local or remote m= section is
366// rejected. |old_content_one| and |old_content_two| refer to the m= section
367// of the old remote and old local descriptions in no particular order.
368// We need to check both the old local and remote because either
369// could be the most current from the latest negotation.
370bool IsMediaSectionBeingRecycled(SdpType type,
371 const ContentInfo& content,
372 const ContentInfo* old_content_one,
373 const ContentInfo* old_content_two) {
374 return type == SdpType::kOffer && !content.rejected &&
375 ((old_content_one && old_content_one->rejected) ||
376 (old_content_two && old_content_two->rejected));
377}
378
Steve Anton75737c02017-11-06 10:37:17 -0800379// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380// |current_desc|. The number of m= sections in |new_desc| should be no
381// less than |current_desc|. In the case of checking an answer's
382// |new_desc|, the |current_desc| is the last offer that was set as the
383// local or remote. In the case of checking an offer's |new_desc| we
384// check against the local and remote descriptions stored from the last
385// negotiation, because either of these could be the most up to date for
386// possible rejected m sections. These are the |current_desc| and
387// |secondary_current_desc|.
388bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
389 const SessionDescription* secondary_current_desc,
390 const SessionDescription& new_desc,
391 const SdpType type) {
392 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800393 return false;
394 }
395
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
397 const cricket::ContentInfo* secondary_content_info = nullptr;
398 if (secondary_current_desc &&
399 i < secondary_current_desc->contents().size()) {
400 secondary_content_info = &secondary_current_desc->contents()[i];
401 }
402 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
403 &current_desc.contents()[i],
404 secondary_content_info)) {
405 // For new offer descriptions, if the media section can be recycled, it's
406 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800407 continue;
408 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800409 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800410 return false;
411 }
412 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 new_desc.contents()[i].media_description();
414 const MediaContentDescription* current_desc_mdesc =
415 current_desc.contents()[i].media_description();
416 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800417 return false;
418 }
419 }
420 return true;
421}
422
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800423bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
424 const SessionDescription& desc2) {
425 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800426}
427
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700428void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
429 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200430 // Array of structs needed to map {KeyExchangeProtocolType,
431 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
432 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
433 static constexpr struct {
434 KeyExchangeProtocolType protocol_type;
435 cricket::MediaType media_type;
436 KeyExchangeProtocolMedia protocol_media;
437 } kEnumCounterKeyProtocolMediaMap[] = {
438 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
439 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
440 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
441 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
443 kEnumCounterKeyProtocolMediaTypeDtlsData},
444 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
445 kEnumCounterKeyProtocolMediaTypeSdesAudio},
446 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
447 kEnumCounterKeyProtocolMediaTypeSdesVideo},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
449 kEnumCounterKeyProtocolMediaTypeSdesData},
450 };
451
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
453 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100454
Mirko Bonadeiab499822018-09-11 10:43:20 +0200455 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
456 if (i.protocol_type == protocol_type && i.media_type == media_type) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
458 i.protocol_media,
459 kEnumCounterKeyProtocolMediaTypeMax);
460 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100461 }
462}
463
Harald Alvestrand76829d72018-07-18 23:24:36 +0200464void NoteAddIceCandidateResult(int result) {
465 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
466 kAddIceCandidateMax);
467}
468
Steve Anton75737c02017-11-06 10:37:17 -0800469// Checks that each non-rejected content has SDES crypto keys or a DTLS
470// fingerprint, unless it's in a BUNDLE group, in which case only the
471// BUNDLE-tag section (first media section/description in the BUNDLE group)
472// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
473// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
474// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700475RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100482 // Note what media is used with each crypto protocol, for all sections.
483 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
484 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700485 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800486 const std::string& mid = content_info.name;
487 if (bundle && bundle->HasContentName(mid) &&
488 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800489 // This isn't the first media section in the BUNDLE group, so it's not
490 // required to have crypto attributes, since only the crypto attributes
491 // from the first section actually get used.
492 continue;
493 }
494
495 // If the content isn't rejected or bundled into another m= section, crypto
496 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800498 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800499 if (!media || !tinfo) {
500 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 if (dtls_enabled) {
504 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
506 << "Session description must have DTLS fingerprint if "
507 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800508 return RTCError(RTCErrorType::INVALID_PARAMETER,
509 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800510 }
511 } else {
512 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100513 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800514 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800515 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800516 }
517 }
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800520}
521
522// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
523// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
524// media section/description in the BUNDLE group) needs a ufrag and pwd.
525bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
526 const cricket::ContentGroup* bundle =
527 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800528 for (const cricket::ContentInfo& content_info : desc->contents()) {
529 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800530 continue;
531 }
Steve Anton8a006912017-12-04 15:25:56 -0800532 const std::string& mid = content_info.name;
533 if (bundle && bundle->HasContentName(mid) &&
534 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800535 // This isn't the first media section in the BUNDLE group, so it's not
536 // required to have ufrag/password, since only the ufrag/password from
537 // the first section actually get used.
538 continue;
539 }
540
541 // If the content isn't rejected or bundled into another m= section,
542 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800543 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800544 if (!tinfo) {
545 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800547 return false;
548 }
549 if (tinfo->description.ice_ufrag.empty() ||
550 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100551 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800552 return false;
553 }
554 }
555 return true;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Get the SCTP port out of a SessionDescription.
559// Return -1 if not found.
560int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800561 const cricket::DataContentDescription* data_desc =
562 GetFirstDataContentDescription(session_description);
563 RTC_DCHECK(data_desc);
564 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800565 return -1;
566 }
Steve Anton75737c02017-11-06 10:37:17 -0800567 std::string value;
568 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
569 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800570 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800571 if (!codec.Matches(match_pattern)) {
572 continue;
573 }
574 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
575 return rtc::FromString<int>(value);
576 }
577 }
578 return -1;
579}
580
Steve Anton75737c02017-11-06 10:37:17 -0800581// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
582bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
583 const SessionDescriptionInterface* new_desc,
584 const std::string& content_name) {
585 if (!old_desc) {
586 return false;
587 }
588 const SessionDescription* new_sd = new_desc->description();
589 const SessionDescription* old_sd = old_desc->description();
590 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
591 if (!cinfo || cinfo->rejected) {
592 return false;
593 }
594 // If the content isn't rejected, check if ufrag and password has changed.
595 const cricket::TransportDescription* new_transport_desc =
596 new_sd->GetTransportDescriptionByName(content_name);
597 const cricket::TransportDescription* old_transport_desc =
598 old_sd->GetTransportDescriptionByName(content_name);
599 if (!new_transport_desc || !old_transport_desc) {
600 // No transport description exists. This is not an ICE restart.
601 return false;
602 }
603 if (cricket::IceCredentialsChanged(
604 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
605 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100606 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
607 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800608 return true;
609 }
610 return false;
611}
612
Steve Anton80dd7b52018-02-16 17:08:42 -0800613// Generates a string error message for SetLocalDescription/SetRemoteDescription
614// from an RTCError.
615std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
616 SdpType type,
617 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200618 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800619 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
620 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200621 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800622}
623
Seth Hampson5b4f0752018-04-02 16:31:36 -0700624std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
625 std::string output = "streams=[";
626 const char* separator = "";
627 for (const auto& stream_id : stream_ids) {
628 output.append(separator).append(stream_id);
629 separator = ", ";
630 }
631 output.append("]");
632 return output;
633}
634
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200635absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700636 int rtc_configuration_parameter) {
637 if (rtc_configuration_parameter ==
638 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200639 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700640 }
641 return rtc_configuration_parameter;
642}
643
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800644cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
645 switch (type) {
646 case DataMessageType::kText:
647 return cricket::DMT_TEXT;
648 case DataMessageType::kBinary:
649 return cricket::DMT_BINARY;
650 case DataMessageType::kControl:
651 return cricket::DMT_CONTROL;
652 default:
653 return cricket::DMT_NONE;
654 }
655 return cricket::DMT_NONE;
656}
657
658DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
659 switch (type) {
660 case cricket::DMT_TEXT:
661 return DataMessageType::kText;
662 case cricket::DMT_BINARY:
663 return DataMessageType::kBinary;
664 case cricket::DMT_CONTROL:
665 return DataMessageType::kControl;
666 case cricket::DMT_NONE:
667 default:
668 RTC_NOTREACHED();
669 }
670 return DataMessageType::kControl;
671}
672
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800673void ReportSimulcastApiVersion(const char* name,
674 const SessionDescription& session) {
675 bool has_legacy = false;
676 bool has_spec_compliant = false;
677 for (const ContentInfo& content : session.contents()) {
678 if (!content.description) {
679 continue;
680 }
681 has_spec_compliant |= content.description->HasSimulcast();
682 for (const StreamParams& sp : content.description->streams()) {
683 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
684 }
685 }
686
687 if (has_legacy) {
688 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
689 kSimulcastApiVersionMax);
690 }
691 if (has_spec_compliant) {
692 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
693 kSimulcastApiVersionMax);
694 }
695 if (!has_legacy && !has_spec_compliant) {
696 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
697 kSimulcastApiVersionMax);
698 }
699}
700
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200701const ContentInfo* FindTransceiverMSection(
702 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
703 const SessionDescriptionInterface* session_description) {
704 return transceiver->mid()
705 ? session_description->description()->GetContentByName(
706 *transceiver->mid())
707 : nullptr;
708}
709
Steve Anton75737c02017-11-06 10:37:17 -0800710} // namespace
711
Henrik Boström31638672017-11-23 17:48:32 +0100712// Upon completion, posts a task to execute the callback of the
713// SetSessionDescriptionObserver asynchronously on the same thread. At this
714// point, the state of the peer connection might no longer reflect the effects
715// of the SetRemoteDescription operation, as the peer connection could have been
716// modified during the post.
717// TODO(hbos): Remove this class once we remove the version of
718// PeerConnectionInterface::SetRemoteDescription() that takes a
719// SetSessionDescriptionObserver as an argument.
720class PeerConnection::SetRemoteDescriptionObserverAdapter
721 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
722 public:
723 SetRemoteDescriptionObserverAdapter(
724 rtc::scoped_refptr<PeerConnection> pc,
725 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
726 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
727
728 // SetRemoteDescriptionObserverInterface implementation.
729 void OnSetRemoteDescriptionComplete(RTCError error) override {
730 if (error.ok())
731 pc_->PostSetSessionDescriptionSuccess(wrapper_);
732 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100733 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100734 }
735
736 private:
737 rtc::scoped_refptr<PeerConnection> pc_;
738 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
739};
740
deadbeef293e9262017-01-11 12:28:30 -0800741bool PeerConnectionInterface::RTCConfiguration::operator==(
742 const PeerConnectionInterface::RTCConfiguration& o) const {
743 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700744 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800745 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000746 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700747 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800748 BundlePolicy bundle_policy;
749 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700750 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
751 int ice_candidate_pool_size;
752 bool disable_ipv6;
753 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700754 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100755 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700756 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200757 absl::optional<int> screencast_min_bitrate;
758 absl::optional<bool> combined_audio_video_bwe;
759 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800760 TcpCandidatePolicy tcp_candidate_policy;
761 CandidateNetworkPolicy candidate_network_policy;
762 int audio_jitter_buffer_max_packets;
763 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100764 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100765 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800766 int ice_connection_receiving_timeout;
767 int ice_backup_candidate_pair_ping_interval;
768 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800769 bool prioritize_most_likely_ice_candidate_pairs;
770 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800771 bool prune_turn_ports;
772 bool presume_writable_when_fully_relayed;
773 bool enable_ice_renomination;
774 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200775 absl::optional<int> ice_check_interval_strong_connectivity;
776 absl::optional<int> ice_check_interval_weak_connectivity;
777 absl::optional<int> ice_check_min_interval;
778 absl::optional<int> ice_unwritable_timeout;
779 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800780 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200781 absl::optional<int> stun_candidate_keepalive_interval;
782 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200783 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800784 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200785 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700786 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700787 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700788 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700789 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100790 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800791 };
792 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
793 "Did you add something to RTCConfiguration and forget to "
794 "update operator==?");
795 return type == o.type && servers == o.servers &&
796 bundle_policy == o.bundle_policy &&
797 rtcp_mux_policy == o.rtcp_mux_policy &&
798 tcp_candidate_policy == o.tcp_candidate_policy &&
799 candidate_network_policy == o.candidate_network_policy &&
800 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
801 audio_jitter_buffer_fast_accelerate ==
802 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100803 audio_jitter_buffer_min_delay_ms ==
804 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100805 audio_jitter_buffer_enable_rtx_handling ==
806 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800807 ice_connection_receiving_timeout ==
808 o.ice_connection_receiving_timeout &&
809 ice_backup_candidate_pair_ping_interval ==
810 o.ice_backup_candidate_pair_ping_interval &&
811 continual_gathering_policy == o.continual_gathering_policy &&
812 certificates == o.certificates &&
813 prioritize_most_likely_ice_candidate_pairs ==
814 o.prioritize_most_likely_ice_candidate_pairs &&
815 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800816 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700817 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100818 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800819 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800820 screencast_min_bitrate == o.screencast_min_bitrate &&
821 combined_audio_video_bwe == o.combined_audio_video_bwe &&
822 enable_dtls_srtp == o.enable_dtls_srtp &&
823 ice_candidate_pool_size == o.ice_candidate_pool_size &&
824 prune_turn_ports == o.prune_turn_ports &&
825 presume_writable_when_fully_relayed ==
826 o.presume_writable_when_fully_relayed &&
827 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800828 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800829 ice_check_interval_strong_connectivity ==
830 o.ice_check_interval_strong_connectivity &&
831 ice_check_interval_weak_connectivity ==
832 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700833 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700834 ice_unwritable_timeout == o.ice_unwritable_timeout &&
835 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800836 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800837 stun_candidate_keepalive_interval ==
838 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200839 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800840 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800841 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700842 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700843 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700844 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700845 use_media_transport_for_data_channels ==
846 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100847 crypto_options == o.crypto_options &&
848 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800849}
850
851bool PeerConnectionInterface::RTCConfiguration::operator!=(
852 const PeerConnectionInterface::RTCConfiguration& o) const {
853 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800854}
855
zhihuang8f65cdf2016-05-06 18:40:30 -0700856// Generate a RTCP CNAME when a PeerConnection is created.
857std::string GenerateRtcpCname() {
858 std::string cname;
859 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100860 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800861 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700862 }
863 return cname;
864}
865
zhihuang1c378ed2017-08-17 14:10:50 -0700866bool ValidateOfferAnswerOptions(
867 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
868 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
869 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700870}
871
zhihuang1c378ed2017-08-17 14:10:50 -0700872// From |rtc_options|, fill parts of |session_options| shared by all generated
873// m= sections (in other words, nothing that involves a map/array).
874void ExtractSharedMediaSessionOptions(
875 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
876 cricket::MediaSessionOptions* session_options) {
877 session_options->vad_enabled = rtc_options.voice_activity_detection;
878 session_options->bundle_enabled = rtc_options.use_rtp_mux;
879}
zhihuanga77e6bb2017-08-14 18:17:48 -0700880
zhihuang38ede132017-06-15 12:52:32 -0700881PeerConnection::PeerConnection(PeerConnectionFactory* factory,
882 std::unique_ptr<RtcEventLog> event_log,
883 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700885 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100886 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700887 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700888 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700889 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100890 call_(std::move(call)),
891 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892
893PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100894 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800895 RTC_DCHECK_RUN_ON(signaling_thread());
896
Steve Anton8af21862017-12-15 11:20:13 -0800897 // Need to stop transceivers before destroying the stats collector because
898 // AudioRtpSender has a reference to the StatsCollector it will update when
899 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100900 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800901 transceiver->Stop();
902 }
Steve Anton4171afb2017-11-20 10:20:22 -0800903
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700904 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800905 if (stats_collector_) {
906 stats_collector_->WaitForPendingRequest();
907 stats_collector_ = nullptr;
908 }
Steve Anton75737c02017-11-06 10:37:17 -0800909
Steve Anton8af21862017-12-15 11:20:13 -0800910 // Don't destroy BaseChannels until after stats has been cleaned up so that
911 // the last stats request can still read from the channels.
912 DestroyAllChannels();
913
Mirko Bonadei675513b2017-11-09 11:09:25 +0100914 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800915
916 webrtc_session_desc_factory_.reset();
917 sctp_invoker_.reset();
918 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800919 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800920 transport_controller_.reset();
921
deadbeef91dd5672016-05-18 16:55:30 -0700922 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100923 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
924 RTC_DCHECK_RUN_ON(network_thread());
925 port_allocator_.reset();
926 });
eladalon248fd4f2017-09-06 05:18:15 -0700927 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700928 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100929 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700930 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800931 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700932 event_log_.reset();
933 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934}
935
Steve Anton8af21862017-12-15 11:20:13 -0800936void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800937 // Destroy video channels first since they may have a pointer to a voice
938 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100939 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800940 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800941 DestroyTransceiverChannel(transceiver);
942 }
943 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100944 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800945 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800946 DestroyTransceiverChannel(transceiver);
947 }
948 }
949 DestroyDataChannel();
950}
951
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000953 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700954 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100955 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100956 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100957 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700958
959 RTCError config_error = ValidateConfiguration(configuration);
960 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100961 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700962 return false;
963 }
964
Benjamin Wrightcab58882018-05-02 15:12:47 -0700965 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100966 RTC_LOG(LS_ERROR)
967 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100968 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800969 return false;
970 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200971
Benjamin Wrightcab58882018-05-02 15:12:47 -0700972 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800973 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100974 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100975 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800976 return false;
977 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700978
Benjamin Wrightcab58882018-05-02 15:12:47 -0700979 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700980 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700981 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700982 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800983
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200984 cricket::ServerAddresses stun_servers;
985 std::vector<cricket::RelayServerConfig> turn_servers;
986
987 RTCErrorType parse_error =
988 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
989 if (parse_error != RTCErrorType::NONE) {
990 return false;
991 }
992
deadbeef91dd5672016-05-18 16:55:30 -0700993 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700994 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100995 const auto pa_result =
996 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200997 RTC_FROM_HERE,
998 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100999 stun_servers, turn_servers, configuration));
1000
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001001 // If initialization was successful, note if STUN or TURN servers
1002 // were supplied.
1003 if (!stun_servers.empty()) {
1004 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1005 }
1006 if (!turn_servers.empty()) {
1007 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1008 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001010 // Send information about IPv4/IPv6 status.
1011 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001012 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001013 address_family = kPeerConnection_IPv6;
1014 } else {
1015 address_family = kPeerConnection_IPv4;
1016 }
1017 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1018 kPeerConnectionAddressFamilyCounter_Max);
1019
Zhi Huange830e682018-03-30 10:48:35 -07001020 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1021
Steve Anton75737c02017-11-06 10:37:17 -08001022 // RFC 3264: The numeric value of the session id and version in the
1023 // o line MUST be representable with a "64 bit signed integer".
1024 // Due to this constraint session id |session_id_| is max limited to
1025 // LLONG_MAX.
1026 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001027 JsepTransportController::Config config;
1028 config.redetermine_role_on_ice_restart =
1029 configuration.redetermine_role_on_ice_restart;
1030 config.ssl_max_version = factory_->options().ssl_max_version;
1031 config.disable_encryption = options.disable_encryption;
1032 config.bundle_policy = configuration.bundle_policy;
1033 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001034 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1035 // stub.
1036 config.crypto_options = configuration.crypto_options.has_value()
1037 ? *configuration.crypto_options
1038 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001039 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001040 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001041#if defined(ENABLE_EXTERNAL_AUTH)
1042 config.enable_external_auth = true;
1043#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001044 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001045
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001046 if (configuration.use_media_transport ||
1047 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001048 if (!factory_->media_transport_factory()) {
1049 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001050 << "PeerConnecton is initialized with use_media_transport = true or "
1051 << "use_media_transport_for_data_channels = true "
1052 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001053 return false;
1054 }
1055
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001056 if (configuration.use_media_transport ||
1057 configuration.use_media_transport_for_data_channels) {
1058 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1059 // RTP media transport is introduced. But until then, we require SDES to
1060 // be enabled.
1061 if (configuration.enable_dtls_srtp.has_value() &&
1062 configuration.enable_dtls_srtp.value()) {
1063 RTC_LOG(LS_WARNING)
1064 << "When media transport is used, SDES must be enabled. Set "
1065 "configuration.enable_dtls_srtp to false. use_media_transport="
1066 << configuration.use_media_transport
1067 << ", use_media_transport_for_data_channels="
1068 << configuration.use_media_transport_for_data_channels;
1069 return false;
1070 }
1071 }
1072
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001073 config.use_media_transport_for_media = configuration.use_media_transport;
1074 config.use_media_transport_for_data_channels =
1075 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001076 config.media_transport_factory = factory_->media_transport_factory();
1077 }
1078
Zhi Huange830e682018-03-30 10:48:35 -07001079 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001080 signaling_thread(), network_thread(), port_allocator_.get(),
1081 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001082 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001083 this, &PeerConnection::OnTransportControllerConnectionState);
1084 transport_controller_->SignalStandardizedIceConnectionState.connect(
1085 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001086 transport_controller_->SignalConnectionState.connect(
1087 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001088 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001089 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001090 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001091 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001092 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001093 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1094 transport_controller_->SignalDtlsHandshakeError.connect(
1095 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1096
1097 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001098
deadbeefab9b2d12015-10-14 11:33:11 -07001099 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001100 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101
Steve Antonba818672017-11-06 10:21:57 -08001102 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001103 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001104
Steve Anton75737c02017-11-06 10:37:17 -08001105 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1106 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1107 if (!configuration.certificates.empty()) {
1108 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1109 // just picking the first one. The decision should be made based on the DTLS
1110 // handshake. The DTLS negotiations need to know about all certificates.
1111 certificate = configuration.certificates[0];
1112 }
1113
Steve Antond25da372017-11-06 14:50:29 -08001114 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001115
1116 if (options.disable_encryption) {
1117 dtls_enabled_ = false;
1118 } else {
1119 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001120 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001121 // |configuration| can override the default |dtls_enabled_| value.
1122 if (configuration.enable_dtls_srtp) {
1123 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1124 }
1125 }
1126
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001127 if (configuration.use_media_transport_for_data_channels) {
1128 if (configuration.enable_rtp_data_channel) {
1129 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1130 "use_media_transport_for_data_channels are "
1131 "incompatible and cannot both be set to true";
1132 return false;
1133 }
1134 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1135 } else if (configuration.enable_rtp_data_channel) {
1136 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1137 // set. It takes precendence over the disable_sctp_data_channels
1138 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001139 data_channel_type_ = cricket::DCT_RTP;
1140 } else {
1141 // DTLS has to be enabled to use SCTP.
1142 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1143 data_channel_type_ = cricket::DCT_SCTP;
1144 }
1145 }
1146
1147 video_options_.screencast_min_bitrate_kbps =
1148 configuration.screencast_min_bitrate;
1149 audio_options_.combined_audio_video_bwe =
1150 configuration.combined_audio_video_bwe;
1151
1152 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001153 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001154
1155 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001156 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001157
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001158 audio_options_.audio_jitter_buffer_min_delay_ms =
1159 configuration.audio_jitter_buffer_min_delay_ms;
1160
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001161 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1162 configuration.audio_jitter_buffer_enable_rtx_handling;
1163
Steve Anton75737c02017-11-06 10:37:17 -08001164 // Whether the certificate generator/certificate is null or not determines
1165 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1166 // the right instructions by clearing the variables if needed.
1167 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001168 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001169 certificate = nullptr;
1170 } else if (certificate) {
1171 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001172 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001173 }
1174
1175 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1176 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001177 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001178 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1179 this, &PeerConnection::OnCertificateReady);
1180
1181 if (options.disable_encryption) {
1182 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1183 }
1184
1185 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001186 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001187 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188
Steve Anton4171afb2017-11-20 10:20:22 -08001189 // Add default audio/video transceivers for Plan B SDP.
1190 if (!IsUnifiedPlan()) {
1191 transceivers_.push_back(
1192 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1193 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1194 transceivers_.push_back(
1195 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1196 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1197 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001198 int delay_ms =
1199 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001200 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1201 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202 return true;
1203}
1204
Steve Anton038834f2017-07-14 15:59:59 -07001205RTCError PeerConnection::ValidateConfiguration(
1206 const RTCConfiguration& config) const {
1207 if (config.ice_regather_interval_range &&
1208 config.continual_gathering_policy == GATHER_ONCE) {
1209 return RTCError(RTCErrorType::INVALID_PARAMETER,
1210 "ice_regather_interval_range specified but continual "
1211 "gathering policy is GATHER_ONCE");
1212 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001213 auto result =
1214 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1215 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001216}
1217
Yves Gerey665174f2018-06-19 15:03:05 +02001218rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001219 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001220 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1221 "Plan SdpSemantics. Please use GetSenders "
1222 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001223 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001224}
1225
Yves Gerey665174f2018-06-19 15:03:05 +02001226rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001227 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001228 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1229 "Plan SdpSemantics. Please use GetReceivers "
1230 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001231 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232}
1233
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001234bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001235 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001236 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1237 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001238 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 if (IsClosed()) {
1240 return false;
1241 }
deadbeefab9b2d12015-10-14 11:33:11 -07001242 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243 return false;
1244 }
deadbeefab9b2d12015-10-14 11:33:11 -07001245
1246 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001247 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1248 observer->SignalAudioTrackAdded.connect(this,
1249 &PeerConnection::OnAudioTrackAdded);
1250 observer->SignalAudioTrackRemoved.connect(
1251 this, &PeerConnection::OnAudioTrackRemoved);
1252 observer->SignalVideoTrackAdded.connect(this,
1253 &PeerConnection::OnVideoTrackAdded);
1254 observer->SignalVideoTrackRemoved.connect(
1255 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001256 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001257
deadbeefab9b2d12015-10-14 11:33:11 -07001258 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001259 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001260 }
1261 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001262 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001263 }
1264
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001265 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001266 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 return true;
1268}
1269
1270void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001271 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001272 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1273 "Plan SdpSemantics. Please use RemoveTrack "
1274 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001275 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001276 if (!IsClosed()) {
1277 for (const auto& track : local_stream->GetAudioTracks()) {
1278 RemoveAudioTrack(track.get(), local_stream);
1279 }
1280 for (const auto& track : local_stream->GetVideoTracks()) {
1281 RemoveVideoTrack(track.get(), local_stream);
1282 }
deadbeefab9b2d12015-10-14 11:33:11 -07001283 }
deadbeefab9b2d12015-10-14 11:33:11 -07001284 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001285 stream_observers_.erase(
1286 std::remove_if(
1287 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001288 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001289 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001290 }),
1291 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001292
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 if (IsClosed()) {
1294 return;
1295 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001296 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297}
1298
Steve Anton2d6c76a2018-01-05 17:10:52 -08001299RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001300 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001301 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001302 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001303 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001304 if (!track) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1306 }
1307 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1308 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1309 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1310 "Track has invalid kind: " + track->kind());
1311 }
Steve Antonf9381f02017-12-14 10:23:57 -08001312 if (IsClosed()) {
1313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1314 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001315 }
Steve Anton4171afb2017-11-20 10:20:22 -08001316 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001317 LOG_AND_RETURN_ERROR(
1318 RTCErrorType::INVALID_PARAMETER,
1319 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001320 }
Steve Antonf9381f02017-12-14 10:23:57 -08001321 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001322 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1323 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001324 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001325 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001326 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001327 }
1328 return sender_or_error;
1329}
deadbeefe1f9d832016-01-14 15:35:42 -08001330
Steve Antonf9381f02017-12-14 10:23:57 -08001331RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1332PeerConnection::AddTrackPlanB(
1333 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001334 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001335 if (stream_ids.size() > 1u) {
1336 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1337 "AddTrack with more than one stream is not "
1338 "supported with Plan B semantics.");
1339 }
1340 std::vector<std::string> adjusted_stream_ids = stream_ids;
1341 if (adjusted_stream_ids.empty()) {
1342 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1343 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001344 cricket::MediaType media_type =
1345 (track->kind() == MediaStreamTrackInterface::kAudioKind
1346 ? cricket::MEDIA_TYPE_AUDIO
1347 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001348 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001349 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001350 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001351 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001352 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001353 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001354 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001355 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001356 if (sender_info) {
1357 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001358 }
Steve Antonf9381f02017-12-14 10:23:57 -08001359 } else {
1360 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001361 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001362 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001363 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001364 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001365 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001366 if (sender_info) {
1367 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001368 }
deadbeefe1f9d832016-01-14 15:35:42 -08001369 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001370 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001371}
deadbeefe1f9d832016-01-14 15:35:42 -08001372
Steve Antonf9381f02017-12-14 10:23:57 -08001373RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1374PeerConnection::AddTrackUnifiedPlan(
1375 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001376 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001377 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1378 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001379 RTC_LOG(LS_INFO) << "Reusing an existing "
1380 << cricket::MediaTypeToString(transceiver->media_type())
1381 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001382 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001383 transceiver->internal()->set_direction(
1384 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001385 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001386 transceiver->internal()->set_direction(
1387 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001388 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001389 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001390 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001391 } else {
1392 cricket::MediaType media_type =
1393 (track->kind() == MediaStreamTrackInterface::kAudioKind
1394 ? cricket::MEDIA_TYPE_AUDIO
1395 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001396 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1397 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001398 std::string sender_id = track->id();
1399 // Avoid creating a sender with an existing ID by generating a random ID.
1400 // This can happen if this is the second time AddTrack has created a sender
1401 // for this track.
1402 if (FindSenderById(sender_id)) {
1403 sender_id = rtc::CreateRandomUuid();
1404 }
Florent Castelli892acf02018-10-01 22:47:20 +02001405 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001406 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1407 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001408 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001409 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001410 }
Steve Antonf9381f02017-12-14 10:23:57 -08001411 return transceiver->sender();
1412}
1413
1414rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1415PeerConnection::FindFirstTransceiverForAddedTrack(
1416 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1417 RTC_DCHECK(track);
1418 for (auto transceiver : transceivers_) {
1419 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001420 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001421 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001422 !transceiver->internal()->has_ever_been_used_to_send() &&
1423 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001424 return transceiver;
1425 }
1426 }
1427 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001428}
1429
1430bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1431 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001432 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001433}
1434
Steve Anton24db5732018-07-23 10:27:33 -07001435RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001436 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001437 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001438 if (!sender) {
1439 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1440 }
deadbeefe1f9d832016-01-14 15:35:42 -08001441 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001442 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1443 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001444 }
Steve Antonf9381f02017-12-14 10:23:57 -08001445 if (IsUnifiedPlan()) {
1446 auto transceiver = FindTransceiverBySender(sender);
1447 if (!transceiver || !sender->track()) {
1448 return RTCError::OK();
1449 }
1450 sender->SetTrack(nullptr);
1451 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001452 transceiver->internal()->set_direction(
1453 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001454 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001455 transceiver->internal()->set_direction(
1456 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001457 }
Steve Anton4171afb2017-11-20 10:20:22 -08001458 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001459 bool removed;
1460 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1461 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1462 } else {
1463 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1464 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1465 }
1466 if (!removed) {
1467 LOG_AND_RETURN_ERROR(
1468 RTCErrorType::INVALID_PARAMETER,
1469 "Couldn't find sender " + sender->id() + " to remove.");
1470 }
Steve Anton4171afb2017-11-20 10:20:22 -08001471 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001472 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001473 return RTCError::OK();
1474}
1475
1476rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1477PeerConnection::FindTransceiverBySender(
1478 rtc::scoped_refptr<RtpSenderInterface> sender) {
1479 for (auto transceiver : transceivers_) {
1480 if (transceiver->sender() == sender) {
1481 return transceiver;
1482 }
1483 }
1484 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001485}
1486
Steve Anton9158ef62017-11-27 13:01:52 -08001487RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1488PeerConnection::AddTransceiver(
1489 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1490 return AddTransceiver(track, RtpTransceiverInit());
1491}
1492
1493RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1494PeerConnection::AddTransceiver(
1495 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1496 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001497 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001498 RTC_CHECK(IsUnifiedPlan())
1499 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001500 if (!track) {
1501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1502 }
1503 cricket::MediaType media_type;
1504 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1505 media_type = cricket::MEDIA_TYPE_AUDIO;
1506 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1507 media_type = cricket::MEDIA_TYPE_VIDEO;
1508 } else {
1509 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1510 "Track kind is not audio or video");
1511 }
1512 return AddTransceiver(media_type, track, init);
1513}
1514
1515RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1516PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1517 return AddTransceiver(media_type, RtpTransceiverInit());
1518}
1519
1520RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1521PeerConnection::AddTransceiver(cricket::MediaType media_type,
1522 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001523 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001524 RTC_CHECK(IsUnifiedPlan())
1525 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001526 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1527 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1528 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1529 "media type is not audio or video");
1530 }
1531 return AddTransceiver(media_type, nullptr, init);
1532}
1533
1534RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1535PeerConnection::AddTransceiver(
1536 cricket::MediaType media_type,
1537 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001538 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001539 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001540 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1541 media_type == cricket::MEDIA_TYPE_VIDEO));
1542 if (track) {
1543 RTC_DCHECK_EQ(media_type,
1544 (track->kind() == MediaStreamTrackInterface::kAudioKind
1545 ? cricket::MEDIA_TYPE_AUDIO
1546 : cricket::MEDIA_TYPE_VIDEO));
1547 }
1548
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001549 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1550 init.send_encodings.size(), 0, 7, 8);
1551
Amit Hilbuchaa584152019-02-06 17:09:52 -08001552 size_t num_rids = absl::c_count_if(init.send_encodings,
1553 [](const RtpEncodingParameters& encoding) {
1554 return !encoding.rid.empty();
1555 });
1556 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001557 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001558 RTCErrorType::INVALID_PARAMETER,
1559 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001560 }
1561
Amit Hilbuchf4770402019-04-08 14:11:57 -07001562 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1563 [](const RtpEncodingParameters& encoding) {
1564 return !IsLegalRsidName(encoding.rid);
1565 })) {
1566 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1567 "Invalid RID value provided.");
1568 }
1569
Amit Hilbuchaa584152019-02-06 17:09:52 -08001570 if (absl::c_any_of(init.send_encodings,
1571 [](const RtpEncodingParameters& encoding) {
1572 return encoding.ssrc.has_value();
1573 })) {
1574 LOG_AND_RETURN_ERROR(
1575 RTCErrorType::UNSUPPORTED_PARAMETER,
1576 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001577 }
1578
1579 RtpParameters parameters;
1580 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001581
1582 // Encodings are dropped from the tail if too many are provided.
1583 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1584 parameters.encodings.erase(
1585 parameters.encodings.begin() + kMaxSimulcastStreams,
1586 parameters.encodings.end());
1587 }
1588
1589 // Single RID should be removed.
1590 if (parameters.encodings.size() == 1 &&
1591 !parameters.encodings[0].rid.empty()) {
1592 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1593 parameters.encodings[0].rid.clear();
1594 }
1595
1596 // If RIDs were not provided, they are generated for simulcast scenario.
1597 if (parameters.encodings.size() > 1 && num_rids == 0) {
1598 rtc::UniqueStringGenerator rid_generator;
1599 for (RtpEncodingParameters& encoding : parameters.encodings) {
1600 encoding.rid = rid_generator();
1601 }
1602 }
1603
Florent Castelli892acf02018-10-01 22:47:20 +02001604 if (UnimplementedRtpParameterHasValue(parameters)) {
1605 LOG_AND_RETURN_ERROR(
1606 RTCErrorType::UNSUPPORTED_PARAMETER,
1607 "Attempted to set an unimplemented parameter of RtpParameters.");
1608 }
Steve Anton9158ef62017-11-27 13:01:52 -08001609
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001610 auto result = cricket::CheckRtpParametersValues(parameters);
1611 if (!result.ok()) {
1612 LOG_AND_RETURN_ERROR(result.type(), result.message());
1613 }
1614
Steve Anton3d954a62018-04-02 11:27:23 -07001615 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1616 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001617 // Set the sender ID equal to the track ID if the track is specified unless
1618 // that sender ID is already in use.
1619 std::string sender_id =
1620 (track && !FindSenderById(track->id()) ? track->id()
1621 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001622 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001623 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001624 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1625 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1626 transceiver->internal()->set_direction(init.direction);
1627
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001628 if (update_negotiation_needed) {
1629 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001630 }
Steve Antonf9381f02017-12-14 10:23:57 -08001631
1632 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1633}
1634
Steve Anton02ee47c2018-01-10 16:26:06 -08001635rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1636PeerConnection::CreateSender(
1637 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001638 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001639 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001640 const std::vector<std::string>& stream_ids,
1641 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001642 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001643 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001644 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1645 RTC_DCHECK(!track ||
1646 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1647 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1648 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001649 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001650 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001651 } else {
1652 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1653 RTC_DCHECK(!track ||
1654 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1655 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001656 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001657 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001658 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001659 bool set_track_succeeded = sender->SetTrack(track);
1660 RTC_DCHECK(set_track_succeeded);
1661 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001662 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001663 return sender;
1664}
1665
1666rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1667PeerConnection::CreateReceiver(cricket::MediaType media_type,
1668 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001669 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1670 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001671 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001672 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001673 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1674 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001675 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001676 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001677 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001678 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001679 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1680 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001681 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001682 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001683 return receiver;
1684}
1685
1686rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1687PeerConnection::CreateAndAddTransceiver(
1688 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1689 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1690 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001691 // Ensure that the new sender does not have an ID that is already in use by
1692 // another sender.
1693 // Allow receiver IDs to conflict since those come from remote SDP (which
1694 // could be invalid, but should not cause a crash).
1695 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001696 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1697 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001698 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001699 transceiver->internal()->SignalNegotiationNeeded.connect(
1700 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001701 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001702}
1703
Steve Anton52d86772018-02-20 15:48:12 -08001704void PeerConnection::OnNegotiationNeeded() {
1705 RTC_DCHECK_RUN_ON(signaling_thread());
1706 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001707 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001708}
1709
deadbeeffac06552015-11-25 11:26:01 -08001710rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001711 const std::string& kind,
1712 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001713 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001714 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1715 "Plan SdpSemantics. Please use AddTransceiver "
1716 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001717 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001718 if (IsClosed()) {
1719 return nullptr;
1720 }
Steve Anton4171afb2017-11-20 10:20:22 -08001721
Seth Hampson5b4f0752018-04-02 16:31:36 -07001722 // Internally we need to have one stream with Plan B semantics, so we
1723 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001724 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001725 if (stream_id.empty()) {
1726 stream_ids.push_back(rtc::CreateRandomUuid());
1727 RTC_LOG(LS_INFO)
1728 << "No stream_id specified for sender. Generated stream ID: "
1729 << stream_ids[0];
1730 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001731 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001732 }
1733
Steve Anton4171afb2017-11-20 10:20:22 -08001734 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001735 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001736 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001737 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001738 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001739 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001740 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001741 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001742 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001743 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001744 auto video_sender =
1745 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001746 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001747 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001748 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001749 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001750 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001751 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001752 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001753 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001754 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001755
deadbeefe1f9d832016-01-14 15:35:42 -08001756 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001757}
1758
deadbeef70ab1a12015-09-28 16:53:55 -07001759std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1760 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001761 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001762 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001763 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001764 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001765 }
1766 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001767}
1768
Steve Anton4171afb2017-11-20 10:20:22 -08001769std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1770PeerConnection::GetSendersInternal() const {
1771 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1772 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001773 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001774 auto senders = transceiver->internal()->senders();
1775 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1776 }
1777 return all_senders;
1778}
1779
deadbeef70ab1a12015-09-28 16:53:55 -07001780std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1781PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001782 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001783 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001784 for (const auto& receiver : GetReceiversInternal()) {
1785 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001786 }
1787 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001788}
1789
Steve Anton4171afb2017-11-20 10:20:22 -08001790std::vector<
1791 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1792PeerConnection::GetReceiversInternal() const {
1793 std::vector<
1794 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1795 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001796 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001797 auto receivers = transceiver->internal()->receivers();
1798 all_receivers.insert(all_receivers.end(), receivers.begin(),
1799 receivers.end());
1800 }
1801 return all_receivers;
1802}
1803
Steve Anton9158ef62017-11-27 13:01:52 -08001804std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1805PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001806 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001807 RTC_CHECK(IsUnifiedPlan())
1808 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001809 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001810 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001811 all_transceivers.push_back(transceiver);
1812 }
1813 return all_transceivers;
1814}
1815
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001816bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001817 MediaStreamTrackInterface* track,
1818 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001819 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001820 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001821 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001822 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823 return false;
1824 }
1825
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001826 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001827 // The StatsCollector is used to tell if a track is valid because it may
1828 // remember tracks that the PeerConnection previously removed.
1829 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001830 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1831 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001832 return false;
1833 }
Steve Antonad182762018-09-05 20:22:40 +00001834 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1835 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001836 return true;
1837}
1838
hbos74e1a4f2016-09-15 23:33:01 -07001839void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001840 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001841 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001842 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001843 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001844 stats_collector_->GetStatsReport(callback);
1845}
1846
Henrik Boström1df1bf82018-03-20 13:24:20 +01001847void PeerConnection::GetStats(
1848 rtc::scoped_refptr<RtpSenderInterface> selector,
1849 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1850 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001851 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001852 RTC_DCHECK(callback);
1853 RTC_DCHECK(stats_collector_);
1854 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1855 if (selector) {
1856 for (const auto& proxy_transceiver : transceivers_) {
1857 for (const auto& proxy_sender :
1858 proxy_transceiver->internal()->senders()) {
1859 if (proxy_sender == selector) {
1860 internal_sender = proxy_sender->internal();
1861 break;
1862 }
1863 }
1864 if (internal_sender)
1865 break;
1866 }
1867 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001868 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001869 // belong to the PeerConnection (in Plan B, senders can be removed from the
1870 // PeerConnection). This means that "all the stats objects representing the
1871 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1872 // produces an empty stats report.
1873 stats_collector_->GetStatsReport(internal_sender, callback);
1874}
1875
1876void PeerConnection::GetStats(
1877 rtc::scoped_refptr<RtpReceiverInterface> selector,
1878 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1879 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001880 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001881 RTC_DCHECK(callback);
1882 RTC_DCHECK(stats_collector_);
1883 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1884 if (selector) {
1885 for (const auto& proxy_transceiver : transceivers_) {
1886 for (const auto& proxy_receiver :
1887 proxy_transceiver->internal()->receivers()) {
1888 if (proxy_receiver == selector) {
1889 internal_receiver = proxy_receiver->internal();
1890 break;
1891 }
1892 }
1893 if (internal_receiver)
1894 break;
1895 }
1896 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001897 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001898 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1899 // the PeerConnection). This means that "all the stats objects representing
1900 // the selector" is an empty set. Invoking GetStatsReport() with a null
1901 // selector produces an empty stats report.
1902 stats_collector_->GetStatsReport(internal_receiver, callback);
1903}
1904
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001906 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907 return signaling_state_;
1908}
1909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910PeerConnectionInterface::IceConnectionState
1911PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001912 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001913 return ice_connection_state_;
1914}
1915
Alex Loiko9289eda2018-11-23 16:18:59 +00001916PeerConnectionInterface::IceConnectionState
1917PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001918 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001919 return standardized_ice_connection_state_;
1920}
1921
Jonas Olsson635474e2018-10-18 15:58:17 +02001922PeerConnectionInterface::PeerConnectionState
1923PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001924 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001925 return connection_state_;
1926}
1927
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928PeerConnectionInterface::IceGatheringState
1929PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001930 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 return ice_gathering_state_;
1932}
1933
Yves Gerey665174f2018-06-19 15:03:05 +02001934rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935 const std::string& label,
1936 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001937 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001938 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001939
deadbeefab9b2d12015-10-14 11:33:11 -07001940 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001941
kwibergd1fe2812016-04-27 06:47:29 -07001942 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001943 if (config) {
1944 internal_config.reset(new InternalDataChannelInit(*config));
1945 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001946 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001947 InternalCreateDataChannel(label, internal_config.get()));
1948 if (!channel.get()) {
1949 return nullptr;
1950 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001952 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1953 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001954 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001955 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001956 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001957 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001958 return DataChannelProxy::Create(signaling_thread(), channel.get());
1959}
1960
1961void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001962 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001963 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001964 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001965
nisse7ce109a2017-01-31 00:57:56 -08001966 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001967 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001968 return;
1969 }
deadbeefab9b2d12015-10-14 11:33:11 -07001970
Steve Anton8d3444d2017-10-20 15:30:51 -07001971 if (IsClosed()) {
1972 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001973 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001974 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001975 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001976 return;
1977 }
1978
zhihuang1c378ed2017-08-17 14:10:50 -07001979 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001980 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001981 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001982 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001983 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001984 return;
1985 }
1986
Steve Anton22da89f2018-01-25 13:58:07 -08001987 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1988 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1989 if (IsUnifiedPlan()) {
1990 RTCError error = HandleLegacyOfferOptions(options);
1991 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001992 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001993 return;
1994 }
1995 }
1996
zhihuang1c378ed2017-08-17 14:10:50 -07001997 cricket::MediaSessionOptions session_options;
1998 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001999 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002000}
2001
Steve Anton22da89f2018-01-25 13:58:07 -08002002RTCError PeerConnection::HandleLegacyOfferOptions(
2003 const RTCOfferAnswerOptions& options) {
2004 RTC_DCHECK(IsUnifiedPlan());
2005
2006 if (options.offer_to_receive_audio == 0) {
2007 RemoveRecvDirectionFromReceivingTransceiversOfType(
2008 cricket::MEDIA_TYPE_AUDIO);
2009 } else if (options.offer_to_receive_audio == 1) {
2010 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2011 } else if (options.offer_to_receive_audio > 1) {
2012 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2013 "offer_to_receive_audio > 1 is not supported.");
2014 }
2015
2016 if (options.offer_to_receive_video == 0) {
2017 RemoveRecvDirectionFromReceivingTransceiversOfType(
2018 cricket::MEDIA_TYPE_VIDEO);
2019 } else if (options.offer_to_receive_video == 1) {
2020 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2021 } else if (options.offer_to_receive_video > 1) {
2022 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2023 "offer_to_receive_video > 1 is not supported.");
2024 }
2025
2026 return RTCError::OK();
2027}
2028
2029void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2030 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002031 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002032 RtpTransceiverDirection new_direction =
2033 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2034 if (new_direction != transceiver->direction()) {
2035 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2036 << " transceiver (MID="
2037 << transceiver->mid().value_or("<not set>") << ") from "
2038 << RtpTransceiverDirectionToString(
2039 transceiver->direction())
2040 << " to "
2041 << RtpTransceiverDirectionToString(new_direction)
2042 << " since CreateOffer specified offer_to_receive=0";
2043 transceiver->internal()->set_direction(new_direction);
2044 }
Steve Anton22da89f2018-01-25 13:58:07 -08002045 }
2046}
2047
2048void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2049 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002050 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002051 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002052 RTC_LOG(LS_INFO)
2053 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2054 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002055 RtpTransceiverInit init;
2056 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002057 AddTransceiver(media_type, nullptr, init,
2058 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002059 }
2060}
2061
2062std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2063PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2064 std::vector<
2065 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2066 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002067 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002068 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002069 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2070 receiving_transceivers.push_back(transceiver);
2071 }
2072 }
2073 return receiving_transceivers;
2074}
2075
htaa2a49d92016-03-04 02:51:39 -08002076void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2077 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002078 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002079 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002080 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002081 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002082 return;
2083 }
2084
Steve Antondffead82018-02-06 10:31:29 -08002085 if (!(signaling_state_ == kHaveRemoteOffer ||
2086 signaling_state_ == kHaveLocalPrAnswer)) {
2087 std::string error =
2088 "PeerConnection cannot create an answer in a state other than "
2089 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002090 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002091 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002092 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002093 return;
2094 }
2095
Steve Antondffead82018-02-06 10:31:29 -08002096 // The remote description should be set if we're in the right state.
2097 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002098
Steve Anton22da89f2018-01-25 13:58:07 -08002099 if (IsUnifiedPlan()) {
2100 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2101 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2102 "supported with Unified Plan semantics. Use the "
2103 "RtpTransceiver API instead.";
2104 }
2105 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2106 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2107 "supported with Unified Plan semantics. Use the "
2108 "RtpTransceiver API instead.";
2109 }
2110 }
2111
htaa2a49d92016-03-04 02:51:39 -08002112 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002113 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002114
Steve Antond25da372017-11-06 14:50:29 -08002115 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002116}
2117
2118void PeerConnection::SetLocalDescription(
2119 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002120 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002121 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002122 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002123
Steve Anton80dd7b52018-02-16 17:08:42 -08002124 // The SetLocalDescription contract is that we take ownership of the session
2125 // description regardless of the outcome, so wrap it in a unique_ptr right
2126 // away. Ideally, SetLocalDescription's signature will be changed to take the
2127 // description as a unique_ptr argument to formalize this agreement.
2128 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2129
nisse7ce109a2017-01-31 00:57:56 -08002130 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002131 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132 return;
2133 }
Steve Anton8a006912017-12-04 15:25:56 -08002134
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002136 PostSetSessionDescriptionFailure(
2137 observer,
2138 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139 return;
2140 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002141
Steve Anton80dd7b52018-02-16 17:08:42 -08002142 // If a session error has occurred the PeerConnection is in a possibly
2143 // inconsistent state so fail right away.
2144 if (session_error() != SessionError::kNone) {
2145 std::string error_message = GetSessionErrorMsg();
2146 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002147 PostSetSessionDescriptionFailure(
2148 observer,
2149 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002150 return;
2151 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002152
Steve Anton80dd7b52018-02-16 17:08:42 -08002153 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2154 if (!error.ok()) {
2155 std::string error_message = GetSetDescriptionErrorMessage(
2156 cricket::CS_LOCAL, desc->GetType(), error);
2157 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002158 PostSetSessionDescriptionFailure(
2159 observer,
2160 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002161 return;
2162 }
2163
2164 // Grab the description type before moving ownership to ApplyLocalDescription,
2165 // which may destroy it before returning.
2166 const SdpType type = desc->GetType();
2167
2168 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002169 // |desc| may be destroyed at this point.
2170
2171 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002172 // If ApplyLocalDescription fails, the PeerConnection could be in an
2173 // inconsistent state, so act conservatively here and set the session error
2174 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2175 SetSessionError(SessionError::kContent, error.message());
2176 std::string error_message =
2177 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2178 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002179 PostSetSessionDescriptionFailure(
2180 observer,
2181 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002182 return;
2183 }
Steve Anton8a006912017-12-04 15:25:56 -08002184 RTC_DCHECK(local_description());
2185
2186 PostSetSessionDescriptionSuccess(observer);
2187
Steve Antonad182762018-09-05 20:22:40 +00002188 // MaybeStartGathering needs to be called after posting
2189 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2190 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002191 transport_controller_->MaybeStartGathering();
2192
Steve Antona3a92c22017-12-07 10:27:41 -08002193 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002194 // TODO(deadbeef): We already had to hop to the network thread for
2195 // MaybeStartGathering...
2196 network_thread()->Invoke<void>(
2197 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2198 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002199 // Make UMA notes about what was agreed to.
2200 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002201 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002202
2203 if (IsUnifiedPlan()) {
2204 bool was_negotiation_needed = is_negotiation_needed_;
2205 UpdateNegotiationNeeded();
2206 if (signaling_state() == kStable && was_negotiation_needed &&
2207 is_negotiation_needed_) {
2208 Observer()->OnRenegotiationNeeded();
2209 }
2210 }
2211
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002212 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002213}
2214
2215RTCError PeerConnection::ApplyLocalDescription(
2216 std::unique_ptr<SessionDescriptionInterface> desc) {
2217 RTC_DCHECK_RUN_ON(signaling_thread());
2218 RTC_DCHECK(desc);
2219
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 // Update stats here so that we have the most recent stats for tracks and
2221 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002222 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002223
Steve Antondcc3c022017-12-22 16:02:54 -08002224 // Take a reference to the old local description since it's used below to
2225 // compare against the new local description. When setting the new local
2226 // description, grab ownership of the replaced session description in case it
2227 // is the same as |old_local_description|, to keep it alive for the duration
2228 // of the method.
2229 const SessionDescriptionInterface* old_local_description =
2230 local_description();
2231 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002232 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002233 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002234 replaced_local_description = pending_local_description_
2235 ? std::move(pending_local_description_)
2236 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002237 current_local_description_ = std::move(desc);
2238 pending_local_description_ = nullptr;
2239 current_remote_description_ = std::move(pending_remote_description_);
2240 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002241 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002242 pending_local_description_ = std::move(desc);
2243 }
2244 // The session description to apply now must be accessed by
2245 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002246 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002247
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002248 // Report statistics about any use of simulcast.
2249 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2250 *local_description()->description());
2251
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002252 if (!is_caller_) {
2253 if (remote_description()) {
2254 // Remote description was applied first, so this PC is the callee.
2255 is_caller_ = false;
2256 } else {
2257 // Local description is applied first, so this PC is the caller.
2258 is_caller_ = true;
2259 }
2260 }
2261
Zhi Huange830e682018-03-30 10:48:35 -07002262 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2263 if (!error.ok()) {
2264 return error;
2265 }
2266
Steve Antondcc3c022017-12-22 16:02:54 -08002267 if (IsUnifiedPlan()) {
2268 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002269 cricket::CS_LOCAL, *local_description(), old_local_description,
2270 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002271 if (!error.ok()) {
2272 return error;
2273 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002274 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2275 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002276 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002277 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2278 // Note that code paths that don't set MID won't be able to use
2279 // information about DTLS transports.
2280 if (transceiver->mid()) {
2281 auto dtls_transport =
2282 LookupDtlsTransportByMidInternal(*transceiver->mid());
2283 transceiver->internal()->sender_internal()->set_transport(
2284 dtls_transport);
2285 transceiver->internal()->receiver_internal()->set_transport(
2286 dtls_transport);
2287 }
2288
Steve Antondcc3c022017-12-22 16:02:54 -08002289 const ContentInfo* content =
2290 FindMediaSectionForTransceiver(transceiver, local_description());
2291 if (!content) {
2292 continue;
2293 }
2294 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002295 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2296 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002297 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002298 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2299 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2300 // "recvonly", process the removal of a remote track for the media
2301 // description, given transceiver, removeList, and muteTracks.
2302 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2303 (transceiver->internal()->fired_direction() &&
2304 RtpTransceiverDirectionHasRecv(
2305 *transceiver->internal()->fired_direction()))) {
2306 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2307 &removed_streams);
2308 }
2309 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2310 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002311 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002312 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002313 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002314 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002315 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002316 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002317 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002318 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002319 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002320 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002321 }
2322 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002323 // Media channels will be created only when offer is set. These may use new
2324 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002325 if (type == SdpType::kOffer) {
2326 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2327 // description is applied. Restore back to old description.
2328 RTCError error = CreateChannels(*local_description()->description());
2329 if (!error.ok()) {
2330 return error;
2331 }
2332 }
Steve Antondcc3c022017-12-22 16:02:54 -08002333 // Remove unused channels if MediaContentDescription is rejected.
2334 RemoveUnusedChannels(local_description()->description());
2335 }
Steve Anton8a006912017-12-04 15:25:56 -08002336
Zhi Huange830e682018-03-30 10:48:35 -07002337 error = UpdateSessionState(type, cricket::CS_LOCAL,
2338 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002339 if (!error.ok()) {
2340 return error;
2341 }
Steve Antondcc3c022017-12-22 16:02:54 -08002342
Steve Anton8a006912017-12-04 15:25:56 -08002343 if (remote_description()) {
2344 // Now that we have a local description, we can push down remote candidates.
2345 UseCandidatesInSessionDescription(remote_description());
2346 }
2347
2348 pending_ice_restarts_.clear();
2349 if (session_error() != SessionError::kNone) {
2350 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2351 }
2352
deadbeefab9b2d12015-10-14 11:33:11 -07002353 // If setting the description decided our SSL role, allocate any necessary
2354 // SCTP sids.
2355 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002356 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002357 AllocateSctpSids(role);
2358 }
2359
Steve Antond3679212018-01-17 17:41:02 -08002360 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002361 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002362 const ContentInfo* content =
2363 FindMediaSectionForTransceiver(transceiver, local_description());
2364 if (!content) {
2365 continue;
2366 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002367 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2368 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002369 // 0 is a special value meaning "this sender has no associated send
2370 // stream". Need to call this so the sender won't attempt to configure
2371 // a no longer existing stream and run into DCHECKs in the lower
2372 // layers.
2373 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002374 } else {
2375 // Get the StreamParams from the channel which could generate SSRCs.
2376 const std::vector<StreamParams>& streams = channel->local_streams();
2377 transceiver->internal()->sender_internal()->set_stream_ids(
2378 streams[0].stream_ids());
2379 transceiver->internal()->sender_internal()->SetSsrc(
2380 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002381 }
2382 }
2383 } else {
2384 // Plan B semantics.
2385
Steve Antondcc3c022017-12-22 16:02:54 -08002386 // Update state and SSRC of local MediaStreams and DataChannels based on the
2387 // local session description.
2388 const cricket::ContentInfo* audio_content =
2389 GetFirstAudioContent(local_description()->description());
2390 if (audio_content) {
2391 if (audio_content->rejected) {
2392 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2393 } else {
2394 const cricket::AudioContentDescription* audio_desc =
2395 audio_content->media_description()->as_audio();
2396 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2397 }
deadbeeffaac4972015-11-12 15:33:07 -08002398 }
deadbeefab9b2d12015-10-14 11:33:11 -07002399
Steve Antondcc3c022017-12-22 16:02:54 -08002400 const cricket::ContentInfo* video_content =
2401 GetFirstVideoContent(local_description()->description());
2402 if (video_content) {
2403 if (video_content->rejected) {
2404 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2405 } else {
2406 const cricket::VideoContentDescription* video_desc =
2407 video_content->media_description()->as_video();
2408 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2409 }
deadbeeffaac4972015-11-12 15:33:07 -08002410 }
deadbeefab9b2d12015-10-14 11:33:11 -07002411 }
2412
2413 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002414 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002415 if (data_content) {
2416 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002417 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002418 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002419 cricket::kMediaProtocolRtpPrefix)) {
2420 UpdateLocalRtpDataChannels(data_desc->streams());
2421 }
2422 }
2423
Steve Anton8a006912017-12-04 15:25:56 -08002424 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425}
2426
Steve Anton06817cd2018-12-18 15:55:30 -08002427// The SDP parser used to populate these values by default for the 'content
2428// name' if an a=mid line was absent.
2429static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2430 switch (media_type) {
2431 case cricket::MEDIA_TYPE_AUDIO:
2432 return cricket::CN_AUDIO;
2433 case cricket::MEDIA_TYPE_VIDEO:
2434 return cricket::CN_VIDEO;
2435 case cricket::MEDIA_TYPE_DATA:
2436 return cricket::CN_DATA;
2437 }
2438 RTC_NOTREACHED();
2439 return "";
2440}
2441
2442void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002443 cricket::SessionDescription* new_remote_description) {
2444 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002445 const cricket::ContentInfos& local_contents =
2446 (local_description() ? local_description()->description()->contents()
2447 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002448 const cricket::ContentInfos& remote_contents =
2449 (remote_description() ? remote_description()->description()->contents()
2450 : cricket::ContentInfos());
2451 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2452 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002453 if (!content.name.empty()) {
2454 continue;
2455 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002456 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002457 absl::string_view source_explanation;
2458 if (IsUnifiedPlan()) {
2459 if (i < local_contents.size()) {
2460 new_mid = local_contents[i].name;
2461 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002462 } else if (i < remote_contents.size()) {
2463 new_mid = remote_contents[i].name;
2464 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002465 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002466 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002467 source_explanation = "generated just now";
2468 }
2469 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002470 new_mid = std::string(
2471 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002472 source_explanation = "to match pre-existing behavior";
2473 }
Steve Antond7180cc2019-02-07 10:44:53 -08002474 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002475 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002476 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002477 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2478 << " is missing an a=mid line. Filling in the value '"
2479 << new_mid << "' " << source_explanation << ".";
2480 }
2481}
2482
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002483void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002484 SetSessionDescriptionObserver* observer,
2485 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002486 SetRemoteDescription(
2487 std::unique_ptr<SessionDescriptionInterface>(desc),
2488 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2489 new SetRemoteDescriptionObserverAdapter(this, observer)));
2490}
2491
2492void PeerConnection::SetRemoteDescription(
2493 std::unique_ptr<SessionDescriptionInterface> desc,
2494 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002495 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002496 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002497
nisse7ce109a2017-01-31 00:57:56 -08002498 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002499 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002500 return;
2501 }
Steve Anton8a006912017-12-04 15:25:56 -08002502
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002503 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002504 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002505 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002506 return;
2507 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002508
Steve Anton80dd7b52018-02-16 17:08:42 -08002509 // If a session error has occurred the PeerConnection is in a possibly
2510 // inconsistent state so fail right away.
2511 if (session_error() != SessionError::kNone) {
2512 std::string error_message = GetSessionErrorMsg();
2513 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2514 observer->OnSetRemoteDescriptionComplete(
2515 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2516 return;
2517 }
Steve Anton71439a62018-02-15 11:53:06 -08002518
Steve Antonba42e992018-04-09 14:10:01 -07002519 if (desc->GetType() == SdpType::kOffer) {
2520 // Report to UMA the format of the received offer.
2521 ReportSdpFormatReceived(*desc);
2522 }
2523
Steve Anton06817cd2018-12-18 15:55:30 -08002524 // Handle remote descriptions missing a=mid lines for interop with legacy end
2525 // points.
2526 FillInMissingRemoteMids(desc->description());
2527
Steve Anton80dd7b52018-02-16 17:08:42 -08002528 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002529 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002530 std::string error_message = GetSetDescriptionErrorMessage(
2531 cricket::CS_REMOTE, desc->GetType(), error);
2532 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002533 observer->OnSetRemoteDescriptionComplete(
2534 RTCError(error.type(), std::move(error_message)));
2535 return;
2536 }
Steve Anton71439a62018-02-15 11:53:06 -08002537
Steve Anton80dd7b52018-02-16 17:08:42 -08002538 // Grab the description type before moving ownership to
2539 // ApplyRemoteDescription, which may destroy it before returning.
2540 const SdpType type = desc->GetType();
2541
2542 error = ApplyRemoteDescription(std::move(desc));
2543 // |desc| may be destroyed at this point.
2544
2545 if (!error.ok()) {
2546 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2547 // inconsistent state, so act conservatively here and set the session error
2548 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2549 SetSessionError(SessionError::kContent, error.message());
2550 std::string error_message =
2551 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2552 RTC_LOG(LS_ERROR) << error_message;
2553 observer->OnSetRemoteDescriptionComplete(
2554 RTCError(error.type(), std::move(error_message)));
2555 return;
2556 }
2557 RTC_DCHECK(remote_description());
2558
2559 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002560 // TODO(deadbeef): We already had to hop to the network thread for
2561 // MaybeStartGathering...
2562 network_thread()->Invoke<void>(
2563 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2564 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002565 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002566 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002567 }
2568
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002569 if (IsUnifiedPlan()) {
2570 bool was_negotiation_needed = is_negotiation_needed_;
2571 UpdateNegotiationNeeded();
2572 if (signaling_state() == kStable && was_negotiation_needed &&
2573 is_negotiation_needed_) {
2574 Observer()->OnRenegotiationNeeded();
2575 }
2576 }
2577
Steve Anton8a006912017-12-04 15:25:56 -08002578 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002579 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002580}
2581
2582RTCError PeerConnection::ApplyRemoteDescription(
2583 std::unique_ptr<SessionDescriptionInterface> desc) {
2584 RTC_DCHECK_RUN_ON(signaling_thread());
2585 RTC_DCHECK(desc);
2586
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002587 // Update stats here so that we have the most recent stats for tracks and
2588 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002589 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002590
Steve Antondcc3c022017-12-22 16:02:54 -08002591 // Take a reference to the old remote description since it's used below to
2592 // compare against the new remote description. When setting the new remote
2593 // description, grab ownership of the replaced session description in case it
2594 // is the same as |old_remote_description|, to keep it alive for the duration
2595 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002596 const SessionDescriptionInterface* old_remote_description =
2597 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002598 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002599 SdpType type = desc->GetType();
2600 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002601 replaced_remote_description = pending_remote_description_
2602 ? std::move(pending_remote_description_)
2603 : std::move(current_remote_description_);
2604 current_remote_description_ = std::move(desc);
2605 pending_remote_description_ = nullptr;
2606 current_local_description_ = std::move(pending_local_description_);
2607 } else {
2608 replaced_remote_description = std::move(pending_remote_description_);
2609 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 }
Steve Anton8a006912017-12-04 15:25:56 -08002611 // The session description to apply now must be accessed by
2612 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002613 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002614
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002615 // Report statistics about any use of simulcast.
2616 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2617 *remote_description()->description());
2618
Zhi Huange830e682018-03-30 10:48:35 -07002619 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2620 if (!error.ok()) {
2621 return error;
2622 }
Steve Anton8a006912017-12-04 15:25:56 -08002623 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002624 if (IsUnifiedPlan()) {
2625 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002626 cricket::CS_REMOTE, *remote_description(), local_description(),
2627 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002628 if (!error.ok()) {
2629 return error;
2630 }
Steve Antondcc3c022017-12-22 16:02:54 -08002631 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002632 // Media channels will be created only when offer is set. These may use new
2633 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002634 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002635 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002636 // description is applied. Restore back to old description.
2637 RTCError error = CreateChannels(*remote_description()->description());
2638 if (!error.ok()) {
2639 return error;
2640 }
2641 }
Steve Antondcc3c022017-12-22 16:02:54 -08002642 // Remove unused channels if MediaContentDescription is rejected.
2643 RemoveUnusedChannels(remote_description()->description());
2644 }
Steve Anton8a006912017-12-04 15:25:56 -08002645
Zhi Huange830e682018-03-30 10:48:35 -07002646 // NOTE: Candidates allocation will be initiated only when
2647 // SetLocalDescription is called.
2648 error = UpdateSessionState(type, cricket::CS_REMOTE,
2649 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002650 if (!error.ok()) {
2651 return error;
2652 }
2653
2654 if (local_description() &&
2655 !UseCandidatesInSessionDescription(remote_description())) {
2656 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2657 }
2658
2659 if (old_remote_description) {
2660 for (const cricket::ContentInfo& content :
2661 old_remote_description->description()->contents()) {
2662 // Check if this new SessionDescription contains new ICE ufrag and
2663 // password that indicates the remote peer requests an ICE restart.
2664 // TODO(deadbeef): When we start storing both the current and pending
2665 // remote description, this should reset pending_ice_restarts and compare
2666 // against the current description.
2667 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2668 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002669 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002670 pending_ice_restarts_.insert(content.name);
2671 }
2672 } else {
2673 // We retain all received candidates only if ICE is not restarted.
2674 // When ICE is restarted, all previous candidates belong to an old
2675 // generation and should not be kept.
2676 // TODO(deadbeef): This goes against the W3C spec which says the remote
2677 // description should only contain candidates from the last set remote
2678 // description plus any candidates added since then. We should remove
2679 // this once we're sure it won't break anything.
2680 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2681 old_remote_description, content.name, mutable_remote_description());
2682 }
2683 }
2684 }
2685
2686 if (session_error() != SessionError::kNone) {
2687 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2688 }
2689
2690 // Set the the ICE connection state to connecting since the connection may
2691 // become writable with peer reflexive candidates before any remote candidate
2692 // is signaled.
2693 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2694 // is to have a new signal the indicates a change in checking state from the
2695 // transport and expose a new checking() member from transport that can be
2696 // read to determine the current checking state. The existing SignalConnecting
2697 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002698 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002699 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002700 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2701 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2702 }
2703
deadbeefab9b2d12015-10-14 11:33:11 -07002704 // If setting the description decided our SSL role, allocate any necessary
2705 // SCTP sids.
2706 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002707 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002708 AllocateSctpSids(role);
2709 }
2710
Steve Antondcc3c022017-12-22 16:02:54 -08002711 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002712 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002713 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002714 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002715 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002716 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002717 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002718 const ContentInfo* content =
2719 FindMediaSectionForTransceiver(transceiver, remote_description());
2720 if (!content) {
2721 continue;
2722 }
2723 const MediaContentDescription* media_desc = content->media_description();
2724 RtpTransceiverDirection local_direction =
2725 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002726 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2727 // RTCSessionDescription: Set the associated remote streams given
2728 // transceiver.[[Receiver]], msids, addList, and removeList".
2729 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2730 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2731 std::vector<std::string> stream_ids;
2732 if (!media_desc->streams().empty()) {
2733 // The remote description has signaled the stream IDs.
2734 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002735 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002736 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2737 << " (" << GetStreamIdsString(stream_ids) << ").";
2738 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2739 stream_ids, &added_streams,
2740 &removed_streams);
2741 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2742 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2743 // and transceiver's current direction is neither sendrecv nor recvonly,
2744 // process the addition of a remote track for the media description.
2745 if (!transceiver->fired_direction() ||
2746 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2747 RTC_LOG(LS_INFO)
2748 << "Processing the addition of a remote track for MID="
2749 << content->name << ".";
2750 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002751 }
Steve Antondcc3c022017-12-22 16:02:54 -08002752 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002753 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002754 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2755 // removal of a remote track for the media description, given transceiver,
2756 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002757 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002758 (transceiver->fired_direction() &&
2759 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2760 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2761 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002762 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002763 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002764 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002765 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002766 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002767 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002768 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002769 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002770 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002771 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2772 if (transceiver->mid()) {
2773 auto dtls_transport =
2774 LookupDtlsTransportByMidInternal(*transceiver->mid());
2775 transceiver->internal()->sender_internal()->set_transport(
2776 dtls_transport);
2777 transceiver->internal()->receiver_internal()->set_transport(
2778 dtls_transport);
2779 }
Steve Antondcc3c022017-12-22 16:02:54 -08002780 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002781 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002782 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002783 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002784 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2785 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002786 transceiver->Stop();
2787 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002788 if (!content->rejected &&
2789 RtpTransceiverDirectionHasRecv(local_direction)) {
2790 // Set ssrc to 0 in the case of an unsignalled ssrc.
2791 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002792 if (!media_desc->streams().empty() &&
2793 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002794 ssrc = media_desc->streams()[0].first_ssrc();
2795 }
2796 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002797 }
Steve Antondcc3c022017-12-22 16:02:54 -08002798 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002799 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002800 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002801 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002802 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002803 observer->OnTrack(transceiver);
2804 observer->OnAddTrack(transceiver->receiver(),
2805 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002806 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002807 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002808 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002809 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002810 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002811 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002812 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002813 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002814 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002815 }
Steve Antondcc3c022017-12-22 16:02:54 -08002816 }
2817
Henrik Boströmfdb92012017-11-09 19:55:44 +01002818 const cricket::ContentInfo* audio_content =
2819 GetFirstAudioContent(remote_description()->description());
2820 const cricket::ContentInfo* video_content =
2821 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002822 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002823 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002824 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002825 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002826 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002827 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002828
2829 // Check if the descriptions include streams, just in case the peer supports
2830 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002831 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002832 (audio_desc && !audio_desc->streams().empty()) ||
2833 (video_desc && !video_desc->streams().empty())) {
2834 remote_peer_supports_msid_ = true;
2835 }
deadbeefab9b2d12015-10-14 11:33:11 -07002836
2837 // We wait to signal new streams until we finish processing the description,
2838 // since only at that point will new streams have all their tracks.
2839 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2840
Steve Antondcc3c022017-12-22 16:02:54 -08002841 if (!IsUnifiedPlan()) {
2842 // TODO(steveanton): When removing RTP senders/receivers in response to a
2843 // rejected media section, there is some cleanup logic that expects the
2844 // voice/ video channel to still be set. But in this method the voice/video
2845 // channel would have been destroyed by the SetRemoteDescription caller
2846 // above so the cleanup that relies on them fails to run. The RemoveSenders
2847 // calls should be moved to right before the DestroyChannel calls to fix
2848 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002849
Steve Antondcc3c022017-12-22 16:02:54 -08002850 // Find all audio rtp streams and create corresponding remote AudioTracks
2851 // and MediaStreams.
2852 if (audio_content) {
2853 if (audio_content->rejected) {
2854 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2855 } else {
2856 bool default_audio_track_needed =
2857 !remote_peer_supports_msid_ &&
2858 RtpTransceiverDirectionHasSend(audio_desc->direction());
2859 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2860 default_audio_track_needed, audio_desc->type(),
2861 new_streams);
2862 }
deadbeeffaac4972015-11-12 15:33:07 -08002863 }
deadbeefab9b2d12015-10-14 11:33:11 -07002864
Steve Antondcc3c022017-12-22 16:02:54 -08002865 // Find all video rtp streams and create corresponding remote VideoTracks
2866 // and MediaStreams.
2867 if (video_content) {
2868 if (video_content->rejected) {
2869 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2870 } else {
2871 bool default_video_track_needed =
2872 !remote_peer_supports_msid_ &&
2873 RtpTransceiverDirectionHasSend(video_desc->direction());
2874 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2875 default_video_track_needed, video_desc->type(),
2876 new_streams);
2877 }
deadbeeffaac4972015-11-12 15:33:07 -08002878 }
deadbeefab9b2d12015-10-14 11:33:11 -07002879
Steve Antondcc3c022017-12-22 16:02:54 -08002880 // Update the DataChannels with the information from the remote peer.
2881 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002882 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002883 cricket::kMediaProtocolRtpPrefix)) {
2884 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2885 }
deadbeefab9b2d12015-10-14 11:33:11 -07002886 }
deadbeefab9b2d12015-10-14 11:33:11 -07002887
Steve Antondcc3c022017-12-22 16:02:54 -08002888 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002889 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002890 for (size_t i = 0; i < new_streams->count(); ++i) {
2891 MediaStreamInterface* new_stream = new_streams->at(i);
2892 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002893 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002894 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2895 }
deadbeefab9b2d12015-10-14 11:33:11 -07002896
Steve Antondcc3c022017-12-22 16:02:54 -08002897 UpdateEndedRemoteMediaStreams();
2898 }
deadbeefab9b2d12015-10-14 11:33:11 -07002899
Steve Anton8a006912017-12-04 15:25:56 -08002900 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002901}
2902
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002903void PeerConnection::SetAssociatedRemoteStreams(
2904 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2905 const std::vector<std::string>& stream_ids,
2906 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2907 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2908 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2909 for (const std::string& stream_id : stream_ids) {
2910 rtc::scoped_refptr<MediaStreamInterface> stream =
2911 remote_streams_->find(stream_id);
2912 if (!stream) {
2913 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2914 MediaStream::Create(stream_id));
2915 remote_streams_->AddStream(stream);
2916 added_streams->push_back(stream);
2917 }
2918 media_streams.push_back(stream);
2919 }
2920 // Special case: "a=msid" missing, use random stream ID.
2921 if (media_streams.empty() &&
2922 !(remote_description()->description()->msid_signaling() &
2923 cricket::kMsidSignalingMediaSection)) {
2924 if (!missing_msid_default_stream_) {
2925 missing_msid_default_stream_ = MediaStreamProxy::Create(
2926 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2927 added_streams->push_back(missing_msid_default_stream_);
2928 }
2929 media_streams.push_back(missing_msid_default_stream_);
2930 }
2931 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2932 receiver->streams();
2933 // SetStreams() will add/remove the receiver's track to/from the streams. This
2934 // differs from the spec - the spec uses an "addList" and "removeList" to
2935 // update the stream-track relationships in a later step. We do this earlier,
2936 // changing the order of things, but the end-result is the same.
2937 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2938 // instead. https://crbug.com/webrtc/9480
2939 receiver->SetStreams(media_streams);
2940 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2941}
2942
Steve Anton0f5400a2018-07-17 14:25:36 -07002943void PeerConnection::ProcessRemovalOfRemoteTrack(
2944 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2945 transceiver,
2946 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2947 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2948 RTC_DCHECK(transceiver->mid());
2949 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2950 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002951 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002952 transceiver->internal()->receiver_internal()->streams();
2953 // This will remove the remote track from the streams.
2954 transceiver->internal()->receiver_internal()->set_stream_ids({});
2955 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002956 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2957}
2958
2959void PeerConnection::RemoveRemoteStreamsIfEmpty(
2960 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2961 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2962 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2963 // streams, see if the stream was removed by checking if this was the last
2964 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002965 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002966 if (remote_stream->GetAudioTracks().empty() &&
2967 remote_stream->GetVideoTracks().empty()) {
2968 remote_streams_->RemoveStream(remote_stream);
2969 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002970 }
2971 }
2972}
2973
Steve Antondcc3c022017-12-22 16:02:54 -08002974RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2975 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002976 const SessionDescriptionInterface& new_session,
2977 const SessionDescriptionInterface* old_local_description,
2978 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002979 RTC_DCHECK(IsUnifiedPlan());
2980
Steve Anton7464fca2018-01-19 11:10:37 -08002981 const cricket::ContentGroup* bundle_group = nullptr;
2982 if (new_session.GetType() == SdpType::kOffer) {
2983 auto bundle_group_or_error =
2984 GetEarlyBundleGroup(*new_session.description());
2985 if (!bundle_group_or_error.ok()) {
2986 return bundle_group_or_error.MoveError();
2987 }
2988 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002989 }
Steve Antondcc3c022017-12-22 16:02:54 -08002990
Steve Antondcc3c022017-12-22 16:02:54 -08002991 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002992 for (size_t i = 0; i < new_contents.size(); ++i) {
2993 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002994 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002995 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002996 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2997 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002998 const cricket::ContentInfo* old_local_content = nullptr;
2999 if (old_local_description &&
3000 i < old_local_description->description()->contents().size()) {
3001 old_local_content =
3002 &old_local_description->description()->contents()[i];
3003 }
3004 const cricket::ContentInfo* old_remote_content = nullptr;
3005 if (old_remote_description &&
3006 i < old_remote_description->description()->contents().size()) {
3007 old_remote_content =
3008 &old_remote_description->description()->contents()[i];
3009 }
Steve Antondcc3c022017-12-22 16:02:54 -08003010 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003011 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3012 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003013 if (!transceiver_or_error.ok()) {
3014 return transceiver_or_error.MoveError();
3015 }
3016 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003017 RTCError error =
3018 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3019 if (!error.ok()) {
3020 return error;
3021 }
3022 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003023 if (GetDataMid() && new_content.name != *GetDataMid()) {
3024 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003025 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3026 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003027 continue;
3028 }
3029 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3030 if (!error.ok()) {
3031 return error;
3032 }
Steve Antondcc3c022017-12-22 16:02:54 -08003033 } else {
3034 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3035 "Unknown section type.");
3036 }
3037 }
3038
3039 return RTCError::OK();
3040}
3041
3042RTCError PeerConnection::UpdateTransceiverChannel(
3043 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3044 transceiver,
3045 const cricket::ContentInfo& content,
3046 const cricket::ContentGroup* bundle_group) {
3047 RTC_DCHECK(IsUnifiedPlan());
3048 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003049 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003050 if (content.rejected) {
3051 if (channel) {
3052 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003053 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003054 }
3055 } else {
3056 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003057 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003058 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003059 } else {
Steve Anton69470252018-02-09 11:43:08 -08003060 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003061 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003062 }
3063 if (!channel) {
3064 LOG_AND_RETURN_ERROR(
3065 RTCErrorType::INTERNAL_ERROR,
3066 "Failed to create channel for mid=" + content.name);
3067 }
3068 transceiver->internal()->SetChannel(channel);
3069 }
3070 }
3071 return RTCError::OK();
3072}
3073
Steve Antonfa2260d2017-12-28 16:38:23 -08003074RTCError PeerConnection::UpdateDataChannel(
3075 cricket::ContentSource source,
3076 const cricket::ContentInfo& content,
3077 const cricket::ContentGroup* bundle_group) {
3078 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003079 // If data channels are disabled, ignore this media section. CreateAnswer
3080 // will take care of rejecting it.
3081 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003082 }
3083 if (content.rejected) {
3084 DestroyDataChannel();
3085 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003086 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003087 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003088 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3089 "Failed to create data channel.");
3090 }
3091 }
3092 if (source == cricket::CS_REMOTE) {
3093 const MediaContentDescription* data_desc = content.media_description();
3094 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3095 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3096 }
3097 }
3098 }
3099 return RTCError::OK();
3100}
3101
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003102// This method will extract any send encodings that were sent by the remote
3103// connection. This is currently only relevant for Simulcast scenario (where
3104// the number of layers may be communicated by the server).
3105static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3106 const MediaContentDescription& desc) {
3107 if (!desc.HasSimulcast()) {
3108 return {};
3109 }
3110 std::vector<RtpEncodingParameters> result;
3111 const SimulcastDescription& simulcast = desc.simulcast_description();
3112
3113 // This is a remote description, the parameters we are after should appear
3114 // as receive streams.
3115 for (const auto& alternatives : simulcast.receive_layers()) {
3116 RTC_DCHECK(!alternatives.empty());
3117 // There is currently no way to specify or choose from alternatives.
3118 // We will always use the first alternative, which is the most preferred.
3119 const SimulcastLayer& layer = alternatives[0];
3120 RtpEncodingParameters parameters;
3121 parameters.rid = layer.rid;
3122 parameters.active = !layer.is_paused;
3123 result.push_back(parameters);
3124 }
3125
3126 return result;
3127}
3128
3129static RTCError UpdateSimulcastLayerStatusInSender(
3130 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003131 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003132 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003133 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003134 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003135
3136 // The simulcast envelope cannot be changed, only the status of the streams.
3137 // So we will iterate over the send encodings rather than the layers.
3138 for (RtpEncodingParameters& encoding : parameters.encodings) {
3139 auto iter = std::find_if(layers.begin(), layers.end(),
3140 [&encoding](const SimulcastLayer& layer) {
3141 return layer.rid == encoding.rid;
3142 });
3143 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003144 if (iter == layers.end()) {
3145 disabled_layers.push_back(encoding.rid);
3146 continue;
3147 }
3148
3149 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003150 }
3151
Amit Hilbuch619b2942019-02-26 15:55:19 -08003152 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003153 if (result.ok()) {
3154 result = sender->DisableEncodingLayers(disabled_layers);
3155 }
3156
3157 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003158}
3159
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003160static bool SimulcastIsRejected(
3161 const ContentInfo* local_content,
3162 const MediaContentDescription& answer_media_desc) {
3163 bool simulcast_offered = local_content &&
3164 local_content->media_description() &&
3165 local_content->media_description()->HasSimulcast();
3166 bool simulcast_answered = answer_media_desc.HasSimulcast();
3167 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3168 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3169 return simulcast_offered && (!simulcast_answered || !rids_supported);
3170}
3171
Amit Hilbuch2297d332019-02-19 12:49:22 -08003172static RTCError DisableSimulcastInSender(
3173 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003174 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003175 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003176 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003177 return RTCError::OK();
3178 }
3179
Amit Hilbuch2297d332019-02-19 12:49:22 -08003180 std::vector<std::string> disabled_layers;
3181 std::transform(
3182 parameters.encodings.begin() + 1, parameters.encodings.end(),
3183 std::back_inserter(disabled_layers),
3184 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3185 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003186}
3187
Steve Antondcc3c022017-12-22 16:02:54 -08003188RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3189PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003190 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003191 size_t mline_index,
3192 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003193 const ContentInfo* old_local_content,
3194 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003195 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003196 // If this is an offer then the m= section might be recycled. If the m=
3197 // section is being recycled (defined as: rejected in the current local or
3198 // remote description and not rejected in new description), dissociate the
3199 // currently associated RtpTransceiver by setting its mid property to null,
3200 // and discard the mapping between the transceiver and its m= section index.
3201 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3202 old_remote_content)) {
3203 // We want to dissociate the transceiver that has the rejected mid.
3204 const std::string& old_mid =
3205 (old_local_content && old_local_content->rejected)
3206 ? old_local_content->name
3207 : old_remote_content->name;
3208 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003209 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003210 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3211 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003212 old_transceiver->internal()->set_mid(absl::nullopt);
3213 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003214 }
3215 }
3216 const MediaContentDescription* media_desc = content.media_description();
3217 auto transceiver = GetAssociatedTransceiver(content.name);
3218 if (source == cricket::CS_LOCAL) {
3219 // Find the RtpTransceiver that corresponds to this m= section, using the
3220 // mapping between transceivers and m= section indices established when
3221 // creating the offer.
3222 if (!transceiver) {
3223 transceiver = GetTransceiverByMLineIndex(mline_index);
3224 }
3225 if (!transceiver) {
3226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3227 "Unknown transceiver");
3228 }
3229 } else {
3230 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3231 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3232 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003233 // When simulcast is requested, a transceiver cannot be associated because
3234 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003235 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003236 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3237 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003238 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3239 }
3240 // If no RtpTransceiver was found in the previous step, create one with a
3241 // recvonly direction.
3242 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003243 RTC_LOG(LS_INFO) << "Adding "
3244 << cricket::MediaTypeToString(media_desc->type())
3245 << " transceiver for MID=" << content.name
3246 << " at i=" << mline_index
3247 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003248 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003249 std::vector<RtpEncodingParameters> send_encodings =
3250 GetSendEncodingsFromRemoteDescription(*media_desc);
3251 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3252 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003253 std::string receiver_id;
3254 if (!media_desc->streams().empty()) {
3255 receiver_id = media_desc->streams()[0].id;
3256 } else {
3257 receiver_id = rtc::CreateRandomUuid();
3258 }
3259 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003260 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003261 transceiver->internal()->set_direction(
3262 RtpTransceiverDirection::kRecvOnly);
3263 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003264
3265 // Check if the offer indicated simulcast but the answer rejected it.
3266 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003267 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003268 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003269 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003270 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003271 if (!error.ok()) {
3272 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3273 return std::move(error);
3274 }
3275 }
Steve Antondcc3c022017-12-22 16:02:54 -08003276 }
3277 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003278 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003279 LOG_AND_RETURN_ERROR(
3280 RTCErrorType::INVALID_PARAMETER,
3281 "Transceiver type does not match media description type.");
3282 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003283 if (media_desc->HasSimulcast()) {
3284 std::vector<SimulcastLayer> layers =
3285 source == cricket::CS_LOCAL
3286 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3287 : media_desc->simulcast_description()
3288 .receive_layers()
3289 .GetAllLayers();
3290 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003291 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003292 if (!error.ok()) {
3293 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3294 return std::move(error);
3295 }
3296 }
Steve Antondcc3c022017-12-22 16:02:54 -08003297 // Associate the found or created RtpTransceiver with the m= section by
3298 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3299 // section, and establish a mapping between the transceiver and the index of
3300 // the m= section.
3301 transceiver->internal()->set_mid(content.name);
3302 transceiver->internal()->set_mline_index(mline_index);
3303 return std::move(transceiver);
3304}
3305
3306rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3307PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3308 RTC_DCHECK(IsUnifiedPlan());
3309 for (auto transceiver : transceivers_) {
3310 if (transceiver->mid() == mid) {
3311 return transceiver;
3312 }
3313 }
3314 return nullptr;
3315}
3316
3317rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3318PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3319 RTC_DCHECK(IsUnifiedPlan());
3320 for (auto transceiver : transceivers_) {
3321 if (transceiver->internal()->mline_index() == mline_index) {
3322 return transceiver;
3323 }
3324 }
3325 return nullptr;
3326}
3327
3328rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3329PeerConnection::FindAvailableTransceiverToReceive(
3330 cricket::MediaType media_type) const {
3331 RTC_DCHECK(IsUnifiedPlan());
3332 // From JSEP section 5.10 (Applying a Remote Description):
3333 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3334 // the same type that were added to the PeerConnection by addTrack and are not
3335 // associated with any m= section and are not stopped, find the first such
3336 // RtpTransceiver.
3337 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003338 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003339 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3340 !transceiver->stopped()) {
3341 return transceiver;
3342 }
3343 }
3344 return nullptr;
3345}
3346
Steve Antoned10bd92017-12-05 10:52:59 -08003347const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3348 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3349 transceiver,
3350 const SessionDescriptionInterface* sdesc) const {
3351 RTC_DCHECK(transceiver);
3352 RTC_DCHECK(sdesc);
3353 if (IsUnifiedPlan()) {
3354 if (!transceiver->internal()->mid()) {
3355 // This transceiver is not associated with a media section yet.
3356 return nullptr;
3357 }
3358 return sdesc->description()->GetContentByName(
3359 *transceiver->internal()->mid());
3360 } else {
3361 // Plan B only allows at most one audio and one video section, so use the
3362 // first media section of that type.
3363 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003364 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003365 }
3366}
3367
deadbeef46c73892016-11-16 19:42:04 -08003368PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003369 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003370 return configuration_;
3371}
3372
deadbeef293e9262017-01-11 12:28:30 -08003373bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3374 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003375 RTC_DCHECK_RUN_ON(signaling_thread());
3376 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003377 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003378 if (IsClosed()) {
3379 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3380 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3381 }
3382
Qingsi Wanga2d60672018-04-11 16:57:45 -07003383 // According to JSEP, after setLocalDescription, changing the candidate pool
3384 // size is not allowed, and changing the set of ICE servers will not result
3385 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003386 if (local_description() && configuration.ice_candidate_pool_size !=
3387 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003388 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3389 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003390 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003391 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003392
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003393 if (local_description() &&
3394 configuration.use_media_transport != configuration_.use_media_transport) {
3395 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3396 "SetLocalDescription.";
3397 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3398 }
3399
3400 if (remote_description() &&
3401 configuration.use_media_transport != configuration_.use_media_transport) {
3402 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3403 "SetRemoteDescription.";
3404 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3405 }
3406
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003407 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003408 configuration.use_media_transport_for_data_channels !=
3409 configuration_.use_media_transport_for_data_channels) {
3410 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3411 "after calling SetLocalDescription.";
3412 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3413 }
3414
3415 if (remote_description() &&
3416 configuration.use_media_transport_for_data_channels !=
3417 configuration_.use_media_transport_for_data_channels) {
3418 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3419 "after calling SetRemoteDescription.";
3420 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3421 }
3422
3423 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003424 configuration.crypto_options != configuration_.crypto_options) {
3425 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3426 "SetLocalDescription.";
3427 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3428 }
3429
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003430 if (configuration.use_media_transport_for_data_channels ||
3431 configuration.use_media_transport) {
3432 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3433 << "Media transport requires MaxBundle policy.";
3434 }
3435
deadbeef293e9262017-01-11 12:28:30 -08003436 // The simplest (and most future-compatible) way to tell if the config was
3437 // modified in an invalid way is to copy each property we do support
3438 // modifying, then use operator==. There are far more properties we don't
3439 // support modifying than those we do, and more could be added.
3440 RTCConfiguration modified_config = configuration_;
3441 modified_config.servers = configuration.servers;
3442 modified_config.type = configuration.type;
3443 modified_config.ice_candidate_pool_size =
3444 configuration.ice_candidate_pool_size;
3445 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003446 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003447 modified_config.ice_check_interval_strong_connectivity =
3448 configuration.ice_check_interval_strong_connectivity;
3449 modified_config.ice_check_interval_weak_connectivity =
3450 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003451 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3452 modified_config.ice_unwritable_min_checks =
3453 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003454 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003455 modified_config.stun_candidate_keepalive_interval =
3456 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003457 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003458 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003459 modified_config.active_reset_srtp_params =
3460 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003461 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003462 modified_config.use_media_transport_for_data_channels =
3463 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003464 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003465 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003466 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3467 }
3468
Steve Anton038834f2017-07-14 15:59:59 -07003469 // Validate the modified configuration.
3470 RTCError validate_error = ValidateConfiguration(modified_config);
3471 if (!validate_error.ok()) {
3472 return SafeSetError(std::move(validate_error), error);
3473 }
3474
deadbeef293e9262017-01-11 12:28:30 -08003475 // Note that this isn't possible through chromium, since it's an unsigned
3476 // short in WebIDL.
3477 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003478 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003479 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3480 }
3481
3482 // Parse ICE servers before hopping to network thread.
3483 cricket::ServerAddresses stun_servers;
3484 std::vector<cricket::RelayServerConfig> turn_servers;
3485 RTCErrorType parse_error =
3486 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3487 if (parse_error != RTCErrorType::NONE) {
3488 return SafeSetError(parse_error, error);
3489 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003490 // Note if STUN or TURN servers were supplied.
3491 if (!stun_servers.empty()) {
3492 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3493 }
3494 if (!turn_servers.empty()) {
3495 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3496 }
deadbeef293e9262017-01-11 12:28:30 -08003497
3498 // In theory this shouldn't fail.
3499 if (!network_thread()->Invoke<bool>(
3500 RTC_FROM_HERE,
3501 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3502 stun_servers, turn_servers, modified_config.type,
3503 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003504 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003505 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003506 modified_config.stun_candidate_keepalive_interval,
3507 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003508 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003509 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3510 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003511
deadbeefd1a38b52016-12-10 13:15:33 -08003512 // As described in JSEP, calling setConfiguration with new ICE servers or
3513 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3514 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003515 if (modified_config.servers != configuration_.servers ||
3516 modified_config.type != configuration_.type ||
3517 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003518 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003519 }
skvladd1f5fda2017-02-03 16:54:05 -08003520
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003521 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003522 transport_controller_->SetMediaTransportSettings(
3523 modified_config.use_media_transport,
3524 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003525
Zhi Huangb57e1692018-06-12 11:41:11 -07003526 if (configuration_.active_reset_srtp_params !=
3527 modified_config.active_reset_srtp_params) {
3528 transport_controller_->SetActiveResetSrtpParams(
3529 modified_config.active_reset_srtp_params);
3530 }
3531
deadbeef293e9262017-01-11 12:28:30 -08003532 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003533 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003534 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003535}
3536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003537bool PeerConnection::AddIceCandidate(
3538 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003539 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003540 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003541 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003542 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003543 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003544 return false;
3545 }
Steve Antond25da372017-11-06 14:50:29 -08003546
3547 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003548 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003549 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003550 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003551 return false;
3552 }
3553
3554 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003555 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003556 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003557 return false;
3558 }
3559
3560 bool valid = false;
3561 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3562 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003563 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003564 return false;
3565 }
3566
3567 // Add this candidate to the remote session description.
3568 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003569 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003570 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003571 return false;
3572 }
3573
3574 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003575 bool result = UseCandidate(ice_candidate);
3576 if (result) {
3577 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3578 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3579 } else {
3580 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3581 }
3582 return result;
Steve Antond25da372017-11-06 14:50:29 -08003583 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003584 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003585 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003586 return true;
3587 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003588}
3589
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003590bool PeerConnection::RemoveIceCandidates(
3591 const std::vector<cricket::Candidate>& candidates) {
3592 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003593 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003594 if (IsClosed()) {
3595 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3596 return false;
3597 }
3598
Steve Antond25da372017-11-06 14:50:29 -08003599 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003600 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3601 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003602 return false;
3603 }
3604
3605 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003606 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003607 return false;
3608 }
3609
3610 size_t number_removed =
3611 mutable_remote_description()->RemoveCandidates(candidates);
3612 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003613 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003614 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003615 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003616 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003617 }
3618
3619 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003620 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3621 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003622 RTC_LOG(LS_ERROR)
3623 << "RemoveIceCandidates: Error when removing remote candidates: "
3624 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003625 }
3626 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003627}
3628
Niels Möller0c4f7be2018-05-07 14:01:37 +02003629RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003630 if (!worker_thread()->IsCurrent()) {
3631 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003632 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003633 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003634 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003635
Niels Möller0c4f7be2018-05-07 14:01:37 +02003636 const bool has_min = bitrate.min_bitrate_bps.has_value();
3637 const bool has_start = bitrate.start_bitrate_bps.has_value();
3638 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003639 if (has_min && *bitrate.min_bitrate_bps < 0) {
3640 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3641 "min_bitrate_bps <= 0");
3642 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003643 if (has_start) {
3644 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003645 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003646 "start_bitrate_bps < min_bitrate_bps");
3647 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003648 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3649 "curent_bitrate_bps < 0");
3650 }
3651 }
3652 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003653 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003654 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003655 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003656 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3657 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3658 "max_bitrate_bps < min_bitrate_bps");
3659 } else if (*bitrate.max_bitrate_bps < 0) {
3660 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3661 "max_bitrate_bps < 0");
3662 }
3663 }
3664
zstein4b979802017-06-02 14:37:37 -07003665 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003666 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003667
3668 return RTCError::OK();
3669}
3670
Alex Narest78609d52017-10-20 10:37:47 +02003671void PeerConnection::SetBitrateAllocationStrategy(
3672 std::unique_ptr<rtc::BitrateAllocationStrategy>
3673 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003674 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003675 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3676 // move-capture values in lambdas.
3677 struct Task {
3678 PeerConnection* const pc;
3679 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3680 void operator()() {
3681 RTC_DCHECK_RUN_ON(pc->worker_thread());
3682 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3683 }
3684 };
3685 worker_thread()->Invoke<void>(
3686 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003687 return;
3688 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003689 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003690 RTC_DCHECK(call_.get());
3691 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3692}
3693
henrika5f6bf242017-11-01 11:06:56 +01003694void PeerConnection::SetAudioPlayout(bool playout) {
3695 if (!worker_thread()->IsCurrent()) {
3696 worker_thread()->Invoke<void>(
3697 RTC_FROM_HERE,
3698 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3699 return;
3700 }
3701 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003702 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003703 audio_state->SetPlayout(playout);
3704}
3705
3706void PeerConnection::SetAudioRecording(bool recording) {
3707 if (!worker_thread()->IsCurrent()) {
3708 worker_thread()->Invoke<void>(
3709 RTC_FROM_HERE,
3710 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3711 return;
3712 }
3713 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003714 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003715 audio_state->SetRecording(recording);
3716}
3717
Steve Anton8c0f7a72017-10-03 10:03:10 -07003718std::unique_ptr<rtc::SSLCertificate>
3719PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003720 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3721 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003722 return nullptr;
3723 }
Steve Antonf25303e2018-10-16 15:23:31 -07003724 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003725}
3726
Zhi Huang70b820f2018-01-27 14:16:15 -08003727std::unique_ptr<rtc::SSLCertChain>
3728PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003729 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003730 auto audio_transceiver = GetFirstAudioTransceiver();
3731 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003732 return nullptr;
3733 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003734 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003735 audio_transceiver->internal()->channel()->transport_name());
3736}
3737
3738rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3739PeerConnection::GetFirstAudioTransceiver() const {
3740 for (auto transceiver : transceivers_) {
3741 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3742 return transceiver;
3743 }
3744 }
3745 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003746}
3747
ivoc14d5dbe2016-07-04 07:06:55 -07003748bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3749 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003750 // TODO(eladalon): It would be better to not allow negative values into PC.
3751 const size_t max_size = (max_size_bytes < 0)
3752 ? RtcEventLog::kUnlimitedOutput
3753 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003754 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3755 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3756 output_period_ms = 5000;
3757 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003758 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003759 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003760 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003761}
3762
Bjorn Tereliusde939432017-11-20 17:38:14 +01003763bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3764 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003765 // TODO(eladalon): In C++14, this can be done with a lambda.
3766 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003767 bool operator()() {
3768 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3769 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003770 PeerConnection* const pc;
3771 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003772 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003773 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003774 return worker_thread()->Invoke<bool>(
3775 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003776}
3777
3778void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003779 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003780 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3781}
3782
Harald Alvestrandad88c882018-11-28 16:47:46 +01003783rtc::scoped_refptr<DtlsTransportInterface>
3784PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003785 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003786 return transport_controller_->LookupDtlsTransportByMid(mid);
3787}
3788
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003789rtc::scoped_refptr<DtlsTransport>
3790PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003791 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003792 return transport_controller_->LookupDtlsTransportByMid(mid);
3793}
3794
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003795rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3796 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003797 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003798 return sctp_transport_;
3799}
3800
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003801const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003802 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003803 return pending_local_description_ ? pending_local_description_.get()
3804 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003805}
3806
3807const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003808 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003809 return pending_remote_description_ ? pending_remote_description_.get()
3810 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003811}
3812
deadbeeffe4a8a42016-12-20 17:56:17 -08003813const SessionDescriptionInterface* PeerConnection::current_local_description()
3814 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003815 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003816 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003817}
3818
3819const SessionDescriptionInterface* PeerConnection::current_remote_description()
3820 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003821 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003822 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003823}
3824
3825const SessionDescriptionInterface* PeerConnection::pending_local_description()
3826 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003827 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003828 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003829}
3830
3831const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3832 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003833 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003834 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003835}
3836
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003837void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003838 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003839 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003840 // Update stats here so that we have the most recent stats for tracks and
3841 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003842 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003843
Steve Anton75737c02017-11-06 10:37:17 -08003844 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003845 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003846
Mirko Bonadei739baf02019-01-27 17:29:42 +01003847 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003848 transceiver->Stop();
3849 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003850
3851 // Ensure that all asynchronous stats requests are completed before destroying
3852 // the transport controller below.
3853 if (stats_collector_) {
3854 stats_collector_->WaitForPendingRequest();
3855 }
3856
3857 // Don't destroy BaseChannels until after stats has been cleaned up so that
3858 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003859 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003860
Qingsi Wang93a84392018-01-30 17:13:09 -08003861 // The event log is used in the transport controller, which must be outlived
3862 // by the former. CreateOffer by the peer connection is implemented
3863 // asynchronously and if the peer connection is closed without resetting the
3864 // WebRTC session description factory, the session description factory would
3865 // call the transport controller.
3866 webrtc_session_desc_factory_.reset();
3867 transport_controller_.reset();
3868
deadbeef42a42632017-03-10 15:18:00 -08003869 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003870 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3871 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003872
Steve Anton978b8762017-09-29 12:15:02 -07003873 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003874 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003875 call_.reset();
3876 // The event log must outlive call (and any other object that uses it).
3877 event_log_.reset();
3878 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003879 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003880 // The .h file says that observer can be discarded after close() returns.
3881 // Make sure this is true.
3882 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003883}
3884
Steve Antonad182762018-09-05 20:22:40 +00003885void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003886 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003887 switch (msg->message_id) {
3888 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3889 SetSessionDescriptionMsg* param =
3890 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3891 param->observer->OnSuccess();
3892 delete param;
3893 break;
3894 }
3895 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3896 SetSessionDescriptionMsg* param =
3897 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3898 param->observer->OnFailure(std::move(param->error));
3899 delete param;
3900 break;
3901 }
3902 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3903 CreateSessionDescriptionMsg* param =
3904 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3905 param->observer->OnFailure(std::move(param->error));
3906 delete param;
3907 break;
3908 }
3909 case MSG_GETSTATS: {
3910 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3911 StatsReports reports;
3912 stats_->GetStats(param->track, &reports);
3913 param->observer->OnComplete(reports);
3914 delete param;
3915 break;
3916 }
3917 case MSG_FREE_DATACHANNELS: {
3918 sctp_data_channels_to_free_.clear();
3919 break;
3920 }
3921 case MSG_REPORT_USAGE_PATTERN: {
3922 ReportUsagePattern();
3923 break;
3924 }
3925 default:
3926 RTC_NOTREACHED() << "Not implemented";
3927 break;
3928 }
3929}
3930
Steve Antonafb0bb72018-02-20 11:35:37 -08003931cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3932 RTC_DCHECK(!IsUnifiedPlan());
3933 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3934 GetAudioTransceiver()->internal()->channel());
3935 if (voice_channel) {
3936 return voice_channel->media_channel();
3937 } else {
3938 return nullptr;
3939 }
3940}
3941
3942cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3943 RTC_DCHECK(!IsUnifiedPlan());
3944 auto* video_channel = static_cast<cricket::VideoChannel*>(
3945 GetVideoTransceiver()->internal()->channel());
3946 if (video_channel) {
3947 return video_channel->media_channel();
3948 } else {
3949 return nullptr;
3950 }
3951}
3952
Steve Anton4171afb2017-11-20 10:20:22 -08003953void PeerConnection::CreateAudioReceiver(
3954 MediaStreamInterface* stream,
3955 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003956 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3957 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003958 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3959 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003960 auto* audio_receiver = new AudioRtpReceiver(
3961 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003962 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003963 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3964 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3965 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003966 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003967 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003968 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003969}
3970
Steve Anton4171afb2017-11-20 10:20:22 -08003971void PeerConnection::CreateVideoReceiver(
3972 MediaStreamInterface* stream,
3973 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003974 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3975 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003976 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3977 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003978 auto* video_receiver = new VideoRtpReceiver(
3979 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003980 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003981 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3982 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3983 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003984 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003985 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003986 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003987}
3988
deadbeef70ab1a12015-09-28 16:53:55 -07003989// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3990// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003991rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003992 const RtpSenderInfo& remote_sender_info) {
3993 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3994 if (!receiver) {
3995 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3996 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003997 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003998 }
Steve Anton4171afb2017-11-20 10:20:22 -08003999 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4000 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4001 } else {
4002 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4003 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004004 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004005}
4006
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004007void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4008 MediaStreamInterface* stream) {
4009 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004010 RTC_DCHECK(track);
4011 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004012 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004013 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004014 // We already have a sender for this track, so just change the stream_id
4015 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004016 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004017 return;
4018 }
4019
4020 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004021 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004022 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004023 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004024 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004025 // If the sender has already been configured in SDP, we call SetSsrc,
4026 // which will connect the sender to the underlying transport. This can
4027 // occur if a local session description that contains the ID of the sender
4028 // is set before AddStream is called. It can also occur if the local
4029 // session description is not changed and RemoveStream is called, and
4030 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004031 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004032 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004033 if (sender_info) {
4034 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004035 }
4036}
4037
4038// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4039// indefinitely, when we have unified plan SDP.
4040void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4041 MediaStreamInterface* stream) {
4042 RTC_DCHECK(!IsClosed());
4043 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004044 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004045 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4046 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004047 return;
4048 }
Steve Anton4171afb2017-11-20 10:20:22 -08004049 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004050}
4051
4052void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4053 MediaStreamInterface* stream) {
4054 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004055 RTC_DCHECK(track);
4056 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004057 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004058 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004059 // We already have a sender for this track, so just change the stream_id
4060 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004061 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004062 return;
4063 }
4064
4065 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004066 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004067 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004068 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004069 GetVideoTransceiver()->internal()->AddSender(new_sender);
4070 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004071 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004072 if (sender_info) {
4073 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004074 }
4075}
4076
4077void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4078 MediaStreamInterface* stream) {
4079 RTC_DCHECK(!IsClosed());
4080 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004081 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004082 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4083 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004084 return;
4085 }
Steve Anton4171afb2017-11-20 10:20:22 -08004086 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004087}
4088
Steve Antonba818672017-11-06 10:21:57 -08004089void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004090 if (ice_connection_state_ == new_state) {
4091 return;
4092 }
4093
deadbeefcbecd352015-09-23 11:50:27 -07004094 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004095 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004096 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004097 return;
4098 }
Steve Antonba818672017-11-06 10:21:57 -08004099
Mirko Bonadei675513b2017-11-09 11:09:25 +01004100 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4101 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004102 RTC_DCHECK(ice_connection_state_ !=
4103 PeerConnectionInterface::kIceConnectionClosed);
4104
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004105 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004106 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004107}
4108
Alex Loiko9289eda2018-11-23 16:18:59 +00004109void PeerConnection::SetStandardizedIceConnectionState(
4110 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004111 if (standardized_ice_connection_state_ == new_state)
4112 return;
4113 if (IsClosed())
4114 return;
4115 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004116 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004117}
4118
Jonas Olsson635474e2018-10-18 15:58:17 +02004119void PeerConnection::SetConnectionState(
4120 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004121 if (connection_state_ == new_state)
4122 return;
4123 if (IsClosed())
4124 return;
4125 connection_state_ = new_state;
4126 Observer()->OnConnectionChange(new_state);
4127}
4128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004129void PeerConnection::OnIceGatheringChange(
4130 PeerConnectionInterface::IceGatheringState new_state) {
4131 if (IsClosed()) {
4132 return;
4133 }
4134 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004135 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004136}
4137
jbauch81bf7b02017-03-25 08:31:12 -07004138void PeerConnection::OnIceCandidate(
4139 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004140 if (IsClosed()) {
4141 return;
4142 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004143 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004144 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4145 candidate->candidate().address().IsPrivateIP()) {
4146 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4147 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004148 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004149}
4150
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004151void PeerConnection::OnIceCandidatesRemoved(
4152 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004153 if (IsClosed()) {
4154 return;
4155 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004156 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004157}
4158
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004159void PeerConnection::ChangeSignalingState(
4160 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004161 if (signaling_state_ == signaling_state) {
4162 return;
4163 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004164 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4165 << GetSignalingStateString(signaling_state_)
4166 << " New state: "
4167 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004168 signaling_state_ = signaling_state;
4169 if (signaling_state == kClosed) {
4170 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004171 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004172 standardized_ice_connection_state_ =
4173 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004174 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4175 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004176 if (ice_gathering_state_ != kIceGatheringComplete) {
4177 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004178 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004179 }
4180 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004181 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004182}
4183
deadbeefeb459812015-12-15 19:24:43 -08004184void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4185 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004186 if (IsClosed()) {
4187 return;
4188 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004189 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004190 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004191}
4192
deadbeefeb459812015-12-15 19:24:43 -08004193void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4194 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004195 if (IsClosed()) {
4196 return;
4197 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004198 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004199 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004200}
4201
4202void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4203 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004204 if (IsClosed()) {
4205 return;
4206 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004207 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004208 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004209}
4210
4211void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4212 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004213 if (IsClosed()) {
4214 return;
4215 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004216 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004217 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004218}
4219
Henrik Boström31638672017-11-23 17:48:32 +01004220void PeerConnection::PostSetSessionDescriptionSuccess(
4221 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004222 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4223 signaling_thread()->Post(RTC_FROM_HERE, this,
4224 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004225}
4226
deadbeefab9b2d12015-10-14 11:33:11 -07004227void PeerConnection::PostSetSessionDescriptionFailure(
4228 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004229 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004230 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004231 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4232 msg->error = std::move(error);
4233 signaling_thread()->Post(RTC_FROM_HERE, this,
4234 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004235}
4236
4237void PeerConnection::PostCreateSessionDescriptionFailure(
4238 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004239 RTCError error) {
4240 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004241 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4242 msg->error = std::move(error);
4243 signaling_thread()->Post(RTC_FROM_HERE, this,
4244 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004245}
4246
zhihuang1c378ed2017-08-17 14:10:50 -07004247void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004248 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004249 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004250 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004251
Steve Antondcc3c022017-12-22 16:02:54 -08004252 if (IsUnifiedPlan()) {
4253 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4254 } else {
4255 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4256 }
4257
Steve Antonfa2260d2017-12-28 16:38:23 -08004258 // Intentionally unset the data channel type for RTP data channel with the
4259 // second condition. Otherwise the RTP data channels would be successfully
4260 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4261 // when building with chromium. We want to leave RTP data channels broken, so
4262 // people won't try to use them.
4263 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4264 session_options->data_channel_type = data_channel_type();
4265 }
4266
Steve Antondcc3c022017-12-22 16:02:54 -08004267 // Apply ICE restart flag and renomination flag.
4268 for (auto& options : session_options->media_description_options) {
4269 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4270 options.transport_options.enable_ice_renomination =
4271 configuration_.enable_ice_renomination;
4272 }
4273
4274 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004275 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004276 session_options->pooled_ice_credentials =
4277 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4278 RTC_FROM_HERE,
4279 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4280 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004281 session_options->offer_extmap_allow_mixed =
4282 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004283
4284 if (configuration_.enable_dtls_srtp &&
4285 !configuration_.enable_dtls_srtp.value()) {
4286 session_options->media_transport_settings =
4287 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4288 }
Steve Antondcc3c022017-12-22 16:02:54 -08004289}
4290
4291void PeerConnection::GetOptionsForPlanBOffer(
4292 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4293 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004294 // Figure out transceiver directional preferences.
4295 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4296 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4297
4298 // By default, generate sendrecv/recvonly m= sections.
4299 bool recv_audio = true;
4300 bool recv_video = true;
4301
4302 // By default, only offer a new m= section if we have media to send with it.
4303 bool offer_new_audio_description = send_audio;
4304 bool offer_new_video_description = send_video;
4305 bool offer_new_data_description = HasDataChannels();
4306
4307 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004308 if (offer_answer_options.offer_to_receive_audio !=
4309 RTCOfferAnswerOptions::kUndefined) {
4310 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004311 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004312 offer_new_audio_description ||
4313 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004314 }
Steve Antondcc3c022017-12-22 16:02:54 -08004315 if (offer_answer_options.offer_to_receive_video !=
4316 RTCOfferAnswerOptions::kUndefined) {
4317 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004318 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004319 offer_new_video_description ||
4320 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004321 }
4322
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004323 absl::optional<size_t> audio_index;
4324 absl::optional<size_t> video_index;
4325 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004326 // If a current description exists, generate m= sections in the same order,
4327 // using the first audio/video/data section that appears and rejecting
4328 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004329 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004330 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004331 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004332 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4333 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4334 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004335 }
4336
zhihuang1c378ed2017-08-17 14:10:50 -07004337 // Add audio/video/data m= sections to the end if needed.
4338 if (!audio_index && offer_new_audio_description) {
4339 session_options->media_description_options.push_back(
4340 cricket::MediaDescriptionOptions(
4341 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004342 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4343 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004344 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004345 }
zhihuang1c378ed2017-08-17 14:10:50 -07004346 if (!video_index && offer_new_video_description) {
4347 session_options->media_description_options.push_back(
4348 cricket::MediaDescriptionOptions(
4349 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004350 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4351 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004352 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004353 }
zhihuang1c378ed2017-08-17 14:10:50 -07004354 if (!data_index && offer_new_data_description) {
4355 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004356 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004357 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004358 }
4359
4360 cricket::MediaDescriptionOptions* audio_media_description_options =
4361 !audio_index ? nullptr
4362 : &session_options->media_description_options[*audio_index];
4363 cricket::MediaDescriptionOptions* video_media_description_options =
4364 !video_index ? nullptr
4365 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004366
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004367 AddPlanBRtpSenderOptions(GetSendersInternal(),
4368 audio_media_description_options,
4369 video_media_description_options,
4370 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004371}
4372
Steve Antondcc3c022017-12-22 16:02:54 -08004373static cricket::MediaDescriptionOptions
4374GetMediaDescriptionOptionsForTransceiver(
4375 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4376 transceiver,
4377 const std::string& mid) {
4378 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004379 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004380 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004381 // This behavior is specified in JSEP. The gist is that:
4382 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4383 // sendrecv.
4384 // 2. If the MSID is included, then it must be included in any subsequent
4385 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004386 if (transceiver->stopped() ||
4387 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4388 !transceiver->internal()->has_ever_been_used_to_send())) {
4389 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004390 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004391
4392 cricket::SenderOptions sender_options;
4393 sender_options.track_id = transceiver->sender()->id();
4394 sender_options.stream_ids = transceiver->sender()->stream_ids();
4395
4396 // The following sets up RIDs and Simulcast.
4397 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004398 RtpParameters send_parameters =
4399 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004400 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4401 send_parameters.encodings.end(),
4402 [](const RtpEncodingParameters& encoding) {
4403 return !encoding.rid.empty();
4404 });
4405
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004406 std::vector<RidDescription> send_rids;
4407 SimulcastLayerList send_layers;
4408 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4409 if (encoding.rid.empty()) {
4410 continue;
4411 }
4412 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4413 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4414 }
4415
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004416 if (has_rids) {
4417 sender_options.rids = send_rids;
4418 }
4419
4420 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004421 // When RIDs are configured, we must set num_sim_layers to 0 to.
4422 // Otherwise, num_sim_layers must be 1 because either there is no
4423 // simulcast, or simulcast is acheived by munging the SDP.
4424 sender_options.num_sim_layers = has_rids ? 0 : 1;
4425 media_description_options.sender_options.push_back(sender_options);
4426
Steve Antondcc3c022017-12-22 16:02:54 -08004427 return media_description_options;
4428}
4429
Steve Anton5c72e712018-12-10 14:25:30 -08004430// Returns the ContentInfo at mline index |i|, or null if none exists.
4431static const ContentInfo* GetContentByIndex(
4432 const SessionDescriptionInterface* sdesc,
4433 size_t i) {
4434 if (!sdesc) {
4435 return nullptr;
4436 }
4437 const ContentInfos& contents = sdesc->description()->contents();
4438 return (i < contents.size() ? &contents[i] : nullptr);
4439}
4440
Steve Antondcc3c022017-12-22 16:02:54 -08004441void PeerConnection::GetOptionsForUnifiedPlanOffer(
4442 const RTCOfferAnswerOptions& offer_answer_options,
4443 cricket::MediaSessionOptions* session_options) {
4444 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4445 // Offers) and 5.2.2 (Subsequent Offers).
4446 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4447 const ContentInfos& local_contents =
4448 (local_description() ? local_description()->description()->contents()
4449 : ContentInfos());
4450 const ContentInfos& remote_contents =
4451 (remote_description() ? remote_description()->description()->contents()
4452 : ContentInfos());
4453 // The mline indices that can be recycled. New transceivers should reuse these
4454 // slots first.
4455 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004456 // First, go through each media section that exists in either the local or
4457 // remote description and generate a media section in this offer for the
4458 // associated transceiver. If a media section can be recycled, generate a
4459 // default, rejected media section here that can be later overwritten.
4460 for (size_t i = 0;
4461 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4462 // Either |local_content| or |remote_content| is non-null.
4463 const ContentInfo* local_content =
4464 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004465 const ContentInfo* current_local_content =
4466 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004467 const ContentInfo* remote_content =
4468 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004469 const ContentInfo* current_remote_content =
4470 GetContentByIndex(current_remote_description(), i);
4471 bool had_been_rejected =
4472 (current_local_content && current_local_content->rejected) ||
4473 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004474 const std::string& mid =
4475 (local_content ? local_content->name : remote_content->name);
4476 cricket::MediaType media_type =
4477 (local_content ? local_content->media_description()->type()
4478 : remote_content->media_description()->type());
4479 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4480 media_type == cricket::MEDIA_TYPE_VIDEO) {
4481 auto transceiver = GetAssociatedTransceiver(mid);
4482 RTC_CHECK(transceiver);
4483 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004484 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004485 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004486 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004487 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4488 RtpTransceiverDirection::kInactive,
4489 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004490 recycleable_mline_indices.push(i);
4491 } else {
4492 session_options->media_description_options.push_back(
4493 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4494 // CreateOffer shouldn't really cause any state changes in
4495 // PeerConnection, but we need a way to match new transceivers to new
4496 // media sections in SetLocalDescription and JSEP specifies this is done
4497 // by recording the index of the media section generated for the
4498 // transceiver in the offer.
4499 transceiver->internal()->set_mline_index(i);
4500 }
4501 } else {
4502 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004503 RTC_CHECK(GetDataMid());
4504 if (had_been_rejected || mid != *GetDataMid()) {
4505 session_options->media_description_options.push_back(
4506 GetMediaDescriptionOptionsForRejectedData(mid));
4507 } else {
4508 session_options->media_description_options.push_back(
4509 GetMediaDescriptionOptionsForActiveData(mid));
4510 }
Steve Antondcc3c022017-12-22 16:02:54 -08004511 }
4512 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004513
Steve Antondcc3c022017-12-22 16:02:54 -08004514 // Next, look for transceivers that are newly added (that is, are not stopped
4515 // and not associated). Reuse media sections marked as recyclable first,
4516 // otherwise append to the end of the offer. New media sections should be
4517 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004518 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004519 if (transceiver->mid() || transceiver->stopped()) {
4520 continue;
4521 }
4522 size_t mline_index;
4523 if (!recycleable_mline_indices.empty()) {
4524 mline_index = recycleable_mline_indices.front();
4525 recycleable_mline_indices.pop();
4526 session_options->media_description_options[mline_index] =
4527 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004528 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004529 } else {
4530 mline_index = session_options->media_description_options.size();
4531 session_options->media_description_options.push_back(
4532 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004533 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004534 }
4535 // See comment above for why CreateOffer changes the transceiver's state.
4536 transceiver->internal()->set_mline_index(mline_index);
4537 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004538 // Lastly, add a m-section if we have local data channels and an m section
4539 // does not already exist.
4540 if (!GetDataMid() && HasDataChannels()) {
4541 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004542 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004543 }
Steve Antondcc3c022017-12-22 16:02:54 -08004544}
4545
4546void PeerConnection::GetOptionsForAnswer(
4547 const RTCOfferAnswerOptions& offer_answer_options,
4548 cricket::MediaSessionOptions* session_options) {
4549 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4550
4551 if (IsUnifiedPlan()) {
4552 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4553 } else {
4554 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4555 }
4556
Steve Antonfa2260d2017-12-28 16:38:23 -08004557 // Intentionally unset the data channel type for RTP data channel. Otherwise
4558 // the RTP data channels would be successfully negotiated by default and the
4559 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4560 // We want to leave RTP data channels broken, so people won't try to use them.
4561 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4562 session_options->data_channel_type = data_channel_type();
4563 }
4564
Steve Antondcc3c022017-12-22 16:02:54 -08004565 // Apply ICE renomination flag.
4566 for (auto& options : session_options->media_description_options) {
4567 options.transport_options.enable_ice_renomination =
4568 configuration_.enable_ice_renomination;
4569 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004570
4571 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004572 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004573 session_options->pooled_ice_credentials =
4574 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4575 RTC_FROM_HERE,
4576 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4577 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004578}
4579
Steve Antondcc3c022017-12-22 16:02:54 -08004580void PeerConnection::GetOptionsForPlanBAnswer(
4581 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004582 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004583 // Figure out transceiver directional preferences.
4584 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4585 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4586
4587 // By default, generate sendrecv/recvonly m= sections. The direction is also
4588 // restricted by the direction in the offer.
4589 bool recv_audio = true;
4590 bool recv_video = true;
4591
4592 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004593 if (offer_answer_options.offer_to_receive_audio !=
4594 RTCOfferAnswerOptions::kUndefined) {
4595 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004596 }
Steve Antondcc3c022017-12-22 16:02:54 -08004597 if (offer_answer_options.offer_to_receive_video !=
4598 RTCOfferAnswerOptions::kUndefined) {
4599 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004600 }
4601
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004602 absl::optional<size_t> audio_index;
4603 absl::optional<size_t> video_index;
4604 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004605
4606 // Generate m= sections that match those in the offer.
4607 // Note that mediasession.cc will handle intersection our preferred
4608 // direction with the offered direction.
4609 GenerateMediaDescriptionOptions(
4610 remote_description(),
4611 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4612 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4613 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004614
4615 cricket::MediaDescriptionOptions* audio_media_description_options =
4616 !audio_index ? nullptr
4617 : &session_options->media_description_options[*audio_index];
4618 cricket::MediaDescriptionOptions* video_media_description_options =
4619 !video_index ? nullptr
4620 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004621
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004622 AddPlanBRtpSenderOptions(GetSendersInternal(),
4623 audio_media_description_options,
4624 video_media_description_options,
4625 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004626}
zhihuangaf388472016-11-02 16:49:48 -07004627
Steve Antondcc3c022017-12-22 16:02:54 -08004628void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4629 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4630 cricket::MediaSessionOptions* session_options) {
4631 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4632 // Answers) and 5.3.2 (Subsequent Answers).
4633 RTC_DCHECK(remote_description());
4634 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4635 for (const ContentInfo& content :
4636 remote_description()->description()->contents()) {
4637 cricket::MediaType media_type = content.media_description()->type();
4638 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4639 media_type == cricket::MEDIA_TYPE_VIDEO) {
4640 auto transceiver = GetAssociatedTransceiver(content.name);
4641 RTC_CHECK(transceiver);
4642 session_options->media_description_options.push_back(
4643 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4644 } else {
4645 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004646 // Reject all data sections if data channels are disabled.
4647 // Reject a data section if it has already been rejected.
4648 // Reject all data sections except for the first one.
4649 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4650 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004651 session_options->media_description_options.push_back(
4652 GetMediaDescriptionOptionsForRejectedData(content.name));
4653 } else {
4654 session_options->media_description_options.push_back(
4655 GetMediaDescriptionOptionsForActiveData(content.name));
4656 }
Steve Antondcc3c022017-12-22 16:02:54 -08004657 }
4658 }
htaa2a49d92016-03-04 02:51:39 -08004659}
4660
zhihuang1c378ed2017-08-17 14:10:50 -07004661void PeerConnection::GenerateMediaDescriptionOptions(
4662 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004663 RtpTransceiverDirection audio_direction,
4664 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004665 absl::optional<size_t>* audio_index,
4666 absl::optional<size_t>* video_index,
4667 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004668 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004669 for (const cricket::ContentInfo& content :
4670 session_desc->description()->contents()) {
4671 if (IsAudioContent(&content)) {
4672 // If we already have an audio m= section, reject this extra one.
4673 if (*audio_index) {
4674 session_options->media_description_options.push_back(
4675 cricket::MediaDescriptionOptions(
4676 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004677 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004678 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004679 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004680 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004681 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4682 content.name, audio_direction,
4683 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004684 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004685 }
4686 } else if (IsVideoContent(&content)) {
4687 // If we already have an video m= section, reject this extra one.
4688 if (*video_index) {
4689 session_options->media_description_options.push_back(
4690 cricket::MediaDescriptionOptions(
4691 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004692 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004693 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004694 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004695 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004696 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4697 content.name, video_direction,
4698 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004699 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004700 }
4701 } else {
4702 RTC_DCHECK(IsDataContent(&content));
4703 // If we already have an data m= section, reject this extra one.
4704 if (*data_index) {
4705 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004706 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004707 } else {
4708 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004709 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004710 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004711 }
4712 }
htaa2a49d92016-03-04 02:51:39 -08004713 }
deadbeefab9b2d12015-10-14 11:33:11 -07004714}
4715
Steve Antonfa2260d2017-12-28 16:38:23 -08004716cricket::MediaDescriptionOptions
4717PeerConnection::GetMediaDescriptionOptionsForActiveData(
4718 const std::string& mid) const {
4719 // Direction for data sections is meaningless, but legacy endpoints might
4720 // expect sendrecv.
4721 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4722 RtpTransceiverDirection::kSendRecv,
4723 /*stopped=*/false);
4724 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4725 return options;
4726}
4727
4728cricket::MediaDescriptionOptions
4729PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4730 const std::string& mid) const {
4731 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4732 RtpTransceiverDirection::kInactive,
4733 /*stopped=*/true);
4734 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4735 return options;
4736}
4737
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004738absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004739 switch (data_channel_type_) {
4740 case cricket::DCT_RTP:
4741 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004742 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004743 }
4744 return rtp_data_channel_->content_name();
4745 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004746 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004747 case cricket::DCT_MEDIA_TRANSPORT:
4748 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004749 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004750 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004751 }
4752}
4753
Steve Anton4171afb2017-11-20 10:20:22 -08004754void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4755 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4756 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004757 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004758}
4759
Steve Anton4171afb2017-11-20 10:20:22 -08004760void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004761 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004762 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004763 cricket::MediaType media_type,
4764 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004765 RTC_DCHECK(!IsUnifiedPlan());
4766
Steve Anton4171afb2017-11-20 10:20:22 -08004767 std::vector<RtpSenderInfo>* current_senders =
4768 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004769
Steve Anton4171afb2017-11-20 10:20:22 -08004770 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004771 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004772 for (auto sender_it = current_senders->begin();
4773 sender_it != current_senders->end();
4774 /* incremented manually */) {
4775 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004776 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004777 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004778 std::string params_stream_id;
4779 if (params) {
4780 params_stream_id =
4781 (!params->first_stream_id().empty() ? params->first_stream_id()
4782 : kDefaultStreamId);
4783 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004784 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004785 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004786 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004787 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004788 sender_exists) {
4789 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004790 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004791 OnRemoteSenderRemoved(info, media_type);
4792 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004793 }
4794 }
4795
Steve Anton4171afb2017-11-20 10:20:22 -08004796 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004797 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004798 if (!params.has_ssrcs()) {
4799 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4800 // sender, this means it is coming from a Unified Plan endpoint,so we just
4801 // create a default.
4802 default_sender_needed = true;
4803 break;
4804 }
4805
Seth Hampson845e8782018-03-02 11:34:10 -08004806 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004807 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004808 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4809 // not supported in Plan B, we just take the first here and create the
4810 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004811 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004812 (!params.first_stream_id().empty() ? params.first_stream_id()
4813 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004814 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004815 uint32_t ssrc = params.first_ssrc();
4816
4817 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004818 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004819 if (!stream) {
4820 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004821 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004822 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004823 remote_streams_->AddStream(stream);
4824 new_streams->AddStream(stream);
4825 }
4826
Steve Anton4171afb2017-11-20 10:20:22 -08004827 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004828 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004829 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004830 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004831 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004832 }
4833 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004834
Steve Anton4171afb2017-11-20 10:20:22 -08004835 // Add default sender if necessary.
4836 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004837 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004838 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004839 if (!default_stream) {
4840 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004841 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004842 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004843 remote_streams_->AddStream(default_stream);
4844 new_streams->AddStream(default_stream);
4845 }
Steve Anton4171afb2017-11-20 10:20:22 -08004846 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4847 ? kDefaultAudioSenderId
4848 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004849 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004850 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004851 if (!default_sender_info) {
4852 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004853 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004854 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004855 }
4856 }
deadbeefab9b2d12015-10-14 11:33:11 -07004857}
4858
Steve Anton4171afb2017-11-20 10:20:22 -08004859void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4860 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004861 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4862 << " receiver for track_id=" << sender_info.sender_id
4863 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004864
Steve Anton3d954a62018-04-02 11:27:23 -07004865 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004866 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004867 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004868 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004869 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004870 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004871 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004872 }
4873}
4874
Steve Anton4171afb2017-11-20 10:20:22 -08004875void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4876 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004877 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4878 << " receiver for track_id=" << sender_info.sender_id
4879 << " and stream_id=" << sender_info.stream_id;
4880
Seth Hampson845e8782018-03-02 11:34:10 -08004881 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004882
Henrik Boström933d8b02017-10-10 10:05:16 -07004883 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004884 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004885 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4886 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004887 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004888 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004889 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004890 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004891 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004892 }
4893 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004894 // Stopping or destroying a VideoRtpReceiver will end the
4895 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004896 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004897 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004898 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004899 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004900 // There's no guarantee the track is still available, e.g. the track may
4901 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004902 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004903 }
4904 } else {
nisseede5da42017-01-12 05:15:36 -08004905 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004906 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004907 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004908 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004909 }
deadbeefab9b2d12015-10-14 11:33:11 -07004910}
4911
4912void PeerConnection::UpdateEndedRemoteMediaStreams() {
4913 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4914 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4915 MediaStreamInterface* stream = remote_streams_->at(i);
4916 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4917 streams_to_remove.push_back(stream);
4918 }
4919 }
4920
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004921 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004922 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004923 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004924 }
4925}
4926
Steve Anton4171afb2017-11-20 10:20:22 -08004927void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004928 const std::vector<cricket::StreamParams>& streams,
4929 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004930 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004931
Seth Hampson845e8782018-03-02 11:34:10 -08004932 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004933 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004934 for (auto sender_it = current_senders->begin();
4935 sender_it != current_senders->end();
4936 /* incremented manually */) {
4937 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004938 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004939 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4940 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004941 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004942 OnLocalSenderRemoved(info, media_type);
4943 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004944 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004945 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004946 }
4947 }
4948
Steve Anton4171afb2017-11-20 10:20:22 -08004949 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004950 for (const cricket::StreamParams& params : streams) {
4951 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004952 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004953 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004954 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004955 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004956 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004957 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004958 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004959 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004960 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004961 }
4962 }
4963}
4964
Steve Anton4171afb2017-11-20 10:20:22 -08004965void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4966 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004967 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004968 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004969 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004970 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4971 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004972 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004973 return;
4974 }
4975
deadbeeffac06552015-11-25 11:26:01 -08004976 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004977 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004978 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004979 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004980 }
deadbeeffac06552015-11-25 11:26:01 -08004981
Seth Hampson5b4f0752018-04-02 16:31:36 -07004982 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004983 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004984}
4985
Steve Anton4171afb2017-11-20 10:20:22 -08004986void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4987 cricket::MediaType media_type) {
4988 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004989 if (!sender) {
4990 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004991 // SessionDescriptions has been renegotiated.
4992 return;
4993 }
deadbeeffac06552015-11-25 11:26:01 -08004994
4995 // A sender has been removed from the SessionDescription but it's still
4996 // associated with the PeerConnection. This only occurs if the SDP doesn't
4997 // match with the calls to CreateSender, AddStream and RemoveStream.
4998 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004999 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005000 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005001 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005002 }
deadbeeffac06552015-11-25 11:26:01 -08005003
Steve Anton4171afb2017-11-20 10:20:22 -08005004 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005005}
5006
5007void PeerConnection::UpdateLocalRtpDataChannels(
5008 const cricket::StreamParamsVec& streams) {
5009 std::vector<std::string> existing_channels;
5010
5011 // Find new and active data channels.
5012 for (const cricket::StreamParams& params : streams) {
5013 // |it->sync_label| is actually the data channel label. The reason is that
5014 // we use the same naming of data channels as we do for
5015 // MediaStreams and Tracks.
5016 // For MediaStreams, the sync_label is the MediaStream label and the
5017 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005018 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005019 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005020 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005021 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005022 continue;
5023 }
5024 // Set the SSRC the data channel should use for sending.
5025 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5026 existing_channels.push_back(data_channel_it->first);
5027 }
5028
5029 UpdateClosingRtpDataChannels(existing_channels, true);
5030}
5031
5032void PeerConnection::UpdateRemoteRtpDataChannels(
5033 const cricket::StreamParamsVec& streams) {
5034 std::vector<std::string> existing_channels;
5035
5036 // Find new and active data channels.
5037 for (const cricket::StreamParams& params : streams) {
5038 // The data channel label is either the mslabel or the SSRC if the mslabel
5039 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005040 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005041 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005042 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005043 auto data_channel_it = rtp_data_channels_.find(label);
5044 if (data_channel_it == rtp_data_channels_.end()) {
5045 // This is a new data channel.
5046 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5047 } else {
5048 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5049 }
5050 existing_channels.push_back(label);
5051 }
5052
5053 UpdateClosingRtpDataChannels(existing_channels, false);
5054}
5055
5056void PeerConnection::UpdateClosingRtpDataChannels(
5057 const std::vector<std::string>& active_channels,
5058 bool is_local_update) {
5059 auto it = rtp_data_channels_.begin();
5060 while (it != rtp_data_channels_.end()) {
5061 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005062 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005063 ++it;
5064 continue;
5065 }
5066
5067 if (is_local_update) {
5068 data_channel->SetSendSsrc(0);
5069 } else {
5070 data_channel->RemotePeerRequestClose();
5071 }
5072
5073 if (data_channel->state() == DataChannel::kClosed) {
5074 rtp_data_channels_.erase(it);
5075 it = rtp_data_channels_.begin();
5076 } else {
5077 ++it;
5078 }
5079 }
5080}
5081
5082void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5083 uint32_t remote_ssrc) {
5084 rtc::scoped_refptr<DataChannel> channel(
5085 InternalCreateDataChannel(label, nullptr));
5086 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005087 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005088 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005089 return;
5090 }
5091 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005092 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5093 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005094 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005095}
5096
5097rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5098 const std::string& label,
5099 const InternalDataChannelInit* config) {
5100 if (IsClosed()) {
5101 return nullptr;
5102 }
Steve Anton75737c02017-11-06 10:37:17 -08005103 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005104 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005105 << "InternalCreateDataChannel: Data is not supported in this call.";
5106 return nullptr;
5107 }
5108 InternalDataChannelInit new_config =
5109 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005110 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005111 if (new_config.id < 0) {
5112 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005113 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005114 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005115 RTC_LOG(LS_ERROR)
5116 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005117 return nullptr;
5118 }
5119 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005120 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005121 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005122 return nullptr;
5123 }
5124 }
5125
Steve Anton75737c02017-11-06 10:37:17 -08005126 rtc::scoped_refptr<DataChannel> channel(
5127 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005128 if (!channel) {
5129 sid_allocator_.ReleaseSid(new_config.id);
5130 return nullptr;
5131 }
5132
5133 if (channel->data_channel_type() == cricket::DCT_RTP) {
5134 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005135 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5136 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005137 return nullptr;
5138 }
5139 rtp_data_channels_[channel->label()] = channel;
5140 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005141 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005142 sctp_data_channels_.push_back(channel);
5143 channel->SignalClosed.connect(this,
5144 &PeerConnection::OnSctpDataChannelClosed);
5145 }
5146
Steve Anton2d8609c2018-01-23 16:38:46 -08005147 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005148 return channel;
5149}
5150
5151bool PeerConnection::HasDataChannels() const {
5152 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5153}
5154
5155void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005156 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005157 for (const auto& channel : sctp_data_channels_) {
5158 if (channel->id() < 0) {
5159 int sid;
5160 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005161 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5162 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005163 continue;
5164 }
5165 channel->SetSctpSid(sid);
5166 }
5167 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005168 // Since closing modifies the list of channels, we have to do the actual
5169 // closing outside the loop.
5170 for (const auto& channel : channels_to_close) {
5171 channel->CloseAbruptly();
5172 }
deadbeefab9b2d12015-10-14 11:33:11 -07005173}
5174
5175void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005176 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005177 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5178 ++it) {
5179 if (it->get() == channel) {
5180 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005181 // After the closing procedure is done, it's safe to use this ID for
5182 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005183 sid_allocator_.ReleaseSid(channel->id());
5184 }
deadbeefbd292462015-12-14 18:15:29 -08005185 // Since this method is triggered by a signal from the DataChannel,
5186 // we can't free it directly here; we need to free it asynchronously.
5187 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005188 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005189 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5190 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005191 return;
5192 }
5193 }
5194}
5195
deadbeefab9b2d12015-10-14 11:33:11 -07005196void PeerConnection::OnDataChannelDestroyed() {
5197 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5198 // DataChannel may callback to us and try to modify the list.
5199 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5200 temp_rtp_dcs.swap(rtp_data_channels_);
5201 for (const auto& kv : temp_rtp_dcs) {
5202 kv.second->OnTransportChannelDestroyed();
5203 }
5204
5205 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5206 temp_sctp_dcs.swap(sctp_data_channels_);
5207 for (const auto& channel : temp_sctp_dcs) {
5208 channel->OnTransportChannelDestroyed();
5209 }
5210}
5211
5212void PeerConnection::OnDataChannelOpenMessage(
5213 const std::string& label,
5214 const InternalDataChannelInit& config) {
5215 rtc::scoped_refptr<DataChannel> channel(
5216 InternalCreateDataChannel(label, &config));
5217 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005218 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005219 return;
5220 }
5221
deadbeefa601f5c2016-06-06 14:27:39 -07005222 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5223 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005224 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005225 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005226}
5227
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005228bool PeerConnection::HandleOpenMessage_s(
5229 const cricket::ReceiveDataParams& params,
5230 const rtc::CopyOnWriteBuffer& buffer) {
5231 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5232 // Received OPEN message; parse and signal that a new data channel should
5233 // be created.
5234 std::string label;
5235 InternalDataChannelInit config;
5236 config.id = params.ssrc;
5237 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5238 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5239 << params.ssrc;
5240 return true;
5241 }
5242 config.open_handshake_role = InternalDataChannelInit::kAcker;
5243 OnDataChannelOpenMessage(label, config);
5244 return true;
5245 }
5246 return false;
5247}
5248
Steve Anton4171afb2017-11-20 10:20:22 -08005249rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5250PeerConnection::GetAudioTransceiver() const {
5251 // This method only works with Plan B SDP, where there is a single
5252 // audio/video transceiver.
5253 RTC_DCHECK(!IsUnifiedPlan());
5254 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005255 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005256 return transceiver;
5257 }
5258 }
5259 RTC_NOTREACHED();
5260 return nullptr;
5261}
5262
5263rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5264PeerConnection::GetVideoTransceiver() const {
5265 // This method only works with Plan B SDP, where there is a single
5266 // audio/video transceiver.
5267 RTC_DCHECK(!IsUnifiedPlan());
5268 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005269 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005270 return transceiver;
5271 }
5272 }
5273 RTC_NOTREACHED();
5274 return nullptr;
5275}
5276
5277// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5278// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005279bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005280 switch (type) {
5281 case cricket::MEDIA_TYPE_AUDIO:
5282 return !GetAudioTransceiver()->internal()->senders().empty();
5283 case cricket::MEDIA_TYPE_VIDEO:
5284 return !GetVideoTransceiver()->internal()->senders().empty();
5285 case cricket::MEDIA_TYPE_DATA:
5286 return false;
5287 }
5288 RTC_NOTREACHED();
5289 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005290}
5291
Steve Anton4171afb2017-11-20 10:20:22 -08005292rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5293PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005294 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005295 for (auto sender : transceiver->internal()->senders()) {
5296 if (sender->track() == track) {
5297 return sender;
5298 }
5299 }
5300 }
5301 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005302}
5303
Steve Anton4171afb2017-11-20 10:20:22 -08005304rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5305PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005306 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005307 for (auto sender : transceiver->internal()->senders()) {
5308 if (sender->id() == sender_id) {
5309 return sender;
5310 }
5311 }
5312 }
5313 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005314}
5315
Steve Anton4171afb2017-11-20 10:20:22 -08005316rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5317PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005318 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005319 for (auto receiver : transceiver->internal()->receivers()) {
5320 if (receiver->id() == receiver_id) {
5321 return receiver;
5322 }
5323 }
5324 }
5325 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005326}
5327
Steve Anton4171afb2017-11-20 10:20:22 -08005328std::vector<PeerConnection::RtpSenderInfo>*
5329PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5330 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5331 media_type == cricket::MEDIA_TYPE_VIDEO);
5332 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5333 ? &remote_audio_sender_infos_
5334 : &remote_video_sender_infos_;
5335}
5336
5337std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005338 cricket::MediaType media_type) {
5339 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5340 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005341 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5342 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005343}
5344
Steve Anton4171afb2017-11-20 10:20:22 -08005345const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5346 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005347 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005348 const std::string sender_id) const {
5349 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005350 if (sender_info.stream_id == stream_id &&
5351 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005352 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005353 }
5354 }
5355 return nullptr;
5356}
5357
5358DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5359 for (const auto& channel : sctp_data_channels_) {
5360 if (channel->id() == sid) {
5361 return channel;
5362 }
5363 }
5364 return nullptr;
5365}
5366
Karl Wibergfb3be392019-03-22 14:13:22 +01005367PeerConnection::InitializePortAllocatorResult
5368PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005369 const cricket::ServerAddresses& stun_servers,
5370 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005371 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005372 RTC_DCHECK_RUN_ON(network_thread());
5373
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005374 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005375 // To handle both internal and externally created port allocator, we will
5376 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005377 int port_allocator_flags = port_allocator_->flags();
5378 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5379 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5380 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005381 // If the disable-IPv6 flag was specified, we'll not override it
5382 // by experiment.
5383 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005384 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005385 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5386 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005387 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005388 }
5389
zhihuangb09b3f92017-03-07 14:40:51 -08005390 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005391 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005392 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005393 }
5394
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005395 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005396 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005397 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005398 }
5399
honghaiz60347052016-05-31 18:29:12 -07005400 if (configuration.candidate_network_policy ==
5401 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005402 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005403 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005404 }
5405
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005406 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005407 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005408 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5409 }
5410
Karl Wibergfb3be392019-03-22 14:13:22 +01005411 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005412 // No step delay is used while allocating ports.
5413 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5414 port_allocator_->set_candidate_filter(
5415 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005416 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005417
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005418 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005419 for (auto& turn_server : turn_servers_copy) {
5420 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005421 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005422 // Call this last since it may create pooled allocator sessions using the
5423 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005424 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005425 stun_servers, std::move(turn_servers_copy),
5426 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5427 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005428 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005429
5430 InitializePortAllocatorResult res;
5431 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5432 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005433}
5434
deadbeef91dd5672016-05-18 16:55:30 -07005435bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005436 const cricket::ServerAddresses& stun_servers,
5437 const std::vector<cricket::RelayServerConfig>& turn_servers,
5438 IceTransportsType type,
5439 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005440 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005441 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005442 absl::optional<int> stun_candidate_keepalive_interval,
5443 bool have_local_description) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005444 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005445 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005446 // According to JSEP, after setLocalDescription, changing the candidate pool
5447 // size is not allowed, and changing the set of ICE servers will not result
5448 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005449 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005450 port_allocator_->FreezeCandidatePool();
5451 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005452 // Add the custom tls turn servers if they exist.
5453 auto turn_servers_copy = turn_servers;
5454 for (auto& turn_server : turn_servers_copy) {
5455 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5456 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005457 // Call this last since it may create pooled allocator sessions using the
5458 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005459 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005460 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5461 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005462}
5463
Steve Antonba818672017-11-06 10:21:57 -08005464cricket::ChannelManager* PeerConnection::channel_manager() const {
5465 return factory_->channel_manager();
5466}
5467
Elad Alon99c3fe52017-10-13 16:29:40 +02005468bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005469 std::unique_ptr<RtcEventLogOutput> output,
5470 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005471 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005472 if (!event_log_) {
5473 return false;
5474 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005475 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005476}
5477
5478void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005479 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005480 if (event_log_) {
5481 event_log_->StopLogging();
5482 }
ivoc14d5dbe2016-07-04 07:06:55 -07005483}
nisseeaabdf62017-05-05 02:23:02 -07005484
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005485cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005486 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005487 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005488 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005489 if (channel && channel->content_name() == content_name) {
5490 return channel;
5491 }
Steve Anton75737c02017-11-06 10:37:17 -08005492 }
5493 if (rtp_data_channel() &&
5494 rtp_data_channel()->content_name() == content_name) {
5495 return rtp_data_channel();
5496 }
5497 return nullptr;
5498}
5499
5500bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005501 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005502 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005503 RTC_LOG(LS_INFO)
5504 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005505 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005506 return false;
5507 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005508 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005509 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005510 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005511 return false;
5512 }
5513
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005514 absl::optional<rtc::SSLRole> dtls_role;
5515 if (sctp_mid_) {
5516 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5517 } else if (is_caller_) {
5518 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5519 }
Zhi Huange830e682018-03-30 10:48:35 -07005520 if (dtls_role) {
5521 *role = *dtls_role;
5522 return true;
5523 }
5524 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005525}
5526
5527bool PeerConnection::GetSslRole(const std::string& content_name,
5528 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005529 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005530 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005531 RTC_LOG(LS_INFO)
5532 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005533 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005534 return false;
5535 }
5536
Zhi Huange830e682018-03-30 10:48:35 -07005537 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5538 if (dtls_role) {
5539 *role = *dtls_role;
5540 return true;
5541 }
5542 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005543}
5544
Steve Antonf8470812017-12-04 10:46:21 -08005545void PeerConnection::SetSessionError(SessionError error,
5546 const std::string& error_desc) {
5547 RTC_DCHECK_RUN_ON(signaling_thread());
5548 if (error != session_error_) {
5549 session_error_ = error;
5550 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005551 }
5552}
5553
Zhi Huange830e682018-03-30 10:48:35 -07005554RTCError PeerConnection::UpdateSessionState(
5555 SdpType type,
5556 cricket::ContentSource source,
5557 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005558 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005559
5560 // If there's already a pending error then no state transition should happen.
5561 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005562 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005563
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005564 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005565 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005566 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005567 }
5568
5569 // Update the signaling state according to the specified state machine (see
5570 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005571 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005572 ChangeSignalingState(source == cricket::CS_LOCAL
5573 ? PeerConnectionInterface::kHaveLocalOffer
5574 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005575 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005576 ChangeSignalingState(source == cricket::CS_LOCAL
5577 ? PeerConnectionInterface::kHaveLocalPrAnswer
5578 : PeerConnectionInterface::kHaveRemotePrAnswer);
5579 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005580 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005581 ChangeSignalingState(PeerConnectionInterface::kStable);
5582 }
5583
5584 // Update internal objects according to the session description's media
5585 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005586 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005587 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005588 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005589 }
5590
Steve Anton8a006912017-12-04 15:25:56 -08005591 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005592}
5593
Steve Anton8a006912017-12-04 15:25:56 -08005594RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005595 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005596 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005597 const SessionDescriptionInterface* sdesc =
5598 (source == cricket::CS_LOCAL ? local_description()
5599 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005600 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005601
5602 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005603 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005604 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005605 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005606 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005607 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005608 continue;
5609 }
5610 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005611 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005612 if (!content_desc) {
5613 continue;
5614 }
5615 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005616 bool success = (source == cricket::CS_LOCAL)
5617 ? channel->SetLocalContent(content_desc, type, &error)
5618 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005619 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005620 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005621 }
5622 }
5623
5624 // If using the RtpDataChannel, push down the new SDP section for it too.
5625 if (rtp_data_channel_) {
5626 const ContentInfo* data_content =
5627 cricket::GetFirstDataContent(sdesc->description());
5628 if (data_content && !data_content->rejected) {
5629 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005630 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005631 if (data_desc) {
5632 std::string error;
5633 bool success =
5634 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005635 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005636 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005637 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005638 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005639 }
Steve Anton75737c02017-11-06 10:37:17 -08005640 }
5641 }
5642 }
Steve Antoned10bd92017-12-05 10:52:59 -08005643
Steve Anton75737c02017-11-06 10:37:17 -08005644 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5645 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5646 if (sctp_transport_ && local_description() && remote_description() &&
5647 cricket::GetFirstDataContent(local_description()->description()) &&
5648 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005649 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005650 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 11:37:28 +02005651 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5652 GetSctpPort(local_description()->description()),
5653 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 15:25:56 -08005654 if (!success) {
5655 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5656 "Failed to push down SCTP parameters.");
5657 }
Steve Anton75737c02017-11-06 10:37:17 -08005658 }
Steve Antoned10bd92017-12-05 10:52:59 -08005659
Steve Anton8a006912017-12-04 15:25:56 -08005660 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005661}
5662
Karl Wiberg739506e2019-04-03 11:37:28 +02005663bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5664 int local_sctp_port,
5665 int remote_sctp_port) {
5666 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005667 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5668 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 11:37:28 +02005669 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 10:37:17 -08005670}
5671
Steve Anton8a006912017-12-04 15:25:56 -08005672RTCError PeerConnection::PushdownTransportDescription(
5673 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005674 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005675 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005676
Zhi Huange830e682018-03-30 10:48:35 -07005677 if (source == cricket::CS_LOCAL) {
5678 const SessionDescriptionInterface* sdesc = local_description();
5679 RTC_DCHECK(sdesc);
5680 return transport_controller_->SetLocalDescription(type,
5681 sdesc->description());
5682 } else {
5683 const SessionDescriptionInterface* sdesc = remote_description();
5684 RTC_DCHECK(sdesc);
5685 return transport_controller_->SetRemoteDescription(type,
5686 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005687 }
Steve Anton75737c02017-11-06 10:37:17 -08005688}
5689
5690bool PeerConnection::GetTransportDescription(
5691 const SessionDescription* description,
5692 const std::string& content_name,
5693 cricket::TransportDescription* tdesc) {
5694 if (!description || !tdesc) {
5695 return false;
5696 }
5697 const TransportInfo* transport_info =
5698 description->GetTransportInfoByName(content_name);
5699 if (!transport_info) {
5700 return false;
5701 }
5702 *tdesc = transport_info->description;
5703 return true;
5704}
5705
Steve Anton75737c02017-11-06 10:37:17 -08005706cricket::IceConfig PeerConnection::ParseIceConfig(
5707 const PeerConnectionInterface::RTCConfiguration& config) const {
5708 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005709 switch (config.continual_gathering_policy) {
5710 case PeerConnectionInterface::GATHER_ONCE:
5711 gathering_policy = cricket::GATHER_ONCE;
5712 break;
5713 case PeerConnectionInterface::GATHER_CONTINUALLY:
5714 gathering_policy = cricket::GATHER_CONTINUALLY;
5715 break;
5716 default:
5717 RTC_NOTREACHED();
5718 gathering_policy = cricket::GATHER_ONCE;
5719 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005720
Steve Anton75737c02017-11-06 10:37:17 -08005721 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005722 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5723 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005724 ice_config.prioritize_most_likely_candidate_pairs =
5725 config.prioritize_most_likely_ice_candidate_pairs;
5726 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005727 RTCConfigurationToIceConfigOptionalInt(
5728 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005729 ice_config.continual_gathering_policy = gathering_policy;
5730 ice_config.presume_writable_when_fully_relayed =
5731 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005732 ice_config.ice_check_interval_strong_connectivity =
5733 config.ice_check_interval_strong_connectivity;
5734 ice_config.ice_check_interval_weak_connectivity =
5735 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005736 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005737 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5738 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005739 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005740 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005741 ice_config.regather_all_networks_interval_range =
5742 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005743 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005744 return ice_config;
5745}
5746
Steve Anton75737c02017-11-06 10:37:17 -08005747bool PeerConnection::SendData(const cricket::SendDataParams& params,
5748 const rtc::CopyOnWriteBuffer& payload,
5749 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005750 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005751 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5752 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5753 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005754 return false;
5755 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005756 if (media_transport_) {
5757 SendDataParams send_params;
5758 send_params.type = ToWebrtcDataMessageType(params.type);
5759 send_params.ordered = params.ordered;
5760 if (params.max_rtx_count >= 0) {
5761 send_params.max_rtx_count = params.max_rtx_count;
5762 } else if (params.max_rtx_ms >= 0) {
5763 send_params.max_rtx_ms = params.max_rtx_ms;
5764 }
5765 return media_transport_->SendData(params.sid, send_params, payload).ok();
5766 }
Steve Anton75737c02017-11-06 10:37:17 -08005767 return rtp_data_channel_
5768 ? rtp_data_channel_->SendData(params, payload, result)
5769 : network_thread()->Invoke<bool>(
5770 RTC_FROM_HERE,
5771 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005772 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005773}
5774
5775bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005776 RTC_DCHECK_RUN_ON(signaling_thread());
5777 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005778 // Don't log an error here, because DataChannels are expected to call
5779 // ConnectDataChannel in this state. It's the only way to initially tell
5780 // whether or not the underlying transport is ready.
5781 return false;
5782 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005783 if (media_transport_) {
5784 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5785 &DataChannel::OnChannelReady);
5786 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5787 &DataChannel::OnDataReceived);
5788 SignalMediaTransportChannelClosing_s.connect(
5789 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5790 SignalMediaTransportChannelClosed_s.connect(
5791 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5792 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005793 rtp_data_channel_->SignalReadyToSendData.connect(
5794 webrtc_data_channel, &DataChannel::OnChannelReady);
5795 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5796 &DataChannel::OnDataReceived);
5797 } else {
5798 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5799 &DataChannel::OnChannelReady);
5800 SignalSctpDataReceived.connect(webrtc_data_channel,
5801 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005802 SignalSctpClosingProcedureStartedRemotely.connect(
5803 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5804 SignalSctpClosingProcedureComplete.connect(
5805 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005806 }
5807 return true;
5808}
5809
5810void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005811 RTC_DCHECK_RUN_ON(signaling_thread());
5812 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005813 RTC_LOG(LS_ERROR)
5814 << "DisconnectDataChannel called when rtp_data_channel_ and "
5815 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005816 return;
5817 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005818 if (media_transport_) {
5819 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5820 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5821 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5822 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5823 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005824 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5825 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5826 } else {
5827 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5828 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005829 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5830 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005831 }
5832}
5833
5834void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005835 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005836 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005837 return;
5838 }
Steve Anton75737c02017-11-06 10:37:17 -08005839 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005840 RTC_LOG(LS_ERROR)
5841 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005842 return;
5843 }
5844 network_thread()->Invoke<void>(
5845 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005846 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005847}
5848
5849void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005850 if (media_transport_) {
5851 media_transport_->CloseChannel(sid);
5852 return;
5853 }
Steve Anton75737c02017-11-06 10:37:17 -08005854 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005855 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005856 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005857 return;
5858 }
5859 network_thread()->Invoke<void>(
5860 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005861 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005862}
5863
5864bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005865 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005866 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005867 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005868 sctp_ready_to_send_data_;
5869}
5870
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005871void PeerConnection::OnDataReceived(int channel_id,
5872 DataMessageType type,
5873 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005874 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005875 cricket::ReceiveDataParams params;
5876 params.sid = channel_id;
5877 params.type = ToCricketDataMessageType(type);
5878 media_transport_invoker_->AsyncInvoke<void>(
5879 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5880 RTC_DCHECK_RUN_ON(signaling_thread());
5881 if (!HandleOpenMessage_s(params, buffer)) {
5882 SignalMediaTransportReceivedData_s(params, buffer);
5883 }
5884 });
5885}
5886
5887void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005888 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005889 media_transport_invoker_->AsyncInvoke<void>(
5890 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5891 RTC_DCHECK_RUN_ON(signaling_thread());
5892 SignalMediaTransportChannelClosing_s(channel_id);
5893 });
5894}
5895
5896void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005897 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005898 media_transport_invoker_->AsyncInvoke<void>(
5899 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5900 RTC_DCHECK_RUN_ON(signaling_thread());
5901 SignalMediaTransportChannelClosed_s(channel_id);
5902 });
5903}
5904
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005905absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005906 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005907 if (sctp_mid_ && transport_controller_) {
5908 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5909 if (dtls_transport) {
5910 return dtls_transport->transport_name();
5911 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005912 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005913 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005914 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005915}
5916
Qingsi Wang72a43a12018-02-20 16:03:18 -08005917cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5918 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005919 network_thread()->Invoke<void>(
5920 RTC_FROM_HERE,
5921 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5922 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005923 return candidate_states_list;
5924}
5925
Steve Anton5dfde182018-02-06 10:34:40 -08005926std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5927 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005928 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005929 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005930 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005931 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005932 if (channel) {
5933 transport_names_by_mid[channel->content_name()] =
5934 channel->transport_name();
5935 }
Steve Anton75737c02017-11-06 10:37:17 -08005936 }
Steve Anton5dfde182018-02-06 10:34:40 -08005937 if (rtp_data_channel_) {
5938 transport_names_by_mid[rtp_data_channel_->content_name()] =
5939 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005940 }
5941 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005942 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005943 RTC_DCHECK(transport_name);
5944 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005945 }
Steve Anton5dfde182018-02-06 10:34:40 -08005946 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005947}
5948
Steve Anton5dfde182018-02-06 10:34:40 -08005949std::map<std::string, cricket::TransportStats>
5950PeerConnection::GetTransportStatsByNames(
5951 const std::set<std::string>& transport_names) {
5952 if (!network_thread()->IsCurrent()) {
5953 return network_thread()
5954 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5955 RTC_FROM_HERE,
5956 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005957 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005958 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005959 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5960 for (const std::string& transport_name : transport_names) {
5961 cricket::TransportStats transport_stats;
5962 bool success =
5963 transport_controller_->GetStats(transport_name, &transport_stats);
5964 if (success) {
5965 transport_stats_by_name[transport_name] = std::move(transport_stats);
5966 } else {
5967 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5968 << transport_name;
5969 }
5970 }
5971 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005972}
5973
5974bool PeerConnection::GetLocalCertificate(
5975 const std::string& transport_name,
5976 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005977 if (!certificate) {
5978 return false;
5979 }
5980 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5981 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005982}
5983
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005984std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005985 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005986 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005987}
5988
5989cricket::DataChannelType PeerConnection::data_channel_type() const {
5990 return data_channel_type_;
5991}
5992
5993bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02005994 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005995 return pending_ice_restarts_.find(content_name) !=
5996 pending_ice_restarts_.end();
5997}
5998
Steve Anton75737c02017-11-06 10:37:17 -08005999bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6000 return transport_controller_->NeedsIceRestart(content_name);
6001}
6002
6003void PeerConnection::OnCertificateReady(
6004 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6005 transport_controller_->SetLocalCertificate(certificate);
6006}
6007
6008void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006009 SetSessionError(SessionError::kTransport,
6010 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006011}
6012
Alex Loiko9289eda2018-11-23 16:18:59 +00006013void PeerConnection::OnTransportControllerConnectionState(
6014 cricket::IceConnectionState state) {
6015 switch (state) {
6016 case cricket::kIceConnectionConnecting:
6017 // If the current state is Connected or Completed, then there were
6018 // writable channels but now there are not, so the next state must
6019 // be Disconnected.
6020 // kIceConnectionConnecting is currently used as the default,
6021 // un-connected state by the TransportController, so its only use is
6022 // detecting disconnections.
6023 if (ice_connection_state_ ==
6024 PeerConnectionInterface::kIceConnectionConnected ||
6025 ice_connection_state_ ==
6026 PeerConnectionInterface::kIceConnectionCompleted) {
6027 SetIceConnectionState(
6028 PeerConnectionInterface::kIceConnectionDisconnected);
6029 }
6030 break;
6031 case cricket::kIceConnectionFailed:
6032 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6033 break;
6034 case cricket::kIceConnectionConnected:
6035 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6036 "all transports are writable.";
6037 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6038 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6039 break;
6040 case cricket::kIceConnectionCompleted:
6041 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6042 "all transports are complete.";
6043 if (ice_connection_state_ !=
6044 PeerConnectionInterface::kIceConnectionConnected) {
6045 // If jumping directly from "checking" to "connected",
6046 // signal "connected" first.
6047 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6048 }
6049 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6050 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6051 ReportTransportStats();
6052 break;
6053 default:
6054 RTC_NOTREACHED();
6055 }
6056}
6057
Steve Anton75737c02017-11-06 10:37:17 -08006058void PeerConnection::OnTransportControllerCandidatesGathered(
6059 const std::string& transport_name,
6060 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006061 int sdp_mline_index;
6062 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006063 RTC_LOG(LS_ERROR)
6064 << "OnTransportControllerCandidatesGathered: content name "
6065 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006066 return;
6067 }
6068
6069 for (cricket::Candidates::const_iterator citer = candidates.begin();
6070 citer != candidates.end(); ++citer) {
6071 // Use transport_name as the candidate media id.
6072 std::unique_ptr<JsepIceCandidate> candidate(
6073 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6074 if (local_description()) {
6075 mutable_local_description()->AddCandidate(candidate.get());
6076 }
6077 OnIceCandidate(std::move(candidate));
6078 }
6079}
6080
6081void PeerConnection::OnTransportControllerCandidatesRemoved(
6082 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006083 // Sanity check.
6084 for (const cricket::Candidate& candidate : candidates) {
6085 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006086 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006087 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006088 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006089 return;
6090 }
6091 }
6092
6093 if (local_description()) {
6094 mutable_local_description()->RemoveCandidates(candidates);
6095 }
6096 OnIceCandidatesRemoved(candidates);
6097}
6098
6099void PeerConnection::OnTransportControllerDtlsHandshakeError(
6100 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006101 RTC_HISTOGRAM_ENUMERATION(
6102 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6103 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006104}
6105
Steve Antoned10bd92017-12-05 10:52:59 -08006106void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006107 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006108 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006109 if (channel && !channel->enabled()) {
6110 channel->Enable(true);
6111 }
Steve Anton75737c02017-11-06 10:37:17 -08006112 }
6113
Steve Anton4171afb2017-11-20 10:20:22 -08006114 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006115 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006116 }
Steve Anton75737c02017-11-06 10:37:17 -08006117}
6118
6119// Returns the media index for a local ice candidate given the content name.
6120bool PeerConnection::GetLocalCandidateMediaIndex(
6121 const std::string& content_name,
6122 int* sdp_mline_index) {
6123 if (!local_description() || !sdp_mline_index) {
6124 return false;
6125 }
6126
6127 bool content_found = false;
6128 const ContentInfos& contents = local_description()->description()->contents();
6129 for (size_t index = 0; index < contents.size(); ++index) {
6130 if (contents[index].name == content_name) {
6131 *sdp_mline_index = static_cast<int>(index);
6132 content_found = true;
6133 break;
6134 }
6135 }
6136 return content_found;
6137}
6138
6139bool PeerConnection::UseCandidatesInSessionDescription(
6140 const SessionDescriptionInterface* remote_desc) {
6141 if (!remote_desc) {
6142 return true;
6143 }
6144 bool ret = true;
6145
6146 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6147 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6148 for (size_t n = 0; n < candidates->count(); ++n) {
6149 const IceCandidateInterface* candidate = candidates->at(n);
6150 bool valid = false;
6151 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6152 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006153 RTC_LOG(LS_INFO)
6154 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006155 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006156 }
6157 continue;
6158 }
6159 ret = UseCandidate(candidate);
6160 if (!ret) {
6161 break;
6162 }
6163 }
6164 }
6165 return ret;
6166}
6167
6168bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6169 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6170 size_t remote_content_size =
6171 remote_description()->description()->contents().size();
6172 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006173 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006174 return false;
6175 }
6176
6177 cricket::ContentInfo content =
6178 remote_description()->description()->contents()[mediacontent_index];
6179 std::vector<cricket::Candidate> candidates;
6180 candidates.push_back(candidate->candidate());
6181 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006182 RTCError error =
6183 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006184 if (error.ok()) {
6185 // Candidates successfully submitted for checking.
6186 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6187 ice_connection_state_ ==
6188 PeerConnectionInterface::kIceConnectionDisconnected) {
6189 // If state is New, then the session has just gotten its first remote ICE
6190 // candidates, so go to Checking.
6191 // If state is Disconnected, the session is re-using old candidates or
6192 // receiving additional ones, so go to Checking.
6193 // If state is Connected, stay Connected.
6194 // TODO(bemasc): If state is Connected, and the new candidates are for a
6195 // newly added transport, then the state actually _should_ move to
6196 // checking. Add a way to distinguish that case.
6197 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6198 }
6199 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006200 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006201 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006202 }
6203 return true;
6204}
6205
6206void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006207 // Destroy video channel first since it may have a pointer to the
6208 // voice channel.
6209 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006210 if (!video_info || video_info->rejected) {
6211 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006212 }
6213
Steve Anton6fec8802017-12-04 10:37:29 -08006214 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6215 if (!audio_info || audio_info->rejected) {
6216 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006217 }
6218
6219 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6220 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006221 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006222 }
6223}
6224
Steve Antondcc3c022017-12-22 16:02:54 -08006225RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6226 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006227 const cricket::ContentGroup* bundle_group = nullptr;
6228 if (configuration_.bundle_policy ==
6229 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006230 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006231 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6233 "max-bundle configured but session description "
6234 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006235 }
6236 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006237 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006238}
6239
6240RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006241 // Creating the media channels. Transports should already have been created
6242 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006243 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006244 if (voice && !voice->rejected &&
6245 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006246 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006247 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006248 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6249 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006250 }
6251 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6252 }
6253
Steve Antondcc3c022017-12-22 16:02:54 -08006254 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006255 if (video && !video->rejected &&
6256 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006257 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006258 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006259 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6260 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006261 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006262 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006263 }
6264
Steve Antondcc3c022017-12-22 16:02:54 -08006265 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006266 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006267 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006268 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006269 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6270 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006271 }
6272 }
6273
Steve Anton8a006912017-12-04 15:25:56 -08006274 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006275}
6276
Steve Anton4171afb2017-11-20 10:20:22 -08006277// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006278cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006279 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006280 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006281 MediaTransportInterface* media_transport = nullptr;
6282 if (configuration_.use_media_transport) {
6283 media_transport = GetMediaTransport(mid);
6284 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006285
Steve Anton75737c02017-11-06 10:37:17 -08006286 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006287 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006288 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006289 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006290 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006291 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006292 }
Steve Anton75737c02017-11-06 10:37:17 -08006293 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6294 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006295 voice_channel->SignalSentPacket.connect(this,
6296 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006297 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006298
Steve Antoneda6ccd2017-12-04 10:21:55 -08006299 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006300}
6301
Steve Anton4171afb2017-11-20 10:20:22 -08006302// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006303cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006304 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006305 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006306 MediaTransportInterface* media_transport = nullptr;
6307 if (configuration_.use_media_transport) {
6308 media_transport = GetMediaTransport(mid);
6309 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006310
Steve Anton75737c02017-11-06 10:37:17 -08006311 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006312 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006313 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006314 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006315 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006316 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006317 }
Steve Anton75737c02017-11-06 10:37:17 -08006318 video_channel->SignalDtlsSrtpSetupFailure.connect(
6319 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006320 video_channel->SignalSentPacket.connect(this,
6321 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006322 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006323
Steve Antoneda6ccd2017-12-04 10:21:55 -08006324 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006325}
6326
Zhi Huange830e682018-03-30 10:48:35 -07006327bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006328 switch (data_channel_type_) {
6329 case cricket::DCT_MEDIA_TRANSPORT:
6330 if (network_thread()->Invoke<bool>(
6331 RTC_FROM_HERE,
6332 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6333 this, mid))) {
6334 for (const auto& channel : sctp_data_channels_) {
6335 channel->OnTransportChannelCreated();
6336 }
6337 return true;
6338 }
Steve Anton75737c02017-11-06 10:37:17 -08006339 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006340 case cricket::DCT_SCTP:
6341 if (!sctp_factory_) {
6342 RTC_LOG(LS_ERROR)
6343 << "Trying to create SCTP transport, but didn't compile with "
6344 "SCTP support (HAVE_SCTP)";
6345 return false;
6346 }
6347 if (!network_thread()->Invoke<bool>(
6348 RTC_FROM_HERE,
6349 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6350 return false;
6351 }
6352 for (const auto& channel : sctp_data_channels_) {
6353 channel->OnTransportChannelCreated();
6354 }
6355 return true;
6356 case cricket::DCT_RTP:
6357 default:
6358 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6359 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6360 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006361 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006362 if (!rtp_data_channel_) {
6363 return false;
6364 }
6365 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6366 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6367 rtp_data_channel_->SignalSentPacket.connect(
6368 this, &PeerConnection::OnSentPacket_w);
6369 rtp_data_channel_->SetRtpTransport(rtp_transport);
6370 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006371 }
6372
Steve Anton75737c02017-11-06 10:37:17 -08006373 return true;
6374}
6375
6376Call::Stats PeerConnection::GetCallStats() {
6377 if (!worker_thread()->IsCurrent()) {
6378 return worker_thread()->Invoke<Call::Stats>(
6379 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6380 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006381 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006382 if (call_) {
6383 return call_->GetStats();
6384 } else {
6385 return Call::Stats();
6386 }
6387}
6388
Zhi Huange830e682018-03-30 10:48:35 -07006389bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006390 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006391 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006392 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6393 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006394 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006395 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006396 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006397 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6398 sctp_factory_->CreateSctpTransport(dtls_transport);
6399 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006400 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006401 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006402 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006403 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006404 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006405 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6406 // another thread. Would be nice if there was a helper class similar to
6407 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6408 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006409 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006410 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006411 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006412 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006413 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006414 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6415 std::move(cricket_sctp_transport));
6416 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006417 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006418}
6419
6420void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006421 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006422 sctp_transport_->Clear();
6423 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006424 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006425 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006426}
6427
6428void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006429 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006430 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006431 // Note: Cannot use rtc::Bind here because it will grab a reference to
6432 // PeerConnection and potentially cause PeerConnection to live longer than
6433 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6434 // be destroyed before PeerConnection is destroyed, and at that point all
6435 // pending tasks will be cleared.
6436 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6437 OnSctpTransportReadyToSendData_s(true);
6438 });
6439}
6440
6441void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006442 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006443 sctp_ready_to_send_data_ = ready;
6444 SignalSctpReadyToSendData(ready);
6445}
6446
6447void PeerConnection::OnSctpTransportDataReceived_n(
6448 const cricket::ReceiveDataParams& params,
6449 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006450 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006451 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006452 // Note: Cannot use rtc::Bind here because it will grab a reference to
6453 // PeerConnection and potentially cause PeerConnection to live longer than
6454 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6455 // be destroyed before PeerConnection is destroyed, and at that point all
6456 // pending tasks will be cleared.
6457 sctp_invoker_->AsyncInvoke<void>(
6458 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6459 OnSctpTransportDataReceived_s(params, payload);
6460 });
6461}
6462
6463void PeerConnection::OnSctpTransportDataReceived_s(
6464 const cricket::ReceiveDataParams& params,
6465 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006466 RTC_DCHECK_RUN_ON(signaling_thread());
6467 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006468 SignalSctpDataReceived(params, payload);
6469 }
6470}
6471
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006472void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006473 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006474 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006475 sctp_invoker_->AsyncInvoke<void>(
6476 RTC_FROM_HERE, signaling_thread(),
6477 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006478 &SignalSctpClosingProcedureStartedRemotely, sid));
6479}
6480
6481void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006482 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006483 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006484 sctp_invoker_->AsyncInvoke<void>(
6485 RTC_FROM_HERE, signaling_thread(),
6486 rtc::Bind(&sigslot::signal1<int>::operator(),
6487 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006488}
6489
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006490bool PeerConnection::SetupMediaTransportForDataChannels_n(
6491 const std::string& mid) {
6492 media_transport_ = transport_controller_->GetMediaTransport(mid);
6493 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006494 RTC_LOG(LS_ERROR)
6495 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006496 return false;
6497 }
6498
6499 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6500 media_transport_->SetDataSink(this);
6501 media_transport_data_mid_ = mid;
6502 transport_controller_->SignalMediaTransportStateChanged.connect(
6503 this, &PeerConnection::OnMediaTransportStateChanged_n);
6504 // Check the initial state right away, in case transport is already writable.
6505 OnMediaTransportStateChanged_n();
6506 return true;
6507}
6508
6509void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6510 if (!media_transport_) {
6511 return;
6512 }
6513 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6514 media_transport_data_mid_.reset();
6515 media_transport_->SetDataSink(nullptr);
6516 media_transport_invoker_ = nullptr;
6517 media_transport_ = nullptr;
6518}
6519
6520void PeerConnection::OnMediaTransportStateChanged_n() {
6521 if (!media_transport_data_mid_ ||
6522 transport_controller_->GetMediaTransportState(
6523 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6524 return;
6525 }
6526 media_transport_invoker_->AsyncInvoke<void>(
6527 RTC_FROM_HERE, signaling_thread(), [this] {
6528 RTC_DCHECK_RUN_ON(signaling_thread());
6529 media_transport_ready_to_send_data_ = true;
6530 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6531 });
6532}
6533
Steve Anton75737c02017-11-06 10:37:17 -08006534// Returns false if bundle is enabled and rtcp_mux is disabled.
6535bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6536 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6537 if (!bundle_enabled)
6538 return true;
6539
6540 const cricket::ContentGroup* bundle_group =
6541 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6542 RTC_DCHECK(bundle_group != NULL);
6543
6544 const cricket::ContentInfos& contents = desc->contents();
6545 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6546 citer != contents.end(); ++citer) {
6547 const cricket::ContentInfo* content = (&*citer);
6548 RTC_DCHECK(content != NULL);
6549 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006550 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006551 if (!HasRtcpMuxEnabled(content))
6552 return false;
6553 }
6554 }
6555 // RTCP-MUX is enabled in all the contents.
6556 return true;
6557}
6558
6559bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006560 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006561}
6562
Steve Anton06817cd2018-12-18 15:55:30 -08006563static RTCError ValidateMids(const cricket::SessionDescription& description) {
6564 std::set<std::string> mids;
6565 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006566 if (content.name.empty()) {
6567 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6568 "A media section is missing a MID attribute.");
6569 }
Steve Anton06817cd2018-12-18 15:55:30 -08006570 if (!mids.insert(content.name).second) {
6571 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6572 "Duplicate a=mid value '" + content.name + "'.");
6573 }
6574 }
6575 return RTCError::OK();
6576}
6577
Steve Anton8a006912017-12-04 15:25:56 -08006578RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006579 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006580 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006581 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006582 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006583 }
6584
6585 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006586 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006587 }
6588
Steve Anton3828c062017-12-06 10:34:51 -08006589 SdpType type = sdesc->GetType();
6590 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6591 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006592 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006593 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006594 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006595 }
6596
Steve Anton06817cd2018-12-18 15:55:30 -08006597 RTCError error = ValidateMids(*sdesc->description());
6598 if (!error.ok()) {
6599 return error;
6600 }
6601
Steve Anton75737c02017-11-06 10:37:17 -08006602 // Verify crypto settings.
6603 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006604 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6605 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006606 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006607 if (!crypto_error.ok()) {
6608 return crypto_error;
6609 }
Steve Anton75737c02017-11-06 10:37:17 -08006610 }
6611
6612 // Verify ice-ufrag and ice-pwd.
6613 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006614 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6615 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006616 }
6617
6618 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006619 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6620 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006621 }
6622
6623 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6624 // m-lines that do not rtcp-mux enabled.
6625
6626 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006627 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006628 // With an answer we want to compare the new answer session description with
6629 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006630 const cricket::SessionDescription* offer_desc =
6631 (source == cricket::CS_LOCAL) ? remote_description()->description()
6632 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006633 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6634 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6635 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006636 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6637 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006638 }
6639 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006640 // The re-offers should respect the order of m= sections in current
6641 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006642 // With a re-offer, either the current local or current remote descriptions
6643 // could be the most up to date, so we would like to check against both of
6644 // them if they exist. It could be the case that one of them has a 0 port
6645 // for a media section, but the other does not. This is important to check
6646 // against in the case that we are recycling an m= section.
6647 const cricket::SessionDescription* current_desc = nullptr;
6648 const cricket::SessionDescription* secondary_current_desc = nullptr;
6649 if (local_description()) {
6650 current_desc = local_description()->description();
6651 if (remote_description()) {
6652 secondary_current_desc = remote_description()->description();
6653 }
6654 } else if (remote_description()) {
6655 current_desc = remote_description()->description();
6656 }
Steve Anton75737c02017-11-06 10:37:17 -08006657 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006658 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6659 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006660 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6661 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006662 }
6663 }
6664
Steve Antonba42e992018-04-09 14:10:01 -07006665 if (IsUnifiedPlan()) {
6666 // Ensure that each audio and video media section has at most one
6667 // "StreamParams". This will return an error if receiving a session
6668 // description from a "Plan B" endpoint which adds multiple tracks of the
6669 // same type. With Unified Plan, there can only be at most one track per
6670 // media section.
6671 for (const ContentInfo& content : sdesc->description()->contents()) {
6672 const MediaContentDescription& desc = *content.description;
6673 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6674 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6675 desc.streams().size() > 1u) {
6676 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6677 "Media section has more than one track specified "
6678 "with a=ssrc lines which is not supported with "
6679 "Unified Plan.");
6680 }
6681 }
6682 }
6683
Steve Anton8a006912017-12-04 15:25:56 -08006684 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006685}
6686
Steve Anton3828c062017-12-06 10:34:51 -08006687bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006688 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006689 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006690 return (state == PeerConnectionInterface::kStable) ||
6691 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006692 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006693 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006694 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6695 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6696 }
6697}
6698
Steve Anton3828c062017-12-06 10:34:51 -08006699bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006700 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006701 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006702 return (state == PeerConnectionInterface::kStable) ||
6703 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006704 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006705 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006706 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6707 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6708 }
6709}
6710
Steve Antonf8470812017-12-04 10:46:21 -08006711const char* PeerConnection::SessionErrorToString(SessionError error) const {
6712 switch (error) {
6713 case SessionError::kNone:
6714 return "ERROR_NONE";
6715 case SessionError::kContent:
6716 return "ERROR_CONTENT";
6717 case SessionError::kTransport:
6718 return "ERROR_TRANSPORT";
6719 }
6720 RTC_NOTREACHED();
6721 return "";
6722}
6723
Steve Anton75737c02017-11-06 10:37:17 -08006724std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006725 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006726 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6727 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006728 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006729}
6730
Steve Anton8e20f172018-03-06 10:55:04 -08006731void PeerConnection::ReportSdpFormatReceived(
6732 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006733 int num_audio_mlines = 0;
6734 int num_video_mlines = 0;
6735 int num_audio_tracks = 0;
6736 int num_video_tracks = 0;
6737 for (const ContentInfo& content : remote_offer.description()->contents()) {
6738 cricket::MediaType media_type = content.media_description()->type();
6739 int num_tracks = std::max(
6740 1, static_cast<int>(content.media_description()->streams().size()));
6741 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6742 num_audio_mlines += 1;
6743 num_audio_tracks += num_tracks;
6744 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6745 num_video_mlines += 1;
6746 num_video_tracks += num_tracks;
6747 }
6748 }
6749 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6750 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6751 format = kSdpFormatReceivedComplexUnifiedPlan;
6752 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6753 format = kSdpFormatReceivedComplexPlanB;
6754 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6755 format = kSdpFormatReceivedSimple;
6756 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006757 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6758 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006759}
6760
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006761void PeerConnection::NoteUsageEvent(UsageEvent event) {
6762 RTC_DCHECK_RUN_ON(signaling_thread());
6763 usage_event_accumulator_ |= static_cast<int>(event);
6764}
6765
6766void PeerConnection::ReportUsagePattern() const {
6767 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006768 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6769 usage_event_accumulator_,
6770 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006771 const int bad_bits =
6772 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6773 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6774 const int good_bits =
6775 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6776 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6777 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6778 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6779 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006780 // If called after close(), we can't report, because observer may have
6781 // been deallocated, and therefore pointer is null. Write to log instead.
6782 if (observer_) {
6783 Observer()->OnInterestingUsage(usage_event_accumulator_);
6784 } else {
6785 RTC_LOG(LS_INFO) << "Interesting usage signature "
6786 << usage_event_accumulator_
6787 << " observed after observer shutdown";
6788 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006789 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006790}
6791
Steve Anton0ffaaa22018-02-23 10:31:30 -08006792void PeerConnection::ReportNegotiatedSdpSemantics(
6793 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006794 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006795 switch (answer.description()->msid_signaling()) {
6796 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006797 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006798 break;
6799 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006800 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006801 break;
6802 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006803 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006804 break;
6805 case cricket::kMsidSignalingMediaSection |
6806 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006807 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006808 break;
6809 default:
6810 RTC_NOTREACHED();
6811 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006812 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6813 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006814}
6815
Steve Anton75737c02017-11-06 10:37:17 -08006816// We need to check the local/remote description for the Transport instead of
6817// the session, because a new Transport added during renegotiation may have
6818// them unset while the session has them set from the previous negotiation.
6819// Not doing so may trigger the auto generation of transport description and
6820// mess up DTLS identity information, ICE credential, etc.
6821bool PeerConnection::ReadyToUseRemoteCandidate(
6822 const IceCandidateInterface* candidate,
6823 const SessionDescriptionInterface* remote_desc,
6824 bool* valid) {
6825 *valid = true;
6826
6827 const SessionDescriptionInterface* current_remote_desc =
6828 remote_desc ? remote_desc : remote_description();
6829
6830 if (!current_remote_desc) {
6831 return false;
6832 }
6833
6834 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6835 size_t remote_content_size =
6836 current_remote_desc->description()->contents().size();
6837 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006838 RTC_LOG(LS_ERROR)
6839 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6840 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006841
6842 *valid = false;
6843 return false;
6844 }
6845
6846 cricket::ContentInfo content =
6847 current_remote_desc->description()->contents()[mediacontent_index];
6848
6849 const std::string transport_name = GetTransportName(content.name);
6850 if (transport_name.empty()) {
6851 return false;
6852 }
Zhi Huange830e682018-03-30 10:48:35 -07006853 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006854}
6855
6856bool PeerConnection::SrtpRequired() const {
6857 return dtls_enabled_ ||
6858 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6859}
6860
6861void PeerConnection::OnTransportControllerGatheringState(
6862 cricket::IceGatheringState state) {
6863 RTC_DCHECK(signaling_thread()->IsCurrent());
6864 if (state == cricket::kIceGatheringGathering) {
6865 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6866 } else if (state == cricket::kIceGatheringComplete) {
6867 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6868 }
6869}
6870
6871void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006872 std::map<std::string, std::set<cricket::MediaType>>
6873 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006874 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006875 if (transceiver->internal()->channel()) {
6876 const std::string& transport_name =
6877 transceiver->internal()->channel()->transport_name();
6878 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006879 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006880 }
Steve Anton75737c02017-11-06 10:37:17 -08006881 }
6882 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006883 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6884 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006885 }
Zhi Huange830e682018-03-30 10:48:35 -07006886
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006887 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006888 if (transport_name) {
6889 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006890 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006891 }
Zhi Huange830e682018-03-30 10:48:35 -07006892
Steve Antonc7b964c2018-02-01 14:39:45 -08006893 for (const auto& entry : media_types_by_transport_name) {
6894 const std::string& transport_name = entry.first;
6895 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006896 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006897 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006898 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006899 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006900 }
6901 }
6902}
6903// Walk through the ConnectionInfos to gather best connection usage
6904// for IPv4 and IPv6.
6905void PeerConnection::ReportBestConnectionState(
6906 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006907 for (const cricket::TransportChannelStats& channel_stats :
6908 stats.channel_stats) {
6909 for (const cricket::ConnectionInfo& connection_info :
6910 channel_stats.connection_infos) {
6911 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006912 continue;
6913 }
6914
Steve Antonc7b964c2018-02-01 14:39:45 -08006915 const cricket::Candidate& local = connection_info.local_candidate;
6916 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006917
6918 // Increment the counter for IceCandidatePairType.
6919 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6920 (local.type() == RELAY_PORT_TYPE &&
6921 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006922 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6923 GetIceCandidatePairCounter(local, remote),
6924 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006925 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006926 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6927 GetIceCandidatePairCounter(local, remote),
6928 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006929 } else {
6930 RTC_CHECK(0);
6931 }
Steve Anton75737c02017-11-06 10:37:17 -08006932
6933 // Increment the counter for IP type.
6934 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006935 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6936 kBestConnections_IPv4,
6937 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006938 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006939 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6940 kBestConnections_IPv6,
6941 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006942 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006943 RTC_CHECK(!local.address().hostname().empty() &&
6944 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006945 }
6946
6947 return;
6948 }
6949 }
6950}
6951
6952void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006953 const cricket::TransportStats& stats,
6954 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006955 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6956 return;
6957 }
6958
6959 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6960 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6961 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6962 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6963 return;
6964 }
6965
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006966 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6967 for (cricket::MediaType media_type : media_types) {
6968 switch (media_type) {
6969 case cricket::MEDIA_TYPE_AUDIO:
6970 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6971 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6972 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6973 break;
6974 case cricket::MEDIA_TYPE_VIDEO:
6975 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6976 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6977 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6978 break;
6979 case cricket::MEDIA_TYPE_DATA:
6980 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6981 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6982 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6983 break;
6984 default:
6985 RTC_NOTREACHED();
6986 continue;
6987 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006988 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006989 }
6990
6991 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6992 for (cricket::MediaType media_type : media_types) {
6993 switch (media_type) {
6994 case cricket::MEDIA_TYPE_AUDIO:
6995 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6996 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6997 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6998 break;
6999 case cricket::MEDIA_TYPE_VIDEO:
7000 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7001 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7002 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7003 break;
7004 case cricket::MEDIA_TYPE_DATA:
7005 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7006 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7007 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7008 break;
7009 default:
7010 RTC_NOTREACHED();
7011 continue;
7012 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007013 }
Steve Anton75737c02017-11-06 10:37:17 -08007014 }
7015}
7016
7017void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007018 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007019 RTC_DCHECK(call_);
7020 call_->OnSentPacket(sent_packet);
7021}
7022
7023const std::string PeerConnection::GetTransportName(
7024 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007025 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007026 if (channel) {
7027 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007028 }
Steve Anton6fec8802017-12-04 10:37:29 -08007029 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007030 RTC_DCHECK(sctp_mid_);
7031 if (content_name == *sctp_mid_) {
7032 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007033 }
7034 }
7035 // Return an empty string if failed to retrieve the transport name.
7036 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007037}
7038
Steve Anton6fec8802017-12-04 10:37:29 -08007039void PeerConnection::DestroyTransceiverChannel(
7040 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7041 transceiver) {
7042 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007043
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007044 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007045 if (channel) {
7046 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007047 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007048 }
7049}
7050
7051void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007052 if (rtp_data_channel_) {
7053 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007054 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007055 rtp_data_channel_ = nullptr;
7056 }
7057
7058 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7059 // grab a reference to this PeerConnection. If this is called from the
7060 // PeerConnection destructor, the RefCountedObject vtable will have already
7061 // been destroyed (since it is a subclass of PeerConnection) and using
7062 // rtc::Bind will cause "Pure virtual function called" error to appear.
7063
7064 if (sctp_transport_) {
7065 OnDataChannelDestroyed();
7066 network_thread()->Invoke<void>(RTC_FROM_HERE,
7067 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007068 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007069 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007070
7071 if (media_transport_) {
7072 OnDataChannelDestroyed();
7073 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7074 RTC_DCHECK_RUN_ON(network_thread());
7075 TeardownMediaTransportForDataChannels_n();
7076 });
7077 }
Steve Anton6fec8802017-12-04 10:37:29 -08007078}
7079
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007080void PeerConnection::DestroyChannelInterface(
7081 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007082 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007083 switch (channel->media_type()) {
7084 case cricket::MEDIA_TYPE_AUDIO:
7085 channel_manager()->DestroyVoiceChannel(
7086 static_cast<cricket::VoiceChannel*>(channel));
7087 break;
7088 case cricket::MEDIA_TYPE_VIDEO:
7089 channel_manager()->DestroyVideoChannel(
7090 static_cast<cricket::VideoChannel*>(channel));
7091 break;
7092 case cricket::MEDIA_TYPE_DATA:
7093 channel_manager()->DestroyRtpDataChannel(
7094 static_cast<cricket::RtpDataChannel*>(channel));
7095 break;
7096 default:
7097 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7098 break;
7099 }
Zhi Huange830e682018-03-30 10:48:35 -07007100}
Steve Anton6fec8802017-12-04 10:37:29 -08007101
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007102bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007103 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007104 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007105 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007106 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007107 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007108 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007109 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007110 auto base_channel = GetChannel(mid);
7111 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007112 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007113 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007114 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007115 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007116 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007117
Karl Wiberg5966c502019-02-21 23:55:09 +01007118 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007119 // Only pass media transport to call object if media transport is used
7120 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007121 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007122 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007123
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007124 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007125}
7126
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007127PeerConnectionObserver* PeerConnection::Observer() const {
7128 // In earlier production code, the pointer was not cleared on close,
7129 // which might have led to undefined behavior if the observer was not
7130 // deallocated, or strange crashes if it was.
7131 // We use CHECK in order to catch such behavior if it exists.
7132 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7133 RTC_CHECK(observer_);
7134 return observer_;
7135}
7136
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007137CryptoOptions PeerConnection::GetCryptoOptions() {
7138 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7139 // after it has been removed.
7140 return configuration_.crypto_options.has_value()
7141 ? *configuration_.crypto_options
7142 : factory_->options().crypto_options;
7143}
7144
Harald Alvestrand89061872018-01-02 14:08:34 +01007145void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007146 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007147 if (stats_collector_) {
7148 stats_collector_->ClearCachedStatsReport();
7149 }
7150}
7151
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007152void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007153 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7154 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007155}
7156
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007157void PeerConnection::UpdateNegotiationNeeded() {
7158 RTC_DCHECK_RUN_ON(signaling_thread());
7159 if (!IsUnifiedPlan()) {
7160 Observer()->OnRenegotiationNeeded();
7161 return;
7162 }
7163
7164 // If connection's [[IsClosed]] slot is true, abort these steps.
7165 if (IsClosed())
7166 return;
7167
7168 // If connection's signaling state is not "stable", abort these steps.
7169 if (signaling_state() != kStable)
7170 return;
7171
7172 // NOTE
7173 // The negotiation-needed flag will be updated once the state transitions to
7174 // "stable", as part of the steps for setting an RTCSessionDescription.
7175
7176 // If the result of checking if negotiation is needed is false, clear the
7177 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7178 // to false, and abort these steps.
7179 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7180 if (!is_negotiation_needed) {
7181 is_negotiation_needed_ = false;
7182 return;
7183 }
7184
7185 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7186 // steps.
7187 if (is_negotiation_needed_)
7188 return;
7189
7190 // Set connection's [[NegotiationNeeded]] slot to true.
7191 is_negotiation_needed_ = true;
7192
7193 // Queue a task that runs the following steps:
7194 // If connection's [[IsClosed]] slot is true, abort these steps.
7195 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7196 // Fire an event named negotiationneeded at connection.
7197 Observer()->OnRenegotiationNeeded();
7198}
7199
7200bool PeerConnection::CheckIfNegotiationIsNeeded() {
7201 RTC_DCHECK_RUN_ON(signaling_thread());
7202 // 1. If any implementation-specific negotiation is required, as described at
7203 // the start of this section, return true.
7204
7205 // 2. Let description be connection.[[CurrentLocalDescription]].
7206 const SessionDescriptionInterface* description = current_local_description();
7207 if (!description)
7208 return true;
7209
7210 // 3. If connection has created any RTCDataChannels, and no m= section in
7211 // description has been negotiated yet for data, return true.
7212 if (!sctp_data_channels_.empty()) {
7213 if (!cricket::GetFirstDataContent(description->description()->contents()))
7214 return true;
7215 }
7216
7217 // 4. For each transceiver in connection's set of transceivers, perform the
7218 // following checks:
7219 for (const auto& transceiver : transceivers_) {
7220 const ContentInfo* current_local_msection =
7221 FindTransceiverMSection(transceiver.get(), description);
7222
7223 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7224 transceiver.get(), current_remote_description());
7225
7226 // 4.3 If transceiver is stopped and is associated with an m= section,
7227 // but the associated m= section is not yet rejected in
7228 // connection.[[CurrentLocalDescription]] or
7229 // connection.[[CurrentRemoteDescription]], return true.
7230 if (transceiver->stopped()) {
7231 if (current_local_msection && !current_local_msection->rejected &&
7232 ((current_remote_msection && !current_remote_msection->rejected) ||
7233 !current_remote_msection)) {
7234 return true;
7235 }
7236 continue;
7237 }
7238
7239 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7240 // section in description, return true.
7241 if (!current_local_msection)
7242 return true;
7243
7244 const MediaContentDescription* current_local_media_description =
7245 current_local_msection->media_description();
7246 // 4.2 If transceiver isn't stopped and is associated with an m= section
7247 // in description then perform the following checks:
7248
7249 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7250 // associated m= section in description either doesn't contain a single
7251 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7252 // m= section, or the MSID values themselves, differ from what is in
7253 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7254 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7255 if (current_local_media_description->streams().size() == 0)
7256 return true;
7257
7258 std::vector<std::string> msection_msids;
7259 for (const auto& stream : current_local_media_description->streams()) {
7260 for (const std::string& msid : stream.stream_ids())
7261 msection_msids.push_back(msid);
7262 }
7263
7264 std::vector<std::string> transceiver_msids =
7265 transceiver->sender()->stream_ids();
7266 if (msection_msids.size() != transceiver_msids.size())
7267 return true;
7268
7269 absl::c_sort(transceiver_msids);
7270 absl::c_sort(msection_msids);
7271 if (transceiver_msids != msection_msids)
7272 return true;
7273 }
7274
7275 // 4.2.2 If description is of type "offer", and the direction of the
7276 // associated m= section in neither connection.[[CurrentLocalDescription]]
7277 // nor connection.[[CurrentRemoteDescription]] matches
7278 // transceiver.[[Direction]], return true.
7279 if (description->GetType() == SdpType::kOffer) {
7280 if (!current_remote_description())
7281 return true;
7282
7283 if (!current_remote_msection)
7284 return true;
7285
7286 RtpTransceiverDirection current_local_direction =
7287 current_local_media_description->direction();
7288 RtpTransceiverDirection current_remote_direction =
7289 current_remote_msection->media_description()->direction();
7290 if (transceiver->direction() != current_local_direction &&
7291 transceiver->direction() !=
7292 RtpTransceiverDirectionReversed(current_remote_direction)) {
7293 return true;
7294 }
7295 }
7296
7297 // 4.2.3 If description is of type "answer", and the direction of the
7298 // associated m= section in the description does not match
7299 // transceiver.[[Direction]] intersected with the offered direction (as
7300 // described in [JSEP] (section 5.3.1.)), return true.
7301 if (description->GetType() == SdpType::kAnswer) {
7302 if (!remote_description())
7303 return true;
7304
7305 const ContentInfo* offered_remote_msection =
7306 FindTransceiverMSection(transceiver.get(), remote_description());
7307
7308 RtpTransceiverDirection offered_direction =
7309 offered_remote_msection
7310 ? offered_remote_msection->media_description()->direction()
7311 : RtpTransceiverDirection::kInactive;
7312
7313 if (current_local_media_description->direction() !=
7314 (RtpTransceiverDirectionIntersection(
7315 transceiver->direction(),
7316 RtpTransceiverDirectionReversed(offered_direction)))) {
7317 return true;
7318 }
7319 }
7320 }
7321
7322 // If all the preceding checks were performed and true was not returned,
7323 // nothing remains to be negotiated; return false.
7324 return false;
7325}
7326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007327} // namespace webrtc