blob: 21dfcd463d09ade4fa66b5ff4c061aa9510bce20 [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) {
Harald Alvestrand8a9193c2019-04-16 21:26:47 +0200561 const cricket::SctpDataContentDescription* data_desc =
562 GetFirstSctpDataContentDescription(session_description);
Steve Antonb1c1de12017-12-21 15:14:30 -0800563 RTC_DCHECK(data_desc);
564 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800565 return -1;
566 }
Harald Alvestrand8a9193c2019-04-16 21:26:47 +0200567 return data_desc->port();
Steve Anton75737c02017-11-06 10:37:17 -0800568}
569
Steve Anton75737c02017-11-06 10:37:17 -0800570// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
571bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
572 const SessionDescriptionInterface* new_desc,
573 const std::string& content_name) {
574 if (!old_desc) {
575 return false;
576 }
577 const SessionDescription* new_sd = new_desc->description();
578 const SessionDescription* old_sd = old_desc->description();
579 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
580 if (!cinfo || cinfo->rejected) {
581 return false;
582 }
583 // If the content isn't rejected, check if ufrag and password has changed.
584 const cricket::TransportDescription* new_transport_desc =
585 new_sd->GetTransportDescriptionByName(content_name);
586 const cricket::TransportDescription* old_transport_desc =
587 old_sd->GetTransportDescriptionByName(content_name);
588 if (!new_transport_desc || !old_transport_desc) {
589 // No transport description exists. This is not an ICE restart.
590 return false;
591 }
592 if (cricket::IceCredentialsChanged(
593 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
594 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100595 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
596 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800597 return true;
598 }
599 return false;
600}
601
Steve Anton80dd7b52018-02-16 17:08:42 -0800602// Generates a string error message for SetLocalDescription/SetRemoteDescription
603// from an RTCError.
604std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
605 SdpType type,
606 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200607 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800608 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
609 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200610 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800611}
612
Seth Hampson5b4f0752018-04-02 16:31:36 -0700613std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
614 std::string output = "streams=[";
615 const char* separator = "";
616 for (const auto& stream_id : stream_ids) {
617 output.append(separator).append(stream_id);
618 separator = ", ";
619 }
620 output.append("]");
621 return output;
622}
623
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200624absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700625 int rtc_configuration_parameter) {
626 if (rtc_configuration_parameter ==
627 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200628 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700629 }
630 return rtc_configuration_parameter;
631}
632
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800633cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
634 switch (type) {
635 case DataMessageType::kText:
636 return cricket::DMT_TEXT;
637 case DataMessageType::kBinary:
638 return cricket::DMT_BINARY;
639 case DataMessageType::kControl:
640 return cricket::DMT_CONTROL;
641 default:
642 return cricket::DMT_NONE;
643 }
644 return cricket::DMT_NONE;
645}
646
647DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
648 switch (type) {
649 case cricket::DMT_TEXT:
650 return DataMessageType::kText;
651 case cricket::DMT_BINARY:
652 return DataMessageType::kBinary;
653 case cricket::DMT_CONTROL:
654 return DataMessageType::kControl;
655 case cricket::DMT_NONE:
656 default:
657 RTC_NOTREACHED();
658 }
659 return DataMessageType::kControl;
660}
661
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800662void ReportSimulcastApiVersion(const char* name,
663 const SessionDescription& session) {
664 bool has_legacy = false;
665 bool has_spec_compliant = false;
666 for (const ContentInfo& content : session.contents()) {
667 if (!content.description) {
668 continue;
669 }
670 has_spec_compliant |= content.description->HasSimulcast();
671 for (const StreamParams& sp : content.description->streams()) {
672 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
673 }
674 }
675
676 if (has_legacy) {
677 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
678 kSimulcastApiVersionMax);
679 }
680 if (has_spec_compliant) {
681 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
682 kSimulcastApiVersionMax);
683 }
684 if (!has_legacy && !has_spec_compliant) {
685 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
686 kSimulcastApiVersionMax);
687 }
688}
689
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200690const ContentInfo* FindTransceiverMSection(
691 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
692 const SessionDescriptionInterface* session_description) {
693 return transceiver->mid()
694 ? session_description->description()->GetContentByName(
695 *transceiver->mid())
696 : nullptr;
697}
698
Steve Anton75737c02017-11-06 10:37:17 -0800699} // namespace
700
Henrik Boström31638672017-11-23 17:48:32 +0100701// Upon completion, posts a task to execute the callback of the
702// SetSessionDescriptionObserver asynchronously on the same thread. At this
703// point, the state of the peer connection might no longer reflect the effects
704// of the SetRemoteDescription operation, as the peer connection could have been
705// modified during the post.
706// TODO(hbos): Remove this class once we remove the version of
707// PeerConnectionInterface::SetRemoteDescription() that takes a
708// SetSessionDescriptionObserver as an argument.
709class PeerConnection::SetRemoteDescriptionObserverAdapter
710 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
711 public:
712 SetRemoteDescriptionObserverAdapter(
713 rtc::scoped_refptr<PeerConnection> pc,
714 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
715 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
716
717 // SetRemoteDescriptionObserverInterface implementation.
718 void OnSetRemoteDescriptionComplete(RTCError error) override {
719 if (error.ok())
720 pc_->PostSetSessionDescriptionSuccess(wrapper_);
721 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100722 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100723 }
724
725 private:
726 rtc::scoped_refptr<PeerConnection> pc_;
727 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
728};
729
deadbeef293e9262017-01-11 12:28:30 -0800730bool PeerConnectionInterface::RTCConfiguration::operator==(
731 const PeerConnectionInterface::RTCConfiguration& o) const {
732 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800734 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000735 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700736 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800737 BundlePolicy bundle_policy;
738 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700739 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
740 int ice_candidate_pool_size;
741 bool disable_ipv6;
742 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700743 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100744 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700745 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200746 absl::optional<int> screencast_min_bitrate;
747 absl::optional<bool> combined_audio_video_bwe;
748 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800749 TcpCandidatePolicy tcp_candidate_policy;
750 CandidateNetworkPolicy candidate_network_policy;
751 int audio_jitter_buffer_max_packets;
752 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100753 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100754 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800755 int ice_connection_receiving_timeout;
756 int ice_backup_candidate_pair_ping_interval;
757 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800758 bool prioritize_most_likely_ice_candidate_pairs;
759 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800760 bool prune_turn_ports;
761 bool presume_writable_when_fully_relayed;
762 bool enable_ice_renomination;
763 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200764 absl::optional<int> ice_check_interval_strong_connectivity;
765 absl::optional<int> ice_check_interval_weak_connectivity;
766 absl::optional<int> ice_check_min_interval;
767 absl::optional<int> ice_unwritable_timeout;
768 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800769 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200770 absl::optional<int> stun_candidate_keepalive_interval;
771 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200772 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800773 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200774 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700775 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700776 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700777 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700778 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100779 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800780 };
781 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
782 "Did you add something to RTCConfiguration and forget to "
783 "update operator==?");
784 return type == o.type && servers == o.servers &&
785 bundle_policy == o.bundle_policy &&
786 rtcp_mux_policy == o.rtcp_mux_policy &&
787 tcp_candidate_policy == o.tcp_candidate_policy &&
788 candidate_network_policy == o.candidate_network_policy &&
789 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
790 audio_jitter_buffer_fast_accelerate ==
791 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100792 audio_jitter_buffer_min_delay_ms ==
793 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100794 audio_jitter_buffer_enable_rtx_handling ==
795 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800796 ice_connection_receiving_timeout ==
797 o.ice_connection_receiving_timeout &&
798 ice_backup_candidate_pair_ping_interval ==
799 o.ice_backup_candidate_pair_ping_interval &&
800 continual_gathering_policy == o.continual_gathering_policy &&
801 certificates == o.certificates &&
802 prioritize_most_likely_ice_candidate_pairs ==
803 o.prioritize_most_likely_ice_candidate_pairs &&
804 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800805 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700806 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100807 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800808 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800809 screencast_min_bitrate == o.screencast_min_bitrate &&
810 combined_audio_video_bwe == o.combined_audio_video_bwe &&
811 enable_dtls_srtp == o.enable_dtls_srtp &&
812 ice_candidate_pool_size == o.ice_candidate_pool_size &&
813 prune_turn_ports == o.prune_turn_ports &&
814 presume_writable_when_fully_relayed ==
815 o.presume_writable_when_fully_relayed &&
816 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800817 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800818 ice_check_interval_strong_connectivity ==
819 o.ice_check_interval_strong_connectivity &&
820 ice_check_interval_weak_connectivity ==
821 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700822 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700823 ice_unwritable_timeout == o.ice_unwritable_timeout &&
824 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800825 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800826 stun_candidate_keepalive_interval ==
827 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200828 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800829 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800830 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700831 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700832 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700833 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700834 use_media_transport_for_data_channels ==
835 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100836 crypto_options == o.crypto_options &&
837 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800838}
839
840bool PeerConnectionInterface::RTCConfiguration::operator!=(
841 const PeerConnectionInterface::RTCConfiguration& o) const {
842 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800843}
844
zhihuang8f65cdf2016-05-06 18:40:30 -0700845// Generate a RTCP CNAME when a PeerConnection is created.
846std::string GenerateRtcpCname() {
847 std::string cname;
848 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100849 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800850 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700851 }
852 return cname;
853}
854
zhihuang1c378ed2017-08-17 14:10:50 -0700855bool ValidateOfferAnswerOptions(
856 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
857 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
858 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700859}
860
zhihuang1c378ed2017-08-17 14:10:50 -0700861// From |rtc_options|, fill parts of |session_options| shared by all generated
862// m= sections (in other words, nothing that involves a map/array).
863void ExtractSharedMediaSessionOptions(
864 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
865 cricket::MediaSessionOptions* session_options) {
866 session_options->vad_enabled = rtc_options.voice_activity_detection;
867 session_options->bundle_enabled = rtc_options.use_rtp_mux;
868}
zhihuanga77e6bb2017-08-14 18:17:48 -0700869
zhihuang38ede132017-06-15 12:52:32 -0700870PeerConnection::PeerConnection(PeerConnectionFactory* factory,
871 std::unique_ptr<RtcEventLog> event_log,
872 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700874 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100875 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700876 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700877 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700878 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100879 call_(std::move(call)),
880 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000881
882PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100883 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800884 RTC_DCHECK_RUN_ON(signaling_thread());
885
Steve Anton8af21862017-12-15 11:20:13 -0800886 // Need to stop transceivers before destroying the stats collector because
887 // AudioRtpSender has a reference to the StatsCollector it will update when
888 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100889 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800890 transceiver->Stop();
891 }
Steve Anton4171afb2017-11-20 10:20:22 -0800892
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700893 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800894 if (stats_collector_) {
895 stats_collector_->WaitForPendingRequest();
896 stats_collector_ = nullptr;
897 }
Steve Anton75737c02017-11-06 10:37:17 -0800898
Steve Anton8af21862017-12-15 11:20:13 -0800899 // Don't destroy BaseChannels until after stats has been cleaned up so that
900 // the last stats request can still read from the channels.
901 DestroyAllChannels();
902
Mirko Bonadei675513b2017-11-09 11:09:25 +0100903 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800904
905 webrtc_session_desc_factory_.reset();
906 sctp_invoker_.reset();
907 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800908 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800909 transport_controller_.reset();
910
deadbeef91dd5672016-05-18 16:55:30 -0700911 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100912 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
913 RTC_DCHECK_RUN_ON(network_thread());
914 port_allocator_.reset();
915 });
eladalon248fd4f2017-09-06 05:18:15 -0700916 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700917 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100918 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700919 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800920 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700921 event_log_.reset();
922 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923}
924
Steve Anton8af21862017-12-15 11:20:13 -0800925void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800926 // Destroy video channels first since they may have a pointer to a voice
927 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100928 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800929 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800930 DestroyTransceiverChannel(transceiver);
931 }
932 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100933 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800934 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800935 DestroyTransceiverChannel(transceiver);
936 }
937 }
938 DestroyDataChannel();
939}
940
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000942 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700943 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100944 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100945 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100946 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700947
948 RTCError config_error = ValidateConfiguration(configuration);
949 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100950 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700951 return false;
952 }
953
Benjamin Wrightcab58882018-05-02 15:12:47 -0700954 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100955 RTC_LOG(LS_ERROR)
956 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100957 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800958 return false;
959 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200960
Benjamin Wrightcab58882018-05-02 15:12:47 -0700961 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800962 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100963 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100964 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800965 return false;
966 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700967
Benjamin Wrightcab58882018-05-02 15:12:47 -0700968 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700969 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700970 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700971 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800972
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200973 cricket::ServerAddresses stun_servers;
974 std::vector<cricket::RelayServerConfig> turn_servers;
975
976 RTCErrorType parse_error =
977 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
978 if (parse_error != RTCErrorType::NONE) {
979 return false;
980 }
981
deadbeef91dd5672016-05-18 16:55:30 -0700982 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700983 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100984 const auto pa_result =
985 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200986 RTC_FROM_HERE,
987 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100988 stun_servers, turn_servers, configuration));
989
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200990 // If initialization was successful, note if STUN or TURN servers
991 // were supplied.
992 if (!stun_servers.empty()) {
993 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
994 }
995 if (!turn_servers.empty()) {
996 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
997 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700999 // Send information about IPv4/IPv6 status.
1000 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001001 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001002 address_family = kPeerConnection_IPv6;
1003 } else {
1004 address_family = kPeerConnection_IPv4;
1005 }
1006 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1007 kPeerConnectionAddressFamilyCounter_Max);
1008
Zhi Huange830e682018-03-30 10:48:35 -07001009 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1010
Steve Anton75737c02017-11-06 10:37:17 -08001011 // RFC 3264: The numeric value of the session id and version in the
1012 // o line MUST be representable with a "64 bit signed integer".
1013 // Due to this constraint session id |session_id_| is max limited to
1014 // LLONG_MAX.
1015 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001016 JsepTransportController::Config config;
1017 config.redetermine_role_on_ice_restart =
1018 configuration.redetermine_role_on_ice_restart;
1019 config.ssl_max_version = factory_->options().ssl_max_version;
1020 config.disable_encryption = options.disable_encryption;
1021 config.bundle_policy = configuration.bundle_policy;
1022 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001023 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1024 // stub.
1025 config.crypto_options = configuration.crypto_options.has_value()
1026 ? *configuration.crypto_options
1027 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001028 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001029 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001030#if defined(ENABLE_EXTERNAL_AUTH)
1031 config.enable_external_auth = true;
1032#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001033 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001034
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001035 if (configuration.use_media_transport ||
1036 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001037 if (!factory_->media_transport_factory()) {
1038 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001039 << "PeerConnecton is initialized with use_media_transport = true or "
1040 << "use_media_transport_for_data_channels = true "
1041 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001042 return false;
1043 }
1044
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001045 if (configuration.use_media_transport ||
1046 configuration.use_media_transport_for_data_channels) {
1047 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1048 // RTP media transport is introduced. But until then, we require SDES to
1049 // be enabled.
1050 if (configuration.enable_dtls_srtp.has_value() &&
1051 configuration.enable_dtls_srtp.value()) {
1052 RTC_LOG(LS_WARNING)
1053 << "When media transport is used, SDES must be enabled. Set "
1054 "configuration.enable_dtls_srtp to false. use_media_transport="
1055 << configuration.use_media_transport
1056 << ", use_media_transport_for_data_channels="
1057 << configuration.use_media_transport_for_data_channels;
1058 return false;
1059 }
1060 }
1061
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001062 config.use_media_transport_for_media = configuration.use_media_transport;
1063 config.use_media_transport_for_data_channels =
1064 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001065 config.media_transport_factory = factory_->media_transport_factory();
1066 }
1067
Zhi Huange830e682018-03-30 10:48:35 -07001068 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001069 signaling_thread(), network_thread(), port_allocator_.get(),
1070 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001071 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001072 this, &PeerConnection::OnTransportControllerConnectionState);
1073 transport_controller_->SignalStandardizedIceConnectionState.connect(
1074 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001075 transport_controller_->SignalConnectionState.connect(
1076 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001077 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001078 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001079 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001080 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001081 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001082 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1083 transport_controller_->SignalDtlsHandshakeError.connect(
1084 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1085
1086 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001087
deadbeefab9b2d12015-10-14 11:33:11 -07001088 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001089 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090
Steve Antonba818672017-11-06 10:21:57 -08001091 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001092 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001093
Steve Anton75737c02017-11-06 10:37:17 -08001094 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1095 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1096 if (!configuration.certificates.empty()) {
1097 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1098 // just picking the first one. The decision should be made based on the DTLS
1099 // handshake. The DTLS negotiations need to know about all certificates.
1100 certificate = configuration.certificates[0];
1101 }
1102
Steve Antond25da372017-11-06 14:50:29 -08001103 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001104
1105 if (options.disable_encryption) {
1106 dtls_enabled_ = false;
1107 } else {
1108 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001109 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001110 // |configuration| can override the default |dtls_enabled_| value.
1111 if (configuration.enable_dtls_srtp) {
1112 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1113 }
1114 }
1115
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001116 if (configuration.use_media_transport_for_data_channels) {
1117 if (configuration.enable_rtp_data_channel) {
1118 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1119 "use_media_transport_for_data_channels are "
1120 "incompatible and cannot both be set to true";
1121 return false;
1122 }
1123 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1124 } else if (configuration.enable_rtp_data_channel) {
1125 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1126 // set. It takes precendence over the disable_sctp_data_channels
1127 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001128 data_channel_type_ = cricket::DCT_RTP;
1129 } else {
1130 // DTLS has to be enabled to use SCTP.
1131 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1132 data_channel_type_ = cricket::DCT_SCTP;
1133 }
1134 }
1135
1136 video_options_.screencast_min_bitrate_kbps =
1137 configuration.screencast_min_bitrate;
1138 audio_options_.combined_audio_video_bwe =
1139 configuration.combined_audio_video_bwe;
1140
1141 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001142 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001143
1144 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001145 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001146
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001147 audio_options_.audio_jitter_buffer_min_delay_ms =
1148 configuration.audio_jitter_buffer_min_delay_ms;
1149
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001150 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1151 configuration.audio_jitter_buffer_enable_rtx_handling;
1152
Steve Anton75737c02017-11-06 10:37:17 -08001153 // Whether the certificate generator/certificate is null or not determines
1154 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1155 // the right instructions by clearing the variables if needed.
1156 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001157 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001158 certificate = nullptr;
1159 } else if (certificate) {
1160 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001161 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001162 }
1163
1164 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1165 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001166 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001167 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1168 this, &PeerConnection::OnCertificateReady);
1169
1170 if (options.disable_encryption) {
1171 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1172 }
1173
1174 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001175 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001176 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001177
Steve Anton4171afb2017-11-20 10:20:22 -08001178 // Add default audio/video transceivers for Plan B SDP.
1179 if (!IsUnifiedPlan()) {
1180 transceivers_.push_back(
1181 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1182 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1183 transceivers_.push_back(
1184 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1185 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1186 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001187 int delay_ms =
1188 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001189 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1190 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 return true;
1192}
1193
Steve Anton038834f2017-07-14 15:59:59 -07001194RTCError PeerConnection::ValidateConfiguration(
1195 const RTCConfiguration& config) const {
1196 if (config.ice_regather_interval_range &&
1197 config.continual_gathering_policy == GATHER_ONCE) {
1198 return RTCError(RTCErrorType::INVALID_PARAMETER,
1199 "ice_regather_interval_range specified but continual "
1200 "gathering policy is GATHER_ONCE");
1201 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001202 auto result =
1203 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1204 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001205}
1206
Yves Gerey665174f2018-06-19 15:03:05 +02001207rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001208 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001209 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1210 "Plan SdpSemantics. Please use GetSenders "
1211 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001212 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001213}
1214
Yves Gerey665174f2018-06-19 15:03:05 +02001215rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001216 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001217 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1218 "Plan SdpSemantics. Please use GetReceivers "
1219 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001220 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221}
1222
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001223bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001224 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001225 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1226 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001227 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 if (IsClosed()) {
1229 return false;
1230 }
deadbeefab9b2d12015-10-14 11:33:11 -07001231 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232 return false;
1233 }
deadbeefab9b2d12015-10-14 11:33:11 -07001234
1235 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001236 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1237 observer->SignalAudioTrackAdded.connect(this,
1238 &PeerConnection::OnAudioTrackAdded);
1239 observer->SignalAudioTrackRemoved.connect(
1240 this, &PeerConnection::OnAudioTrackRemoved);
1241 observer->SignalVideoTrackAdded.connect(this,
1242 &PeerConnection::OnVideoTrackAdded);
1243 observer->SignalVideoTrackRemoved.connect(
1244 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001245 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001246
deadbeefab9b2d12015-10-14 11:33:11 -07001247 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001248 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001249 }
1250 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001251 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001252 }
1253
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001254 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001255 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 return true;
1257}
1258
1259void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001260 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001261 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1262 "Plan SdpSemantics. Please use RemoveTrack "
1263 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001264 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001265 if (!IsClosed()) {
1266 for (const auto& track : local_stream->GetAudioTracks()) {
1267 RemoveAudioTrack(track.get(), local_stream);
1268 }
1269 for (const auto& track : local_stream->GetVideoTracks()) {
1270 RemoveVideoTrack(track.get(), local_stream);
1271 }
deadbeefab9b2d12015-10-14 11:33:11 -07001272 }
deadbeefab9b2d12015-10-14 11:33:11 -07001273 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001274 stream_observers_.erase(
1275 std::remove_if(
1276 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001277 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001278 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001279 }),
1280 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001281
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 if (IsClosed()) {
1283 return;
1284 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001285 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286}
1287
Steve Anton2d6c76a2018-01-05 17:10:52 -08001288RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001289 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001290 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001291 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001292 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001293 if (!track) {
1294 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1295 }
1296 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1297 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1299 "Track has invalid kind: " + track->kind());
1300 }
Steve Antonf9381f02017-12-14 10:23:57 -08001301 if (IsClosed()) {
1302 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1303 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001304 }
Steve Anton4171afb2017-11-20 10:20:22 -08001305 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001306 LOG_AND_RETURN_ERROR(
1307 RTCErrorType::INVALID_PARAMETER,
1308 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001309 }
Steve Antonf9381f02017-12-14 10:23:57 -08001310 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001311 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1312 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001313 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001314 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001315 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001316 }
1317 return sender_or_error;
1318}
deadbeefe1f9d832016-01-14 15:35:42 -08001319
Steve Antonf9381f02017-12-14 10:23:57 -08001320RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1321PeerConnection::AddTrackPlanB(
1322 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001323 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001324 if (stream_ids.size() > 1u) {
1325 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1326 "AddTrack with more than one stream is not "
1327 "supported with Plan B semantics.");
1328 }
1329 std::vector<std::string> adjusted_stream_ids = stream_ids;
1330 if (adjusted_stream_ids.empty()) {
1331 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1332 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001333 cricket::MediaType media_type =
1334 (track->kind() == MediaStreamTrackInterface::kAudioKind
1335 ? cricket::MEDIA_TYPE_AUDIO
1336 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001337 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001338 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001339 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001340 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001341 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001342 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001343 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001344 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001345 if (sender_info) {
1346 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001347 }
Steve Antonf9381f02017-12-14 10:23:57 -08001348 } else {
1349 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001350 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001351 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001352 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001353 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001354 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001355 if (sender_info) {
1356 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001357 }
deadbeefe1f9d832016-01-14 15:35:42 -08001358 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001359 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001360}
deadbeefe1f9d832016-01-14 15:35:42 -08001361
Steve Antonf9381f02017-12-14 10:23:57 -08001362RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1363PeerConnection::AddTrackUnifiedPlan(
1364 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001365 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001366 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1367 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001368 RTC_LOG(LS_INFO) << "Reusing an existing "
1369 << cricket::MediaTypeToString(transceiver->media_type())
1370 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001371 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001372 transceiver->internal()->set_direction(
1373 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001374 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001375 transceiver->internal()->set_direction(
1376 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001377 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001378 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001379 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001380 } else {
1381 cricket::MediaType media_type =
1382 (track->kind() == MediaStreamTrackInterface::kAudioKind
1383 ? cricket::MEDIA_TYPE_AUDIO
1384 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001385 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1386 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001387 std::string sender_id = track->id();
1388 // Avoid creating a sender with an existing ID by generating a random ID.
1389 // This can happen if this is the second time AddTrack has created a sender
1390 // for this track.
1391 if (FindSenderById(sender_id)) {
1392 sender_id = rtc::CreateRandomUuid();
1393 }
Florent Castelli892acf02018-10-01 22:47:20 +02001394 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1396 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001397 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001398 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001399 }
Steve Antonf9381f02017-12-14 10:23:57 -08001400 return transceiver->sender();
1401}
1402
1403rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1404PeerConnection::FindFirstTransceiverForAddedTrack(
1405 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1406 RTC_DCHECK(track);
1407 for (auto transceiver : transceivers_) {
1408 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001409 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001410 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001411 !transceiver->internal()->has_ever_been_used_to_send() &&
1412 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001413 return transceiver;
1414 }
1415 }
1416 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001417}
1418
1419bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1420 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001421 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001422}
1423
Steve Anton24db5732018-07-23 10:27:33 -07001424RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001425 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001426 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001427 if (!sender) {
1428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1429 }
deadbeefe1f9d832016-01-14 15:35:42 -08001430 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001431 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1432 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001433 }
Steve Antonf9381f02017-12-14 10:23:57 -08001434 if (IsUnifiedPlan()) {
1435 auto transceiver = FindTransceiverBySender(sender);
1436 if (!transceiver || !sender->track()) {
1437 return RTCError::OK();
1438 }
1439 sender->SetTrack(nullptr);
1440 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001441 transceiver->internal()->set_direction(
1442 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001443 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001444 transceiver->internal()->set_direction(
1445 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001446 }
Steve Anton4171afb2017-11-20 10:20:22 -08001447 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001448 bool removed;
1449 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1450 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1451 } else {
1452 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1453 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1454 }
1455 if (!removed) {
1456 LOG_AND_RETURN_ERROR(
1457 RTCErrorType::INVALID_PARAMETER,
1458 "Couldn't find sender " + sender->id() + " to remove.");
1459 }
Steve Anton4171afb2017-11-20 10:20:22 -08001460 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001461 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001462 return RTCError::OK();
1463}
1464
1465rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1466PeerConnection::FindTransceiverBySender(
1467 rtc::scoped_refptr<RtpSenderInterface> sender) {
1468 for (auto transceiver : transceivers_) {
1469 if (transceiver->sender() == sender) {
1470 return transceiver;
1471 }
1472 }
1473 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001474}
1475
Steve Anton9158ef62017-11-27 13:01:52 -08001476RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1477PeerConnection::AddTransceiver(
1478 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1479 return AddTransceiver(track, RtpTransceiverInit());
1480}
1481
1482RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1483PeerConnection::AddTransceiver(
1484 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1485 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001486 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001487 RTC_CHECK(IsUnifiedPlan())
1488 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001489 if (!track) {
1490 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1491 }
1492 cricket::MediaType media_type;
1493 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1494 media_type = cricket::MEDIA_TYPE_AUDIO;
1495 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1496 media_type = cricket::MEDIA_TYPE_VIDEO;
1497 } else {
1498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1499 "Track kind is not audio or video");
1500 }
1501 return AddTransceiver(media_type, track, init);
1502}
1503
1504RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1505PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1506 return AddTransceiver(media_type, RtpTransceiverInit());
1507}
1508
1509RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1510PeerConnection::AddTransceiver(cricket::MediaType media_type,
1511 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001512 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001513 RTC_CHECK(IsUnifiedPlan())
1514 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001515 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1516 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1517 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1518 "media type is not audio or video");
1519 }
1520 return AddTransceiver(media_type, nullptr, init);
1521}
1522
1523RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1524PeerConnection::AddTransceiver(
1525 cricket::MediaType media_type,
1526 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001527 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001528 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001529 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1530 media_type == cricket::MEDIA_TYPE_VIDEO));
1531 if (track) {
1532 RTC_DCHECK_EQ(media_type,
1533 (track->kind() == MediaStreamTrackInterface::kAudioKind
1534 ? cricket::MEDIA_TYPE_AUDIO
1535 : cricket::MEDIA_TYPE_VIDEO));
1536 }
1537
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001538 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1539 init.send_encodings.size(), 0, 7, 8);
1540
Amit Hilbuchaa584152019-02-06 17:09:52 -08001541 size_t num_rids = absl::c_count_if(init.send_encodings,
1542 [](const RtpEncodingParameters& encoding) {
1543 return !encoding.rid.empty();
1544 });
1545 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001546 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001547 RTCErrorType::INVALID_PARAMETER,
1548 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001549 }
1550
Amit Hilbuchf4770402019-04-08 14:11:57 -07001551 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1552 [](const RtpEncodingParameters& encoding) {
1553 return !IsLegalRsidName(encoding.rid);
1554 })) {
1555 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1556 "Invalid RID value provided.");
1557 }
1558
Amit Hilbuchaa584152019-02-06 17:09:52 -08001559 if (absl::c_any_of(init.send_encodings,
1560 [](const RtpEncodingParameters& encoding) {
1561 return encoding.ssrc.has_value();
1562 })) {
1563 LOG_AND_RETURN_ERROR(
1564 RTCErrorType::UNSUPPORTED_PARAMETER,
1565 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001566 }
1567
1568 RtpParameters parameters;
1569 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001570
1571 // Encodings are dropped from the tail if too many are provided.
1572 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1573 parameters.encodings.erase(
1574 parameters.encodings.begin() + kMaxSimulcastStreams,
1575 parameters.encodings.end());
1576 }
1577
1578 // Single RID should be removed.
1579 if (parameters.encodings.size() == 1 &&
1580 !parameters.encodings[0].rid.empty()) {
1581 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1582 parameters.encodings[0].rid.clear();
1583 }
1584
1585 // If RIDs were not provided, they are generated for simulcast scenario.
1586 if (parameters.encodings.size() > 1 && num_rids == 0) {
1587 rtc::UniqueStringGenerator rid_generator;
1588 for (RtpEncodingParameters& encoding : parameters.encodings) {
1589 encoding.rid = rid_generator();
1590 }
1591 }
1592
Florent Castelli892acf02018-10-01 22:47:20 +02001593 if (UnimplementedRtpParameterHasValue(parameters)) {
1594 LOG_AND_RETURN_ERROR(
1595 RTCErrorType::UNSUPPORTED_PARAMETER,
1596 "Attempted to set an unimplemented parameter of RtpParameters.");
1597 }
Steve Anton9158ef62017-11-27 13:01:52 -08001598
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001599 auto result = cricket::CheckRtpParametersValues(parameters);
1600 if (!result.ok()) {
1601 LOG_AND_RETURN_ERROR(result.type(), result.message());
1602 }
1603
Steve Anton3d954a62018-04-02 11:27:23 -07001604 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1605 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001606 // Set the sender ID equal to the track ID if the track is specified unless
1607 // that sender ID is already in use.
1608 std::string sender_id =
1609 (track && !FindSenderById(track->id()) ? track->id()
1610 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001611 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001612 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001613 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1614 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1615 transceiver->internal()->set_direction(init.direction);
1616
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001617 if (update_negotiation_needed) {
1618 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001619 }
Steve Antonf9381f02017-12-14 10:23:57 -08001620
1621 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1622}
1623
Steve Anton02ee47c2018-01-10 16:26:06 -08001624rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1625PeerConnection::CreateSender(
1626 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001627 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001628 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001629 const std::vector<std::string>& stream_ids,
1630 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001631 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001632 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001633 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1634 RTC_DCHECK(!track ||
1635 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1636 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1637 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001638 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001639 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001640 } else {
1641 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1642 RTC_DCHECK(!track ||
1643 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1644 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001645 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001646 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001647 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001648 bool set_track_succeeded = sender->SetTrack(track);
1649 RTC_DCHECK(set_track_succeeded);
1650 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001651 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001652 return sender;
1653}
1654
1655rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1656PeerConnection::CreateReceiver(cricket::MediaType media_type,
1657 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001658 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1659 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001660 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001661 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001662 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1663 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001664 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001665 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001666 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001667 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001668 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1669 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001670 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001671 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001672 return receiver;
1673}
1674
1675rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1676PeerConnection::CreateAndAddTransceiver(
1677 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1678 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1679 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001680 // Ensure that the new sender does not have an ID that is already in use by
1681 // another sender.
1682 // Allow receiver IDs to conflict since those come from remote SDP (which
1683 // could be invalid, but should not cause a crash).
1684 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001685 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1686 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001687 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001688 transceiver->internal()->SignalNegotiationNeeded.connect(
1689 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001690 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001691}
1692
Steve Anton52d86772018-02-20 15:48:12 -08001693void PeerConnection::OnNegotiationNeeded() {
1694 RTC_DCHECK_RUN_ON(signaling_thread());
1695 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001696 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001697}
1698
deadbeeffac06552015-11-25 11:26:01 -08001699rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001700 const std::string& kind,
1701 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001702 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001703 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1704 "Plan SdpSemantics. Please use AddTransceiver "
1705 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001706 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001707 if (IsClosed()) {
1708 return nullptr;
1709 }
Steve Anton4171afb2017-11-20 10:20:22 -08001710
Seth Hampson5b4f0752018-04-02 16:31:36 -07001711 // Internally we need to have one stream with Plan B semantics, so we
1712 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001713 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001714 if (stream_id.empty()) {
1715 stream_ids.push_back(rtc::CreateRandomUuid());
1716 RTC_LOG(LS_INFO)
1717 << "No stream_id specified for sender. Generated stream ID: "
1718 << stream_ids[0];
1719 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001720 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001721 }
1722
Steve Anton4171afb2017-11-20 10:20:22 -08001723 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001724 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001725 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001726 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001727 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001728 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001729 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001730 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001731 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001732 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001733 auto video_sender =
1734 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001735 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001736 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001737 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001738 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001739 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001741 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001742 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001743 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001744
deadbeefe1f9d832016-01-14 15:35:42 -08001745 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001746}
1747
deadbeef70ab1a12015-09-28 16:53:55 -07001748std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1749 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001750 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001751 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001752 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001753 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001754 }
1755 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001756}
1757
Steve Anton4171afb2017-11-20 10:20:22 -08001758std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1759PeerConnection::GetSendersInternal() const {
1760 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1761 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001762 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001763 auto senders = transceiver->internal()->senders();
1764 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1765 }
1766 return all_senders;
1767}
1768
deadbeef70ab1a12015-09-28 16:53:55 -07001769std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1770PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001771 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001772 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001773 for (const auto& receiver : GetReceiversInternal()) {
1774 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001775 }
1776 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001777}
1778
Steve Anton4171afb2017-11-20 10:20:22 -08001779std::vector<
1780 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1781PeerConnection::GetReceiversInternal() const {
1782 std::vector<
1783 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1784 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001785 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001786 auto receivers = transceiver->internal()->receivers();
1787 all_receivers.insert(all_receivers.end(), receivers.begin(),
1788 receivers.end());
1789 }
1790 return all_receivers;
1791}
1792
Steve Anton9158ef62017-11-27 13:01:52 -08001793std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1794PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001795 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001796 RTC_CHECK(IsUnifiedPlan())
1797 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001798 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001799 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001800 all_transceivers.push_back(transceiver);
1801 }
1802 return all_transceivers;
1803}
1804
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001806 MediaStreamTrackInterface* track,
1807 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001808 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001809 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001810 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001811 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812 return false;
1813 }
1814
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001815 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001816 // The StatsCollector is used to tell if a track is valid because it may
1817 // remember tracks that the PeerConnection previously removed.
1818 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1820 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001821 return false;
1822 }
Steve Antonad182762018-09-05 20:22:40 +00001823 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1824 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825 return true;
1826}
1827
hbos74e1a4f2016-09-15 23:33:01 -07001828void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001829 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001830 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001831 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001832 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001833 stats_collector_->GetStatsReport(callback);
1834}
1835
Henrik Boström1df1bf82018-03-20 13:24:20 +01001836void PeerConnection::GetStats(
1837 rtc::scoped_refptr<RtpSenderInterface> selector,
1838 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1839 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001840 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001841 RTC_DCHECK(callback);
1842 RTC_DCHECK(stats_collector_);
1843 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1844 if (selector) {
1845 for (const auto& proxy_transceiver : transceivers_) {
1846 for (const auto& proxy_sender :
1847 proxy_transceiver->internal()->senders()) {
1848 if (proxy_sender == selector) {
1849 internal_sender = proxy_sender->internal();
1850 break;
1851 }
1852 }
1853 if (internal_sender)
1854 break;
1855 }
1856 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001857 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001858 // belong to the PeerConnection (in Plan B, senders can be removed from the
1859 // PeerConnection). This means that "all the stats objects representing the
1860 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1861 // produces an empty stats report.
1862 stats_collector_->GetStatsReport(internal_sender, callback);
1863}
1864
1865void PeerConnection::GetStats(
1866 rtc::scoped_refptr<RtpReceiverInterface> selector,
1867 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1868 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001869 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001870 RTC_DCHECK(callback);
1871 RTC_DCHECK(stats_collector_);
1872 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1873 if (selector) {
1874 for (const auto& proxy_transceiver : transceivers_) {
1875 for (const auto& proxy_receiver :
1876 proxy_transceiver->internal()->receivers()) {
1877 if (proxy_receiver == selector) {
1878 internal_receiver = proxy_receiver->internal();
1879 break;
1880 }
1881 }
1882 if (internal_receiver)
1883 break;
1884 }
1885 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001886 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001887 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1888 // the PeerConnection). This means that "all the stats objects representing
1889 // the selector" is an empty set. Invoking GetStatsReport() with a null
1890 // selector produces an empty stats report.
1891 stats_collector_->GetStatsReport(internal_receiver, callback);
1892}
1893
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001895 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896 return signaling_state_;
1897}
1898
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001899PeerConnectionInterface::IceConnectionState
1900PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001901 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902 return ice_connection_state_;
1903}
1904
Alex Loiko9289eda2018-11-23 16:18:59 +00001905PeerConnectionInterface::IceConnectionState
1906PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001907 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001908 return standardized_ice_connection_state_;
1909}
1910
Jonas Olsson635474e2018-10-18 15:58:17 +02001911PeerConnectionInterface::PeerConnectionState
1912PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001913 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001914 return connection_state_;
1915}
1916
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917PeerConnectionInterface::IceGatheringState
1918PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001919 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001920 return ice_gathering_state_;
1921}
1922
Yves Gerey665174f2018-06-19 15:03:05 +02001923rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924 const std::string& label,
1925 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001926 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001927 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001928
deadbeefab9b2d12015-10-14 11:33:11 -07001929 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001930
kwibergd1fe2812016-04-27 06:47:29 -07001931 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001932 if (config) {
1933 internal_config.reset(new InternalDataChannelInit(*config));
1934 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001935 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001936 InternalCreateDataChannel(label, internal_config.get()));
1937 if (!channel.get()) {
1938 return nullptr;
1939 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001940
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001941 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1942 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001943 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001944 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001945 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001946 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001947 return DataChannelProxy::Create(signaling_thread(), channel.get());
1948}
1949
1950void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001951 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001952 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001953 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001954
nisse7ce109a2017-01-31 00:57:56 -08001955 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001956 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001957 return;
1958 }
deadbeefab9b2d12015-10-14 11:33:11 -07001959
Steve Anton8d3444d2017-10-20 15:30:51 -07001960 if (IsClosed()) {
1961 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001962 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001963 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001964 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001965 return;
1966 }
1967
zhihuang1c378ed2017-08-17 14:10:50 -07001968 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001969 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001970 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001971 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001972 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001973 return;
1974 }
1975
Steve Anton22da89f2018-01-25 13:58:07 -08001976 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1977 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1978 if (IsUnifiedPlan()) {
1979 RTCError error = HandleLegacyOfferOptions(options);
1980 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001981 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001982 return;
1983 }
1984 }
1985
zhihuang1c378ed2017-08-17 14:10:50 -07001986 cricket::MediaSessionOptions session_options;
1987 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001988 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989}
1990
Steve Anton22da89f2018-01-25 13:58:07 -08001991RTCError PeerConnection::HandleLegacyOfferOptions(
1992 const RTCOfferAnswerOptions& options) {
1993 RTC_DCHECK(IsUnifiedPlan());
1994
1995 if (options.offer_to_receive_audio == 0) {
1996 RemoveRecvDirectionFromReceivingTransceiversOfType(
1997 cricket::MEDIA_TYPE_AUDIO);
1998 } else if (options.offer_to_receive_audio == 1) {
1999 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2000 } else if (options.offer_to_receive_audio > 1) {
2001 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2002 "offer_to_receive_audio > 1 is not supported.");
2003 }
2004
2005 if (options.offer_to_receive_video == 0) {
2006 RemoveRecvDirectionFromReceivingTransceiversOfType(
2007 cricket::MEDIA_TYPE_VIDEO);
2008 } else if (options.offer_to_receive_video == 1) {
2009 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2010 } else if (options.offer_to_receive_video > 1) {
2011 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2012 "offer_to_receive_video > 1 is not supported.");
2013 }
2014
2015 return RTCError::OK();
2016}
2017
2018void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2019 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002020 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002021 RtpTransceiverDirection new_direction =
2022 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2023 if (new_direction != transceiver->direction()) {
2024 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2025 << " transceiver (MID="
2026 << transceiver->mid().value_or("<not set>") << ") from "
2027 << RtpTransceiverDirectionToString(
2028 transceiver->direction())
2029 << " to "
2030 << RtpTransceiverDirectionToString(new_direction)
2031 << " since CreateOffer specified offer_to_receive=0";
2032 transceiver->internal()->set_direction(new_direction);
2033 }
Steve Anton22da89f2018-01-25 13:58:07 -08002034 }
2035}
2036
2037void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2038 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002039 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002040 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002041 RTC_LOG(LS_INFO)
2042 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2043 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002044 RtpTransceiverInit init;
2045 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002046 AddTransceiver(media_type, nullptr, init,
2047 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002048 }
2049}
2050
2051std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2052PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2053 std::vector<
2054 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2055 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002056 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002057 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002058 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2059 receiving_transceivers.push_back(transceiver);
2060 }
2061 }
2062 return receiving_transceivers;
2063}
2064
htaa2a49d92016-03-04 02:51:39 -08002065void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2066 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002067 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002068 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002069 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002070 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002071 return;
2072 }
2073
Steve Antondffead82018-02-06 10:31:29 -08002074 if (!(signaling_state_ == kHaveRemoteOffer ||
2075 signaling_state_ == kHaveLocalPrAnswer)) {
2076 std::string error =
2077 "PeerConnection cannot create an answer in a state other than "
2078 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002079 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002080 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002081 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002082 return;
2083 }
2084
Steve Antondffead82018-02-06 10:31:29 -08002085 // The remote description should be set if we're in the right state.
2086 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002087
Steve Anton22da89f2018-01-25 13:58:07 -08002088 if (IsUnifiedPlan()) {
2089 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2090 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2091 "supported with Unified Plan semantics. Use the "
2092 "RtpTransceiver API instead.";
2093 }
2094 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2095 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2096 "supported with Unified Plan semantics. Use the "
2097 "RtpTransceiver API instead.";
2098 }
2099 }
2100
htaa2a49d92016-03-04 02:51:39 -08002101 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002102 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002103
Steve Antond25da372017-11-06 14:50:29 -08002104 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002105}
2106
2107void PeerConnection::SetLocalDescription(
2108 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002109 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002110 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002111 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002112
Steve Anton80dd7b52018-02-16 17:08:42 -08002113 // The SetLocalDescription contract is that we take ownership of the session
2114 // description regardless of the outcome, so wrap it in a unique_ptr right
2115 // away. Ideally, SetLocalDescription's signature will be changed to take the
2116 // description as a unique_ptr argument to formalize this agreement.
2117 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2118
nisse7ce109a2017-01-31 00:57:56 -08002119 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002120 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002121 return;
2122 }
Steve Anton8a006912017-12-04 15:25:56 -08002123
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002124 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002125 PostSetSessionDescriptionFailure(
2126 observer,
2127 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128 return;
2129 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002130
Steve Anton80dd7b52018-02-16 17:08:42 -08002131 // If a session error has occurred the PeerConnection is in a possibly
2132 // inconsistent state so fail right away.
2133 if (session_error() != SessionError::kNone) {
2134 std::string error_message = GetSessionErrorMsg();
2135 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002136 PostSetSessionDescriptionFailure(
2137 observer,
2138 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002139 return;
2140 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002141
Steve Anton80dd7b52018-02-16 17:08:42 -08002142 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2143 if (!error.ok()) {
2144 std::string error_message = GetSetDescriptionErrorMessage(
2145 cricket::CS_LOCAL, desc->GetType(), error);
2146 RTC_LOG(LS_ERROR) << 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 }
2152
2153 // Grab the description type before moving ownership to ApplyLocalDescription,
2154 // which may destroy it before returning.
2155 const SdpType type = desc->GetType();
2156
2157 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002158 // |desc| may be destroyed at this point.
2159
2160 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002161 // If ApplyLocalDescription fails, the PeerConnection could be in an
2162 // inconsistent state, so act conservatively here and set the session error
2163 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2164 SetSessionError(SessionError::kContent, error.message());
2165 std::string error_message =
2166 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2167 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002168 PostSetSessionDescriptionFailure(
2169 observer,
2170 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002171 return;
2172 }
Steve Anton8a006912017-12-04 15:25:56 -08002173 RTC_DCHECK(local_description());
2174
2175 PostSetSessionDescriptionSuccess(observer);
2176
Steve Antonad182762018-09-05 20:22:40 +00002177 // MaybeStartGathering needs to be called after posting
2178 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2179 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002180 transport_controller_->MaybeStartGathering();
2181
Steve Antona3a92c22017-12-07 10:27:41 -08002182 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002183 // TODO(deadbeef): We already had to hop to the network thread for
2184 // MaybeStartGathering...
2185 network_thread()->Invoke<void>(
2186 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2187 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002188 // Make UMA notes about what was agreed to.
2189 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002190 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002191
2192 if (IsUnifiedPlan()) {
2193 bool was_negotiation_needed = is_negotiation_needed_;
2194 UpdateNegotiationNeeded();
2195 if (signaling_state() == kStable && was_negotiation_needed &&
2196 is_negotiation_needed_) {
2197 Observer()->OnRenegotiationNeeded();
2198 }
2199 }
2200
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002201 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002202}
2203
2204RTCError PeerConnection::ApplyLocalDescription(
2205 std::unique_ptr<SessionDescriptionInterface> desc) {
2206 RTC_DCHECK_RUN_ON(signaling_thread());
2207 RTC_DCHECK(desc);
2208
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 // Update stats here so that we have the most recent stats for tracks and
2210 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002211 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002212
Steve Antondcc3c022017-12-22 16:02:54 -08002213 // Take a reference to the old local description since it's used below to
2214 // compare against the new local description. When setting the new local
2215 // description, grab ownership of the replaced session description in case it
2216 // is the same as |old_local_description|, to keep it alive for the duration
2217 // of the method.
2218 const SessionDescriptionInterface* old_local_description =
2219 local_description();
2220 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002221 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002222 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002223 replaced_local_description = pending_local_description_
2224 ? std::move(pending_local_description_)
2225 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002226 current_local_description_ = std::move(desc);
2227 pending_local_description_ = nullptr;
2228 current_remote_description_ = std::move(pending_remote_description_);
2229 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002230 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002231 pending_local_description_ = std::move(desc);
2232 }
2233 // The session description to apply now must be accessed by
2234 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002235 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002236
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002237 // Report statistics about any use of simulcast.
2238 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2239 *local_description()->description());
2240
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002241 if (!is_caller_) {
2242 if (remote_description()) {
2243 // Remote description was applied first, so this PC is the callee.
2244 is_caller_ = false;
2245 } else {
2246 // Local description is applied first, so this PC is the caller.
2247 is_caller_ = true;
2248 }
2249 }
2250
Zhi Huange830e682018-03-30 10:48:35 -07002251 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2252 if (!error.ok()) {
2253 return error;
2254 }
2255
Steve Antondcc3c022017-12-22 16:02:54 -08002256 if (IsUnifiedPlan()) {
2257 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002258 cricket::CS_LOCAL, *local_description(), old_local_description,
2259 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002260 if (!error.ok()) {
2261 return error;
2262 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002263 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2264 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002265 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002266 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2267 // Note that code paths that don't set MID won't be able to use
2268 // information about DTLS transports.
2269 if (transceiver->mid()) {
2270 auto dtls_transport =
2271 LookupDtlsTransportByMidInternal(*transceiver->mid());
2272 transceiver->internal()->sender_internal()->set_transport(
2273 dtls_transport);
2274 transceiver->internal()->receiver_internal()->set_transport(
2275 dtls_transport);
2276 }
2277
Steve Antondcc3c022017-12-22 16:02:54 -08002278 const ContentInfo* content =
2279 FindMediaSectionForTransceiver(transceiver, local_description());
2280 if (!content) {
2281 continue;
2282 }
2283 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002284 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2285 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002286 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002287 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2288 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2289 // "recvonly", process the removal of a remote track for the media
2290 // description, given transceiver, removeList, and muteTracks.
2291 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2292 (transceiver->internal()->fired_direction() &&
2293 RtpTransceiverDirectionHasRecv(
2294 *transceiver->internal()->fired_direction()))) {
2295 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2296 &removed_streams);
2297 }
2298 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2299 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002300 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002301 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002302 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002303 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002304 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002305 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002306 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002307 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002308 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002309 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002310 }
2311 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002312 // Media channels will be created only when offer is set. These may use new
2313 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002314 if (type == SdpType::kOffer) {
2315 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2316 // description is applied. Restore back to old description.
2317 RTCError error = CreateChannels(*local_description()->description());
2318 if (!error.ok()) {
2319 return error;
2320 }
2321 }
Steve Antondcc3c022017-12-22 16:02:54 -08002322 // Remove unused channels if MediaContentDescription is rejected.
2323 RemoveUnusedChannels(local_description()->description());
2324 }
Steve Anton8a006912017-12-04 15:25:56 -08002325
Zhi Huange830e682018-03-30 10:48:35 -07002326 error = UpdateSessionState(type, cricket::CS_LOCAL,
2327 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002328 if (!error.ok()) {
2329 return error;
2330 }
Steve Antondcc3c022017-12-22 16:02:54 -08002331
Steve Anton8a006912017-12-04 15:25:56 -08002332 if (remote_description()) {
2333 // Now that we have a local description, we can push down remote candidates.
2334 UseCandidatesInSessionDescription(remote_description());
2335 }
2336
2337 pending_ice_restarts_.clear();
2338 if (session_error() != SessionError::kNone) {
2339 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2340 }
2341
deadbeefab9b2d12015-10-14 11:33:11 -07002342 // If setting the description decided our SSL role, allocate any necessary
2343 // SCTP sids.
2344 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002345 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002346 AllocateSctpSids(role);
2347 }
2348
Steve Antond3679212018-01-17 17:41:02 -08002349 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002350 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002351 const ContentInfo* content =
2352 FindMediaSectionForTransceiver(transceiver, local_description());
2353 if (!content) {
2354 continue;
2355 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002356 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2357 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002358 // 0 is a special value meaning "this sender has no associated send
2359 // stream". Need to call this so the sender won't attempt to configure
2360 // a no longer existing stream and run into DCHECKs in the lower
2361 // layers.
2362 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002363 } else {
2364 // Get the StreamParams from the channel which could generate SSRCs.
2365 const std::vector<StreamParams>& streams = channel->local_streams();
2366 transceiver->internal()->sender_internal()->set_stream_ids(
2367 streams[0].stream_ids());
2368 transceiver->internal()->sender_internal()->SetSsrc(
2369 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002370 }
2371 }
2372 } else {
2373 // Plan B semantics.
2374
Steve Antondcc3c022017-12-22 16:02:54 -08002375 // Update state and SSRC of local MediaStreams and DataChannels based on the
2376 // local session description.
2377 const cricket::ContentInfo* audio_content =
2378 GetFirstAudioContent(local_description()->description());
2379 if (audio_content) {
2380 if (audio_content->rejected) {
2381 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2382 } else {
2383 const cricket::AudioContentDescription* audio_desc =
2384 audio_content->media_description()->as_audio();
2385 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2386 }
deadbeeffaac4972015-11-12 15:33:07 -08002387 }
deadbeefab9b2d12015-10-14 11:33:11 -07002388
Steve Antondcc3c022017-12-22 16:02:54 -08002389 const cricket::ContentInfo* video_content =
2390 GetFirstVideoContent(local_description()->description());
2391 if (video_content) {
2392 if (video_content->rejected) {
2393 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2394 } else {
2395 const cricket::VideoContentDescription* video_desc =
2396 video_content->media_description()->as_video();
2397 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2398 }
deadbeeffaac4972015-11-12 15:33:07 -08002399 }
deadbeefab9b2d12015-10-14 11:33:11 -07002400 }
2401
2402 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002403 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002404 if (data_content) {
2405 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002406 data_content->media_description()->as_data();
Harald Alvestrand8a9193c2019-04-16 21:26:47 +02002407 // data_desc will be null if this is an SCTP description.
2408 if (data_desc && absl::StartsWith(data_desc->protocol(),
2409 cricket::kMediaProtocolRtpPrefix)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002410 UpdateLocalRtpDataChannels(data_desc->streams());
2411 }
2412 }
2413
Steve Anton8a006912017-12-04 15:25:56 -08002414 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415}
2416
Steve Anton06817cd2018-12-18 15:55:30 -08002417// The SDP parser used to populate these values by default for the 'content
2418// name' if an a=mid line was absent.
2419static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2420 switch (media_type) {
2421 case cricket::MEDIA_TYPE_AUDIO:
2422 return cricket::CN_AUDIO;
2423 case cricket::MEDIA_TYPE_VIDEO:
2424 return cricket::CN_VIDEO;
2425 case cricket::MEDIA_TYPE_DATA:
2426 return cricket::CN_DATA;
2427 }
2428 RTC_NOTREACHED();
2429 return "";
2430}
2431
2432void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002433 cricket::SessionDescription* new_remote_description) {
2434 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002435 const cricket::ContentInfos& local_contents =
2436 (local_description() ? local_description()->description()->contents()
2437 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002438 const cricket::ContentInfos& remote_contents =
2439 (remote_description() ? remote_description()->description()->contents()
2440 : cricket::ContentInfos());
2441 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2442 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002443 if (!content.name.empty()) {
2444 continue;
2445 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002446 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002447 absl::string_view source_explanation;
2448 if (IsUnifiedPlan()) {
2449 if (i < local_contents.size()) {
2450 new_mid = local_contents[i].name;
2451 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002452 } else if (i < remote_contents.size()) {
2453 new_mid = remote_contents[i].name;
2454 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002455 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002456 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002457 source_explanation = "generated just now";
2458 }
2459 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002460 new_mid = std::string(
2461 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002462 source_explanation = "to match pre-existing behavior";
2463 }
Steve Antond7180cc2019-02-07 10:44:53 -08002464 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002465 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002466 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002467 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2468 << " is missing an a=mid line. Filling in the value '"
2469 << new_mid << "' " << source_explanation << ".";
2470 }
2471}
2472
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002473void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002474 SetSessionDescriptionObserver* observer,
2475 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002476 SetRemoteDescription(
2477 std::unique_ptr<SessionDescriptionInterface>(desc),
2478 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2479 new SetRemoteDescriptionObserverAdapter(this, observer)));
2480}
2481
2482void PeerConnection::SetRemoteDescription(
2483 std::unique_ptr<SessionDescriptionInterface> desc,
2484 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002485 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002486 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002487
nisse7ce109a2017-01-31 00:57:56 -08002488 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002489 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 return;
2491 }
Steve Anton8a006912017-12-04 15:25:56 -08002492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002494 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002495 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002496 return;
2497 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002498
Steve Anton80dd7b52018-02-16 17:08:42 -08002499 // If a session error has occurred the PeerConnection is in a possibly
2500 // inconsistent state so fail right away.
2501 if (session_error() != SessionError::kNone) {
2502 std::string error_message = GetSessionErrorMsg();
2503 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2504 observer->OnSetRemoteDescriptionComplete(
2505 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2506 return;
2507 }
Steve Anton71439a62018-02-15 11:53:06 -08002508
Steve Antonba42e992018-04-09 14:10:01 -07002509 if (desc->GetType() == SdpType::kOffer) {
2510 // Report to UMA the format of the received offer.
2511 ReportSdpFormatReceived(*desc);
2512 }
2513
Steve Anton06817cd2018-12-18 15:55:30 -08002514 // Handle remote descriptions missing a=mid lines for interop with legacy end
2515 // points.
2516 FillInMissingRemoteMids(desc->description());
2517
Steve Anton80dd7b52018-02-16 17:08:42 -08002518 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002519 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002520 std::string error_message = GetSetDescriptionErrorMessage(
2521 cricket::CS_REMOTE, desc->GetType(), error);
2522 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002523 observer->OnSetRemoteDescriptionComplete(
2524 RTCError(error.type(), std::move(error_message)));
2525 return;
2526 }
Steve Anton71439a62018-02-15 11:53:06 -08002527
Steve Anton80dd7b52018-02-16 17:08:42 -08002528 // Grab the description type before moving ownership to
2529 // ApplyRemoteDescription, which may destroy it before returning.
2530 const SdpType type = desc->GetType();
2531
2532 error = ApplyRemoteDescription(std::move(desc));
2533 // |desc| may be destroyed at this point.
2534
2535 if (!error.ok()) {
2536 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2537 // inconsistent state, so act conservatively here and set the session error
2538 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2539 SetSessionError(SessionError::kContent, error.message());
2540 std::string error_message =
2541 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2542 RTC_LOG(LS_ERROR) << error_message;
2543 observer->OnSetRemoteDescriptionComplete(
2544 RTCError(error.type(), std::move(error_message)));
2545 return;
2546 }
2547 RTC_DCHECK(remote_description());
2548
2549 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002550 // TODO(deadbeef): We already had to hop to the network thread for
2551 // MaybeStartGathering...
2552 network_thread()->Invoke<void>(
2553 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2554 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002555 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002556 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002557 }
2558
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002559 if (IsUnifiedPlan()) {
2560 bool was_negotiation_needed = is_negotiation_needed_;
2561 UpdateNegotiationNeeded();
2562 if (signaling_state() == kStable && was_negotiation_needed &&
2563 is_negotiation_needed_) {
2564 Observer()->OnRenegotiationNeeded();
2565 }
2566 }
2567
Steve Anton8a006912017-12-04 15:25:56 -08002568 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002569 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002570}
2571
2572RTCError PeerConnection::ApplyRemoteDescription(
2573 std::unique_ptr<SessionDescriptionInterface> desc) {
2574 RTC_DCHECK_RUN_ON(signaling_thread());
2575 RTC_DCHECK(desc);
2576
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002577 // Update stats here so that we have the most recent stats for tracks and
2578 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002579 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002580
Steve Antondcc3c022017-12-22 16:02:54 -08002581 // Take a reference to the old remote description since it's used below to
2582 // compare against the new remote description. When setting the new remote
2583 // description, grab ownership of the replaced session description in case it
2584 // is the same as |old_remote_description|, to keep it alive for the duration
2585 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002586 const SessionDescriptionInterface* old_remote_description =
2587 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002588 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002589 SdpType type = desc->GetType();
2590 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002591 replaced_remote_description = pending_remote_description_
2592 ? std::move(pending_remote_description_)
2593 : std::move(current_remote_description_);
2594 current_remote_description_ = std::move(desc);
2595 pending_remote_description_ = nullptr;
2596 current_local_description_ = std::move(pending_local_description_);
2597 } else {
2598 replaced_remote_description = std::move(pending_remote_description_);
2599 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002600 }
Steve Anton8a006912017-12-04 15:25:56 -08002601 // The session description to apply now must be accessed by
2602 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002603 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002605 // Report statistics about any use of simulcast.
2606 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2607 *remote_description()->description());
2608
Zhi Huange830e682018-03-30 10:48:35 -07002609 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2610 if (!error.ok()) {
2611 return error;
2612 }
Steve Anton8a006912017-12-04 15:25:56 -08002613 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002614 if (IsUnifiedPlan()) {
2615 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002616 cricket::CS_REMOTE, *remote_description(), local_description(),
2617 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002618 if (!error.ok()) {
2619 return error;
2620 }
Steve Antondcc3c022017-12-22 16:02:54 -08002621 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002622 // Media channels will be created only when offer is set. These may use new
2623 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002624 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002625 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002626 // description is applied. Restore back to old description.
2627 RTCError error = CreateChannels(*remote_description()->description());
2628 if (!error.ok()) {
2629 return error;
2630 }
2631 }
Steve Antondcc3c022017-12-22 16:02:54 -08002632 // Remove unused channels if MediaContentDescription is rejected.
2633 RemoveUnusedChannels(remote_description()->description());
2634 }
Steve Anton8a006912017-12-04 15:25:56 -08002635
Zhi Huange830e682018-03-30 10:48:35 -07002636 // NOTE: Candidates allocation will be initiated only when
2637 // SetLocalDescription is called.
2638 error = UpdateSessionState(type, cricket::CS_REMOTE,
2639 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002640 if (!error.ok()) {
2641 return error;
2642 }
2643
2644 if (local_description() &&
2645 !UseCandidatesInSessionDescription(remote_description())) {
2646 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2647 }
2648
2649 if (old_remote_description) {
2650 for (const cricket::ContentInfo& content :
2651 old_remote_description->description()->contents()) {
2652 // Check if this new SessionDescription contains new ICE ufrag and
2653 // password that indicates the remote peer requests an ICE restart.
2654 // TODO(deadbeef): When we start storing both the current and pending
2655 // remote description, this should reset pending_ice_restarts and compare
2656 // against the current description.
2657 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2658 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002659 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002660 pending_ice_restarts_.insert(content.name);
2661 }
2662 } else {
2663 // We retain all received candidates only if ICE is not restarted.
2664 // When ICE is restarted, all previous candidates belong to an old
2665 // generation and should not be kept.
2666 // TODO(deadbeef): This goes against the W3C spec which says the remote
2667 // description should only contain candidates from the last set remote
2668 // description plus any candidates added since then. We should remove
2669 // this once we're sure it won't break anything.
2670 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2671 old_remote_description, content.name, mutable_remote_description());
2672 }
2673 }
2674 }
2675
2676 if (session_error() != SessionError::kNone) {
2677 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2678 }
2679
2680 // Set the the ICE connection state to connecting since the connection may
2681 // become writable with peer reflexive candidates before any remote candidate
2682 // is signaled.
2683 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2684 // is to have a new signal the indicates a change in checking state from the
2685 // transport and expose a new checking() member from transport that can be
2686 // read to determine the current checking state. The existing SignalConnecting
2687 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002688 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002689 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002690 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2691 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2692 }
2693
deadbeefab9b2d12015-10-14 11:33:11 -07002694 // If setting the description decided our SSL role, allocate any necessary
2695 // SCTP sids.
2696 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002697 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002698 AllocateSctpSids(role);
2699 }
2700
Steve Antondcc3c022017-12-22 16:02:54 -08002701 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002702 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002703 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002704 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002705 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002706 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002707 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002708 const ContentInfo* content =
2709 FindMediaSectionForTransceiver(transceiver, remote_description());
2710 if (!content) {
2711 continue;
2712 }
2713 const MediaContentDescription* media_desc = content->media_description();
2714 RtpTransceiverDirection local_direction =
2715 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002716 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2717 // RTCSessionDescription: Set the associated remote streams given
2718 // transceiver.[[Receiver]], msids, addList, and removeList".
2719 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2720 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2721 std::vector<std::string> stream_ids;
2722 if (!media_desc->streams().empty()) {
2723 // The remote description has signaled the stream IDs.
2724 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002725 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002726 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2727 << " (" << GetStreamIdsString(stream_ids) << ").";
2728 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2729 stream_ids, &added_streams,
2730 &removed_streams);
2731 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2732 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2733 // and transceiver's current direction is neither sendrecv nor recvonly,
2734 // process the addition of a remote track for the media description.
2735 if (!transceiver->fired_direction() ||
2736 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2737 RTC_LOG(LS_INFO)
2738 << "Processing the addition of a remote track for MID="
2739 << content->name << ".";
2740 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002741 }
Steve Antondcc3c022017-12-22 16:02:54 -08002742 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002743 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002744 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2745 // removal of a remote track for the media description, given transceiver,
2746 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002747 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002748 (transceiver->fired_direction() &&
2749 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2750 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2751 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002752 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002753 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002754 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002755 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002756 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002757 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002758 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002759 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002760 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002761 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2762 if (transceiver->mid()) {
2763 auto dtls_transport =
2764 LookupDtlsTransportByMidInternal(*transceiver->mid());
2765 transceiver->internal()->sender_internal()->set_transport(
2766 dtls_transport);
2767 transceiver->internal()->receiver_internal()->set_transport(
2768 dtls_transport);
2769 }
Steve Antondcc3c022017-12-22 16:02:54 -08002770 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002771 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002772 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002773 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002774 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2775 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002776 transceiver->Stop();
2777 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002778 if (!content->rejected &&
2779 RtpTransceiverDirectionHasRecv(local_direction)) {
2780 // Set ssrc to 0 in the case of an unsignalled ssrc.
2781 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002782 if (!media_desc->streams().empty() &&
2783 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002784 ssrc = media_desc->streams()[0].first_ssrc();
2785 }
2786 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002787 }
Steve Antondcc3c022017-12-22 16:02:54 -08002788 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002789 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002790 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002791 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002792 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002793 observer->OnTrack(transceiver);
2794 observer->OnAddTrack(transceiver->receiver(),
2795 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002796 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002797 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002798 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002799 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002800 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002801 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002802 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002803 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002804 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002805 }
Steve Antondcc3c022017-12-22 16:02:54 -08002806 }
2807
Henrik Boströmfdb92012017-11-09 19:55:44 +01002808 const cricket::ContentInfo* audio_content =
2809 GetFirstAudioContent(remote_description()->description());
2810 const cricket::ContentInfo* video_content =
2811 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002812 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002813 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002814 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002815 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002816 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002817 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002818
2819 // Check if the descriptions include streams, just in case the peer supports
2820 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002821 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002822 (audio_desc && !audio_desc->streams().empty()) ||
2823 (video_desc && !video_desc->streams().empty())) {
2824 remote_peer_supports_msid_ = true;
2825 }
deadbeefab9b2d12015-10-14 11:33:11 -07002826
2827 // We wait to signal new streams until we finish processing the description,
2828 // since only at that point will new streams have all their tracks.
2829 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2830
Steve Antondcc3c022017-12-22 16:02:54 -08002831 if (!IsUnifiedPlan()) {
2832 // TODO(steveanton): When removing RTP senders/receivers in response to a
2833 // rejected media section, there is some cleanup logic that expects the
2834 // voice/ video channel to still be set. But in this method the voice/video
2835 // channel would have been destroyed by the SetRemoteDescription caller
2836 // above so the cleanup that relies on them fails to run. The RemoveSenders
2837 // calls should be moved to right before the DestroyChannel calls to fix
2838 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002839
Steve Antondcc3c022017-12-22 16:02:54 -08002840 // Find all audio rtp streams and create corresponding remote AudioTracks
2841 // and MediaStreams.
2842 if (audio_content) {
2843 if (audio_content->rejected) {
2844 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2845 } else {
2846 bool default_audio_track_needed =
2847 !remote_peer_supports_msid_ &&
2848 RtpTransceiverDirectionHasSend(audio_desc->direction());
2849 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2850 default_audio_track_needed, audio_desc->type(),
2851 new_streams);
2852 }
deadbeeffaac4972015-11-12 15:33:07 -08002853 }
deadbeefab9b2d12015-10-14 11:33:11 -07002854
Steve Antondcc3c022017-12-22 16:02:54 -08002855 // Find all video rtp streams and create corresponding remote VideoTracks
2856 // and MediaStreams.
2857 if (video_content) {
2858 if (video_content->rejected) {
2859 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2860 } else {
2861 bool default_video_track_needed =
2862 !remote_peer_supports_msid_ &&
2863 RtpTransceiverDirectionHasSend(video_desc->direction());
2864 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2865 default_video_track_needed, video_desc->type(),
2866 new_streams);
2867 }
deadbeeffaac4972015-11-12 15:33:07 -08002868 }
deadbeefab9b2d12015-10-14 11:33:11 -07002869
Steve Antondcc3c022017-12-22 16:02:54 -08002870 // Update the DataChannels with the information from the remote peer.
2871 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002872 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002873 cricket::kMediaProtocolRtpPrefix)) {
2874 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2875 }
deadbeefab9b2d12015-10-14 11:33:11 -07002876 }
deadbeefab9b2d12015-10-14 11:33:11 -07002877
Steve Antondcc3c022017-12-22 16:02:54 -08002878 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002879 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002880 for (size_t i = 0; i < new_streams->count(); ++i) {
2881 MediaStreamInterface* new_stream = new_streams->at(i);
2882 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002883 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002884 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2885 }
deadbeefab9b2d12015-10-14 11:33:11 -07002886
Steve Antondcc3c022017-12-22 16:02:54 -08002887 UpdateEndedRemoteMediaStreams();
2888 }
deadbeefab9b2d12015-10-14 11:33:11 -07002889
Steve Anton8a006912017-12-04 15:25:56 -08002890 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002891}
2892
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002893void PeerConnection::SetAssociatedRemoteStreams(
2894 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2895 const std::vector<std::string>& stream_ids,
2896 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2897 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2898 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2899 for (const std::string& stream_id : stream_ids) {
2900 rtc::scoped_refptr<MediaStreamInterface> stream =
2901 remote_streams_->find(stream_id);
2902 if (!stream) {
2903 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2904 MediaStream::Create(stream_id));
2905 remote_streams_->AddStream(stream);
2906 added_streams->push_back(stream);
2907 }
2908 media_streams.push_back(stream);
2909 }
2910 // Special case: "a=msid" missing, use random stream ID.
2911 if (media_streams.empty() &&
2912 !(remote_description()->description()->msid_signaling() &
2913 cricket::kMsidSignalingMediaSection)) {
2914 if (!missing_msid_default_stream_) {
2915 missing_msid_default_stream_ = MediaStreamProxy::Create(
2916 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2917 added_streams->push_back(missing_msid_default_stream_);
2918 }
2919 media_streams.push_back(missing_msid_default_stream_);
2920 }
2921 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2922 receiver->streams();
2923 // SetStreams() will add/remove the receiver's track to/from the streams. This
2924 // differs from the spec - the spec uses an "addList" and "removeList" to
2925 // update the stream-track relationships in a later step. We do this earlier,
2926 // changing the order of things, but the end-result is the same.
2927 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2928 // instead. https://crbug.com/webrtc/9480
2929 receiver->SetStreams(media_streams);
2930 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2931}
2932
Steve Anton0f5400a2018-07-17 14:25:36 -07002933void PeerConnection::ProcessRemovalOfRemoteTrack(
2934 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2935 transceiver,
2936 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2937 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2938 RTC_DCHECK(transceiver->mid());
2939 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2940 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002941 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002942 transceiver->internal()->receiver_internal()->streams();
2943 // This will remove the remote track from the streams.
2944 transceiver->internal()->receiver_internal()->set_stream_ids({});
2945 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002946 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2947}
2948
2949void PeerConnection::RemoveRemoteStreamsIfEmpty(
2950 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2951 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2952 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2953 // streams, see if the stream was removed by checking if this was the last
2954 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002955 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002956 if (remote_stream->GetAudioTracks().empty() &&
2957 remote_stream->GetVideoTracks().empty()) {
2958 remote_streams_->RemoveStream(remote_stream);
2959 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002960 }
2961 }
2962}
2963
Steve Antondcc3c022017-12-22 16:02:54 -08002964RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2965 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002966 const SessionDescriptionInterface& new_session,
2967 const SessionDescriptionInterface* old_local_description,
2968 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002969 RTC_DCHECK(IsUnifiedPlan());
2970
Steve Anton7464fca2018-01-19 11:10:37 -08002971 const cricket::ContentGroup* bundle_group = nullptr;
2972 if (new_session.GetType() == SdpType::kOffer) {
2973 auto bundle_group_or_error =
2974 GetEarlyBundleGroup(*new_session.description());
2975 if (!bundle_group_or_error.ok()) {
2976 return bundle_group_or_error.MoveError();
2977 }
2978 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002979 }
Steve Antondcc3c022017-12-22 16:02:54 -08002980
Steve Antondcc3c022017-12-22 16:02:54 -08002981 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002982 for (size_t i = 0; i < new_contents.size(); ++i) {
2983 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002984 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002985 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002986 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2987 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002988 const cricket::ContentInfo* old_local_content = nullptr;
2989 if (old_local_description &&
2990 i < old_local_description->description()->contents().size()) {
2991 old_local_content =
2992 &old_local_description->description()->contents()[i];
2993 }
2994 const cricket::ContentInfo* old_remote_content = nullptr;
2995 if (old_remote_description &&
2996 i < old_remote_description->description()->contents().size()) {
2997 old_remote_content =
2998 &old_remote_description->description()->contents()[i];
2999 }
Steve Antondcc3c022017-12-22 16:02:54 -08003000 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003001 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3002 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003003 if (!transceiver_or_error.ok()) {
3004 return transceiver_or_error.MoveError();
3005 }
3006 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003007 RTCError error =
3008 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3009 if (!error.ok()) {
3010 return error;
3011 }
3012 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003013 if (GetDataMid() && new_content.name != *GetDataMid()) {
3014 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003015 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3016 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003017 continue;
3018 }
3019 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3020 if (!error.ok()) {
3021 return error;
3022 }
Steve Antondcc3c022017-12-22 16:02:54 -08003023 } else {
3024 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3025 "Unknown section type.");
3026 }
3027 }
3028
3029 return RTCError::OK();
3030}
3031
3032RTCError PeerConnection::UpdateTransceiverChannel(
3033 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3034 transceiver,
3035 const cricket::ContentInfo& content,
3036 const cricket::ContentGroup* bundle_group) {
3037 RTC_DCHECK(IsUnifiedPlan());
3038 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003039 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003040 if (content.rejected) {
3041 if (channel) {
3042 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003043 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003044 }
3045 } else {
3046 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003047 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003048 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003049 } else {
Steve Anton69470252018-02-09 11:43:08 -08003050 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003051 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003052 }
3053 if (!channel) {
3054 LOG_AND_RETURN_ERROR(
3055 RTCErrorType::INTERNAL_ERROR,
3056 "Failed to create channel for mid=" + content.name);
3057 }
3058 transceiver->internal()->SetChannel(channel);
3059 }
3060 }
3061 return RTCError::OK();
3062}
3063
Steve Antonfa2260d2017-12-28 16:38:23 -08003064RTCError PeerConnection::UpdateDataChannel(
3065 cricket::ContentSource source,
3066 const cricket::ContentInfo& content,
3067 const cricket::ContentGroup* bundle_group) {
3068 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003069 // If data channels are disabled, ignore this media section. CreateAnswer
3070 // will take care of rejecting it.
3071 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003072 }
3073 if (content.rejected) {
3074 DestroyDataChannel();
3075 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003076 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003077 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003078 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3079 "Failed to create data channel.");
3080 }
3081 }
3082 if (source == cricket::CS_REMOTE) {
3083 const MediaContentDescription* data_desc = content.media_description();
3084 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3085 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3086 }
3087 }
3088 }
3089 return RTCError::OK();
3090}
3091
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003092// This method will extract any send encodings that were sent by the remote
3093// connection. This is currently only relevant for Simulcast scenario (where
3094// the number of layers may be communicated by the server).
3095static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3096 const MediaContentDescription& desc) {
3097 if (!desc.HasSimulcast()) {
3098 return {};
3099 }
3100 std::vector<RtpEncodingParameters> result;
3101 const SimulcastDescription& simulcast = desc.simulcast_description();
3102
3103 // This is a remote description, the parameters we are after should appear
3104 // as receive streams.
3105 for (const auto& alternatives : simulcast.receive_layers()) {
3106 RTC_DCHECK(!alternatives.empty());
3107 // There is currently no way to specify or choose from alternatives.
3108 // We will always use the first alternative, which is the most preferred.
3109 const SimulcastLayer& layer = alternatives[0];
3110 RtpEncodingParameters parameters;
3111 parameters.rid = layer.rid;
3112 parameters.active = !layer.is_paused;
3113 result.push_back(parameters);
3114 }
3115
3116 return result;
3117}
3118
3119static RTCError UpdateSimulcastLayerStatusInSender(
3120 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003121 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003122 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003123 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003124 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003125
3126 // The simulcast envelope cannot be changed, only the status of the streams.
3127 // So we will iterate over the send encodings rather than the layers.
3128 for (RtpEncodingParameters& encoding : parameters.encodings) {
3129 auto iter = std::find_if(layers.begin(), layers.end(),
3130 [&encoding](const SimulcastLayer& layer) {
3131 return layer.rid == encoding.rid;
3132 });
3133 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003134 if (iter == layers.end()) {
3135 disabled_layers.push_back(encoding.rid);
3136 continue;
3137 }
3138
3139 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003140 }
3141
Amit Hilbuch619b2942019-02-26 15:55:19 -08003142 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003143 if (result.ok()) {
3144 result = sender->DisableEncodingLayers(disabled_layers);
3145 }
3146
3147 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003148}
3149
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003150static bool SimulcastIsRejected(
3151 const ContentInfo* local_content,
3152 const MediaContentDescription& answer_media_desc) {
3153 bool simulcast_offered = local_content &&
3154 local_content->media_description() &&
3155 local_content->media_description()->HasSimulcast();
3156 bool simulcast_answered = answer_media_desc.HasSimulcast();
3157 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3158 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3159 return simulcast_offered && (!simulcast_answered || !rids_supported);
3160}
3161
Amit Hilbuch2297d332019-02-19 12:49:22 -08003162static RTCError DisableSimulcastInSender(
3163 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003164 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003165 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003166 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003167 return RTCError::OK();
3168 }
3169
Amit Hilbuch2297d332019-02-19 12:49:22 -08003170 std::vector<std::string> disabled_layers;
3171 std::transform(
3172 parameters.encodings.begin() + 1, parameters.encodings.end(),
3173 std::back_inserter(disabled_layers),
3174 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3175 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003176}
3177
Steve Antondcc3c022017-12-22 16:02:54 -08003178RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3179PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003180 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003181 size_t mline_index,
3182 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003183 const ContentInfo* old_local_content,
3184 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003185 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003186 // If this is an offer then the m= section might be recycled. If the m=
3187 // section is being recycled (defined as: rejected in the current local or
3188 // remote description and not rejected in new description), dissociate the
3189 // currently associated RtpTransceiver by setting its mid property to null,
3190 // and discard the mapping between the transceiver and its m= section index.
3191 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3192 old_remote_content)) {
3193 // We want to dissociate the transceiver that has the rejected mid.
3194 const std::string& old_mid =
3195 (old_local_content && old_local_content->rejected)
3196 ? old_local_content->name
3197 : old_remote_content->name;
3198 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003199 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003200 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3201 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003202 old_transceiver->internal()->set_mid(absl::nullopt);
3203 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003204 }
3205 }
3206 const MediaContentDescription* media_desc = content.media_description();
3207 auto transceiver = GetAssociatedTransceiver(content.name);
3208 if (source == cricket::CS_LOCAL) {
3209 // Find the RtpTransceiver that corresponds to this m= section, using the
3210 // mapping between transceivers and m= section indices established when
3211 // creating the offer.
3212 if (!transceiver) {
3213 transceiver = GetTransceiverByMLineIndex(mline_index);
3214 }
3215 if (!transceiver) {
3216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3217 "Unknown transceiver");
3218 }
3219 } else {
3220 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3221 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3222 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003223 // When simulcast is requested, a transceiver cannot be associated because
3224 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003225 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003226 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3227 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003228 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3229 }
3230 // If no RtpTransceiver was found in the previous step, create one with a
3231 // recvonly direction.
3232 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003233 RTC_LOG(LS_INFO) << "Adding "
3234 << cricket::MediaTypeToString(media_desc->type())
3235 << " transceiver for MID=" << content.name
3236 << " at i=" << mline_index
3237 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003238 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003239 std::vector<RtpEncodingParameters> send_encodings =
3240 GetSendEncodingsFromRemoteDescription(*media_desc);
3241 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3242 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003243 std::string receiver_id;
3244 if (!media_desc->streams().empty()) {
3245 receiver_id = media_desc->streams()[0].id;
3246 } else {
3247 receiver_id = rtc::CreateRandomUuid();
3248 }
3249 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003250 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003251 transceiver->internal()->set_direction(
3252 RtpTransceiverDirection::kRecvOnly);
3253 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003254
3255 // Check if the offer indicated simulcast but the answer rejected it.
3256 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003257 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003258 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003259 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003260 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003261 if (!error.ok()) {
3262 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3263 return std::move(error);
3264 }
3265 }
Steve Antondcc3c022017-12-22 16:02:54 -08003266 }
3267 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003268 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003269 LOG_AND_RETURN_ERROR(
3270 RTCErrorType::INVALID_PARAMETER,
3271 "Transceiver type does not match media description type.");
3272 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003273 if (media_desc->HasSimulcast()) {
3274 std::vector<SimulcastLayer> layers =
3275 source == cricket::CS_LOCAL
3276 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3277 : media_desc->simulcast_description()
3278 .receive_layers()
3279 .GetAllLayers();
3280 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003281 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003282 if (!error.ok()) {
3283 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3284 return std::move(error);
3285 }
3286 }
Steve Antondcc3c022017-12-22 16:02:54 -08003287 // Associate the found or created RtpTransceiver with the m= section by
3288 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3289 // section, and establish a mapping between the transceiver and the index of
3290 // the m= section.
3291 transceiver->internal()->set_mid(content.name);
3292 transceiver->internal()->set_mline_index(mline_index);
3293 return std::move(transceiver);
3294}
3295
3296rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3297PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3298 RTC_DCHECK(IsUnifiedPlan());
3299 for (auto transceiver : transceivers_) {
3300 if (transceiver->mid() == mid) {
3301 return transceiver;
3302 }
3303 }
3304 return nullptr;
3305}
3306
3307rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3308PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3309 RTC_DCHECK(IsUnifiedPlan());
3310 for (auto transceiver : transceivers_) {
3311 if (transceiver->internal()->mline_index() == mline_index) {
3312 return transceiver;
3313 }
3314 }
3315 return nullptr;
3316}
3317
3318rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3319PeerConnection::FindAvailableTransceiverToReceive(
3320 cricket::MediaType media_type) const {
3321 RTC_DCHECK(IsUnifiedPlan());
3322 // From JSEP section 5.10 (Applying a Remote Description):
3323 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3324 // the same type that were added to the PeerConnection by addTrack and are not
3325 // associated with any m= section and are not stopped, find the first such
3326 // RtpTransceiver.
3327 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003328 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003329 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3330 !transceiver->stopped()) {
3331 return transceiver;
3332 }
3333 }
3334 return nullptr;
3335}
3336
Steve Antoned10bd92017-12-05 10:52:59 -08003337const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3338 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3339 transceiver,
3340 const SessionDescriptionInterface* sdesc) const {
3341 RTC_DCHECK(transceiver);
3342 RTC_DCHECK(sdesc);
3343 if (IsUnifiedPlan()) {
3344 if (!transceiver->internal()->mid()) {
3345 // This transceiver is not associated with a media section yet.
3346 return nullptr;
3347 }
3348 return sdesc->description()->GetContentByName(
3349 *transceiver->internal()->mid());
3350 } else {
3351 // Plan B only allows at most one audio and one video section, so use the
3352 // first media section of that type.
3353 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003354 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003355 }
3356}
3357
deadbeef46c73892016-11-16 19:42:04 -08003358PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003359 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003360 return configuration_;
3361}
3362
deadbeef293e9262017-01-11 12:28:30 -08003363bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3364 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003365 RTC_DCHECK_RUN_ON(signaling_thread());
3366 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003367 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003368 if (IsClosed()) {
3369 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3370 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3371 }
3372
Qingsi Wanga2d60672018-04-11 16:57:45 -07003373 // According to JSEP, after setLocalDescription, changing the candidate pool
3374 // size is not allowed, and changing the set of ICE servers will not result
3375 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003376 if (local_description() && configuration.ice_candidate_pool_size !=
3377 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003378 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3379 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003380 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003381 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003382
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003383 if (local_description() &&
3384 configuration.use_media_transport != configuration_.use_media_transport) {
3385 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3386 "SetLocalDescription.";
3387 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3388 }
3389
3390 if (remote_description() &&
3391 configuration.use_media_transport != configuration_.use_media_transport) {
3392 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3393 "SetRemoteDescription.";
3394 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3395 }
3396
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003397 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003398 configuration.use_media_transport_for_data_channels !=
3399 configuration_.use_media_transport_for_data_channels) {
3400 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3401 "after calling SetLocalDescription.";
3402 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3403 }
3404
3405 if (remote_description() &&
3406 configuration.use_media_transport_for_data_channels !=
3407 configuration_.use_media_transport_for_data_channels) {
3408 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3409 "after calling SetRemoteDescription.";
3410 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3411 }
3412
3413 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003414 configuration.crypto_options != configuration_.crypto_options) {
3415 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3416 "SetLocalDescription.";
3417 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3418 }
3419
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003420 if (configuration.use_media_transport_for_data_channels ||
3421 configuration.use_media_transport) {
3422 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3423 << "Media transport requires MaxBundle policy.";
3424 }
3425
deadbeef293e9262017-01-11 12:28:30 -08003426 // The simplest (and most future-compatible) way to tell if the config was
3427 // modified in an invalid way is to copy each property we do support
3428 // modifying, then use operator==. There are far more properties we don't
3429 // support modifying than those we do, and more could be added.
3430 RTCConfiguration modified_config = configuration_;
3431 modified_config.servers = configuration.servers;
3432 modified_config.type = configuration.type;
3433 modified_config.ice_candidate_pool_size =
3434 configuration.ice_candidate_pool_size;
3435 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003436 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003437 modified_config.ice_check_interval_strong_connectivity =
3438 configuration.ice_check_interval_strong_connectivity;
3439 modified_config.ice_check_interval_weak_connectivity =
3440 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003441 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3442 modified_config.ice_unwritable_min_checks =
3443 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003444 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003445 modified_config.stun_candidate_keepalive_interval =
3446 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003447 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003448 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003449 modified_config.active_reset_srtp_params =
3450 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003451 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003452 modified_config.use_media_transport_for_data_channels =
3453 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003454 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003455 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003456 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3457 }
3458
Steve Anton038834f2017-07-14 15:59:59 -07003459 // Validate the modified configuration.
3460 RTCError validate_error = ValidateConfiguration(modified_config);
3461 if (!validate_error.ok()) {
3462 return SafeSetError(std::move(validate_error), error);
3463 }
3464
deadbeef293e9262017-01-11 12:28:30 -08003465 // Note that this isn't possible through chromium, since it's an unsigned
3466 // short in WebIDL.
3467 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003468 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003469 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3470 }
3471
3472 // Parse ICE servers before hopping to network thread.
3473 cricket::ServerAddresses stun_servers;
3474 std::vector<cricket::RelayServerConfig> turn_servers;
3475 RTCErrorType parse_error =
3476 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3477 if (parse_error != RTCErrorType::NONE) {
3478 return SafeSetError(parse_error, error);
3479 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003480 // Note if STUN or TURN servers were supplied.
3481 if (!stun_servers.empty()) {
3482 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3483 }
3484 if (!turn_servers.empty()) {
3485 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3486 }
deadbeef293e9262017-01-11 12:28:30 -08003487
3488 // In theory this shouldn't fail.
3489 if (!network_thread()->Invoke<bool>(
3490 RTC_FROM_HERE,
3491 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3492 stun_servers, turn_servers, modified_config.type,
3493 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003494 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003495 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003496 modified_config.stun_candidate_keepalive_interval,
3497 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003498 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003499 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3500 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003501
deadbeefd1a38b52016-12-10 13:15:33 -08003502 // As described in JSEP, calling setConfiguration with new ICE servers or
3503 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3504 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003505 if (modified_config.servers != configuration_.servers ||
3506 modified_config.type != configuration_.type ||
3507 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003508 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003509 }
skvladd1f5fda2017-02-03 16:54:05 -08003510
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003511 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003512 transport_controller_->SetMediaTransportSettings(
3513 modified_config.use_media_transport,
3514 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003515
Zhi Huangb57e1692018-06-12 11:41:11 -07003516 if (configuration_.active_reset_srtp_params !=
3517 modified_config.active_reset_srtp_params) {
3518 transport_controller_->SetActiveResetSrtpParams(
3519 modified_config.active_reset_srtp_params);
3520 }
3521
deadbeef293e9262017-01-11 12:28:30 -08003522 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003523 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003524 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003525}
3526
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003527bool PeerConnection::AddIceCandidate(
3528 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003529 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003530 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003531 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003532 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003533 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003534 return false;
3535 }
Steve Antond25da372017-11-06 14:50:29 -08003536
3537 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003538 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003539 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003540 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003541 return false;
3542 }
3543
3544 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003545 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003546 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003547 return false;
3548 }
3549
3550 bool valid = false;
3551 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3552 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003553 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003554 return false;
3555 }
3556
3557 // Add this candidate to the remote session description.
3558 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003559 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003560 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003561 return false;
3562 }
3563
3564 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003565 bool result = UseCandidate(ice_candidate);
3566 if (result) {
3567 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3568 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3569 } else {
3570 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3571 }
3572 return result;
Steve Antond25da372017-11-06 14:50:29 -08003573 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003574 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003575 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003576 return true;
3577 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003578}
3579
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003580bool PeerConnection::RemoveIceCandidates(
3581 const std::vector<cricket::Candidate>& candidates) {
3582 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003583 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003584 if (IsClosed()) {
3585 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3586 return false;
3587 }
3588
Steve Antond25da372017-11-06 14:50:29 -08003589 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003590 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3591 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003592 return false;
3593 }
3594
3595 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003596 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003597 return false;
3598 }
3599
3600 size_t number_removed =
3601 mutable_remote_description()->RemoveCandidates(candidates);
3602 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003603 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003604 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003605 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003606 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003607 }
3608
3609 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003610 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3611 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003612 RTC_LOG(LS_ERROR)
3613 << "RemoveIceCandidates: Error when removing remote candidates: "
3614 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003615 }
3616 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003617}
3618
Niels Möller0c4f7be2018-05-07 14:01:37 +02003619RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003620 if (!worker_thread()->IsCurrent()) {
3621 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003622 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003623 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003624 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003625
Niels Möller0c4f7be2018-05-07 14:01:37 +02003626 const bool has_min = bitrate.min_bitrate_bps.has_value();
3627 const bool has_start = bitrate.start_bitrate_bps.has_value();
3628 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003629 if (has_min && *bitrate.min_bitrate_bps < 0) {
3630 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3631 "min_bitrate_bps <= 0");
3632 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003633 if (has_start) {
3634 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003635 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003636 "start_bitrate_bps < min_bitrate_bps");
3637 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003638 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3639 "curent_bitrate_bps < 0");
3640 }
3641 }
3642 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003643 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003644 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003645 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003646 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3648 "max_bitrate_bps < min_bitrate_bps");
3649 } else if (*bitrate.max_bitrate_bps < 0) {
3650 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3651 "max_bitrate_bps < 0");
3652 }
3653 }
3654
zstein4b979802017-06-02 14:37:37 -07003655 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003656 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003657
3658 return RTCError::OK();
3659}
3660
Alex Narest78609d52017-10-20 10:37:47 +02003661void PeerConnection::SetBitrateAllocationStrategy(
3662 std::unique_ptr<rtc::BitrateAllocationStrategy>
3663 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003664 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003665 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3666 // move-capture values in lambdas.
3667 struct Task {
3668 PeerConnection* const pc;
3669 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3670 void operator()() {
3671 RTC_DCHECK_RUN_ON(pc->worker_thread());
3672 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3673 }
3674 };
3675 worker_thread()->Invoke<void>(
3676 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003677 return;
3678 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003679 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003680 RTC_DCHECK(call_.get());
3681 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3682}
3683
henrika5f6bf242017-11-01 11:06:56 +01003684void PeerConnection::SetAudioPlayout(bool playout) {
3685 if (!worker_thread()->IsCurrent()) {
3686 worker_thread()->Invoke<void>(
3687 RTC_FROM_HERE,
3688 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3689 return;
3690 }
3691 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003692 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003693 audio_state->SetPlayout(playout);
3694}
3695
3696void PeerConnection::SetAudioRecording(bool recording) {
3697 if (!worker_thread()->IsCurrent()) {
3698 worker_thread()->Invoke<void>(
3699 RTC_FROM_HERE,
3700 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3701 return;
3702 }
3703 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003704 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003705 audio_state->SetRecording(recording);
3706}
3707
Steve Anton8c0f7a72017-10-03 10:03:10 -07003708std::unique_ptr<rtc::SSLCertificate>
3709PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003710 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3711 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003712 return nullptr;
3713 }
Steve Antonf25303e2018-10-16 15:23:31 -07003714 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003715}
3716
Zhi Huang70b820f2018-01-27 14:16:15 -08003717std::unique_ptr<rtc::SSLCertChain>
3718PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003719 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003720 auto audio_transceiver = GetFirstAudioTransceiver();
3721 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003722 return nullptr;
3723 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003724 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003725 audio_transceiver->internal()->channel()->transport_name());
3726}
3727
3728rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3729PeerConnection::GetFirstAudioTransceiver() const {
3730 for (auto transceiver : transceivers_) {
3731 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3732 return transceiver;
3733 }
3734 }
3735 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003736}
3737
ivoc14d5dbe2016-07-04 07:06:55 -07003738bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3739 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003740 // TODO(eladalon): It would be better to not allow negative values into PC.
3741 const size_t max_size = (max_size_bytes < 0)
3742 ? RtcEventLog::kUnlimitedOutput
3743 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003744 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3745 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3746 output_period_ms = 5000;
3747 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003748 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003749 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003750 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003751}
3752
Bjorn Tereliusde939432017-11-20 17:38:14 +01003753bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3754 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003755 // TODO(eladalon): In C++14, this can be done with a lambda.
3756 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003757 bool operator()() {
3758 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3759 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003760 PeerConnection* const pc;
3761 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003762 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003763 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003764 return worker_thread()->Invoke<bool>(
3765 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003766}
3767
3768void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003769 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003770 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3771}
3772
Harald Alvestrandad88c882018-11-28 16:47:46 +01003773rtc::scoped_refptr<DtlsTransportInterface>
3774PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003775 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003776 return transport_controller_->LookupDtlsTransportByMid(mid);
3777}
3778
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003779rtc::scoped_refptr<DtlsTransport>
3780PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003781 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003782 return transport_controller_->LookupDtlsTransportByMid(mid);
3783}
3784
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003785rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3786 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003787 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003788 return sctp_transport_;
3789}
3790
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003791const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003792 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003793 return pending_local_description_ ? pending_local_description_.get()
3794 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003795}
3796
3797const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003798 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003799 return pending_remote_description_ ? pending_remote_description_.get()
3800 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003801}
3802
deadbeeffe4a8a42016-12-20 17:56:17 -08003803const SessionDescriptionInterface* PeerConnection::current_local_description()
3804 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003805 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003806 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003807}
3808
3809const SessionDescriptionInterface* PeerConnection::current_remote_description()
3810 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003811 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003812 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003813}
3814
3815const SessionDescriptionInterface* PeerConnection::pending_local_description()
3816 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003817 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003818 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003819}
3820
3821const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3822 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003823 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003824 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003825}
3826
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003827void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003828 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003829 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003830 // Update stats here so that we have the most recent stats for tracks and
3831 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003832 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003833
Steve Anton75737c02017-11-06 10:37:17 -08003834 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003835 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003836
Mirko Bonadei739baf02019-01-27 17:29:42 +01003837 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003838 transceiver->Stop();
3839 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003840
3841 // Ensure that all asynchronous stats requests are completed before destroying
3842 // the transport controller below.
3843 if (stats_collector_) {
3844 stats_collector_->WaitForPendingRequest();
3845 }
3846
3847 // Don't destroy BaseChannels until after stats has been cleaned up so that
3848 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003849 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003850
Qingsi Wang93a84392018-01-30 17:13:09 -08003851 // The event log is used in the transport controller, which must be outlived
3852 // by the former. CreateOffer by the peer connection is implemented
3853 // asynchronously and if the peer connection is closed without resetting the
3854 // WebRTC session description factory, the session description factory would
3855 // call the transport controller.
3856 webrtc_session_desc_factory_.reset();
3857 transport_controller_.reset();
3858
deadbeef42a42632017-03-10 15:18:00 -08003859 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003860 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3861 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003862
Steve Anton978b8762017-09-29 12:15:02 -07003863 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003864 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003865 call_.reset();
3866 // The event log must outlive call (and any other object that uses it).
3867 event_log_.reset();
3868 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003869 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003870 // The .h file says that observer can be discarded after close() returns.
3871 // Make sure this is true.
3872 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003873}
3874
Steve Antonad182762018-09-05 20:22:40 +00003875void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003876 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003877 switch (msg->message_id) {
3878 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3879 SetSessionDescriptionMsg* param =
3880 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3881 param->observer->OnSuccess();
3882 delete param;
3883 break;
3884 }
3885 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3886 SetSessionDescriptionMsg* param =
3887 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3888 param->observer->OnFailure(std::move(param->error));
3889 delete param;
3890 break;
3891 }
3892 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3893 CreateSessionDescriptionMsg* param =
3894 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3895 param->observer->OnFailure(std::move(param->error));
3896 delete param;
3897 break;
3898 }
3899 case MSG_GETSTATS: {
3900 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3901 StatsReports reports;
3902 stats_->GetStats(param->track, &reports);
3903 param->observer->OnComplete(reports);
3904 delete param;
3905 break;
3906 }
3907 case MSG_FREE_DATACHANNELS: {
3908 sctp_data_channels_to_free_.clear();
3909 break;
3910 }
3911 case MSG_REPORT_USAGE_PATTERN: {
3912 ReportUsagePattern();
3913 break;
3914 }
3915 default:
3916 RTC_NOTREACHED() << "Not implemented";
3917 break;
3918 }
3919}
3920
Steve Antonafb0bb72018-02-20 11:35:37 -08003921cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3922 RTC_DCHECK(!IsUnifiedPlan());
3923 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3924 GetAudioTransceiver()->internal()->channel());
3925 if (voice_channel) {
3926 return voice_channel->media_channel();
3927 } else {
3928 return nullptr;
3929 }
3930}
3931
3932cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3933 RTC_DCHECK(!IsUnifiedPlan());
3934 auto* video_channel = static_cast<cricket::VideoChannel*>(
3935 GetVideoTransceiver()->internal()->channel());
3936 if (video_channel) {
3937 return video_channel->media_channel();
3938 } else {
3939 return nullptr;
3940 }
3941}
3942
Steve Anton4171afb2017-11-20 10:20:22 -08003943void PeerConnection::CreateAudioReceiver(
3944 MediaStreamInterface* stream,
3945 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003946 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3947 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003948 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3949 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003950 auto* audio_receiver = new AudioRtpReceiver(
3951 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003952 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003953 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3954 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3955 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003956 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003957 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003958 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003959}
3960
Steve Anton4171afb2017-11-20 10:20:22 -08003961void PeerConnection::CreateVideoReceiver(
3962 MediaStreamInterface* stream,
3963 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003964 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3965 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003966 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3967 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003968 auto* video_receiver = new VideoRtpReceiver(
3969 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003970 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003971 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3972 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3973 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003974 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003975 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003976 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003977}
3978
deadbeef70ab1a12015-09-28 16:53:55 -07003979// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3980// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003981rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003982 const RtpSenderInfo& remote_sender_info) {
3983 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3984 if (!receiver) {
3985 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3986 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003987 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003988 }
Steve Anton4171afb2017-11-20 10:20:22 -08003989 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3990 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3991 } else {
3992 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3993 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003994 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003995}
3996
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003997void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3998 MediaStreamInterface* stream) {
3999 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004000 RTC_DCHECK(track);
4001 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004002 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004003 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004004 // We already have a sender for this track, so just change the stream_id
4005 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004006 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004007 return;
4008 }
4009
4010 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004011 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004012 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004013 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004014 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004015 // If the sender has already been configured in SDP, we call SetSsrc,
4016 // which will connect the sender to the underlying transport. This can
4017 // occur if a local session description that contains the ID of the sender
4018 // is set before AddStream is called. It can also occur if the local
4019 // session description is not changed and RemoveStream is called, and
4020 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004021 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004022 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004023 if (sender_info) {
4024 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004025 }
4026}
4027
4028// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4029// indefinitely, when we have unified plan SDP.
4030void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4031 MediaStreamInterface* stream) {
4032 RTC_DCHECK(!IsClosed());
4033 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004034 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004035 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4036 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004037 return;
4038 }
Steve Anton4171afb2017-11-20 10:20:22 -08004039 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004040}
4041
4042void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4043 MediaStreamInterface* stream) {
4044 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004045 RTC_DCHECK(track);
4046 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004047 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004048 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004049 // We already have a sender for this track, so just change the stream_id
4050 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004051 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004052 return;
4053 }
4054
4055 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004056 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004057 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004058 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004059 GetVideoTransceiver()->internal()->AddSender(new_sender);
4060 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004061 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004062 if (sender_info) {
4063 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004064 }
4065}
4066
4067void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4068 MediaStreamInterface* stream) {
4069 RTC_DCHECK(!IsClosed());
4070 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004071 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004072 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4073 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004074 return;
4075 }
Steve Anton4171afb2017-11-20 10:20:22 -08004076 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004077}
4078
Steve Antonba818672017-11-06 10:21:57 -08004079void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004080 if (ice_connection_state_ == new_state) {
4081 return;
4082 }
4083
deadbeefcbecd352015-09-23 11:50:27 -07004084 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004085 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004086 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004087 return;
4088 }
Steve Antonba818672017-11-06 10:21:57 -08004089
Mirko Bonadei675513b2017-11-09 11:09:25 +01004090 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4091 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004092 RTC_DCHECK(ice_connection_state_ !=
4093 PeerConnectionInterface::kIceConnectionClosed);
4094
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004095 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004096 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004097}
4098
Alex Loiko9289eda2018-11-23 16:18:59 +00004099void PeerConnection::SetStandardizedIceConnectionState(
4100 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004101 if (standardized_ice_connection_state_ == new_state)
4102 return;
4103 if (IsClosed())
4104 return;
4105 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004106 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004107}
4108
Jonas Olsson635474e2018-10-18 15:58:17 +02004109void PeerConnection::SetConnectionState(
4110 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004111 if (connection_state_ == new_state)
4112 return;
4113 if (IsClosed())
4114 return;
4115 connection_state_ = new_state;
4116 Observer()->OnConnectionChange(new_state);
4117}
4118
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004119void PeerConnection::OnIceGatheringChange(
4120 PeerConnectionInterface::IceGatheringState new_state) {
4121 if (IsClosed()) {
4122 return;
4123 }
4124 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004125 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004126}
4127
jbauch81bf7b02017-03-25 08:31:12 -07004128void PeerConnection::OnIceCandidate(
4129 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004130 if (IsClosed()) {
4131 return;
4132 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004133 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004134 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4135 candidate->candidate().address().IsPrivateIP()) {
4136 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4137 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004138 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004139}
4140
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004141void PeerConnection::OnIceCandidatesRemoved(
4142 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004143 if (IsClosed()) {
4144 return;
4145 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004146 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004147}
4148
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004149void PeerConnection::ChangeSignalingState(
4150 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004151 if (signaling_state_ == signaling_state) {
4152 return;
4153 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004154 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4155 << GetSignalingStateString(signaling_state_)
4156 << " New state: "
4157 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004158 signaling_state_ = signaling_state;
4159 if (signaling_state == kClosed) {
4160 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004161 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004162 standardized_ice_connection_state_ =
4163 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004164 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4165 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004166 if (ice_gathering_state_ != kIceGatheringComplete) {
4167 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004168 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004169 }
4170 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004171 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004172}
4173
deadbeefeb459812015-12-15 19:24:43 -08004174void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4175 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004176 if (IsClosed()) {
4177 return;
4178 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004179 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004180 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004181}
4182
deadbeefeb459812015-12-15 19:24:43 -08004183void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4184 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004185 if (IsClosed()) {
4186 return;
4187 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004188 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004189 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004190}
4191
4192void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4193 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004194 if (IsClosed()) {
4195 return;
4196 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004197 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004198 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004199}
4200
4201void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4202 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004203 if (IsClosed()) {
4204 return;
4205 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004206 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004207 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004208}
4209
Henrik Boström31638672017-11-23 17:48:32 +01004210void PeerConnection::PostSetSessionDescriptionSuccess(
4211 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004212 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4213 signaling_thread()->Post(RTC_FROM_HERE, this,
4214 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004215}
4216
deadbeefab9b2d12015-10-14 11:33:11 -07004217void PeerConnection::PostSetSessionDescriptionFailure(
4218 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004219 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004220 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004221 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4222 msg->error = std::move(error);
4223 signaling_thread()->Post(RTC_FROM_HERE, this,
4224 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004225}
4226
4227void PeerConnection::PostCreateSessionDescriptionFailure(
4228 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004229 RTCError error) {
4230 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004231 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4232 msg->error = std::move(error);
4233 signaling_thread()->Post(RTC_FROM_HERE, this,
4234 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004235}
4236
zhihuang1c378ed2017-08-17 14:10:50 -07004237void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004238 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004239 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004240 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004241
Steve Antondcc3c022017-12-22 16:02:54 -08004242 if (IsUnifiedPlan()) {
4243 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4244 } else {
4245 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4246 }
4247
Steve Antonfa2260d2017-12-28 16:38:23 -08004248 // Intentionally unset the data channel type for RTP data channel with the
4249 // second condition. Otherwise the RTP data channels would be successfully
4250 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4251 // when building with chromium. We want to leave RTP data channels broken, so
4252 // people won't try to use them.
4253 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4254 session_options->data_channel_type = data_channel_type();
4255 }
4256
Steve Antondcc3c022017-12-22 16:02:54 -08004257 // Apply ICE restart flag and renomination flag.
4258 for (auto& options : session_options->media_description_options) {
4259 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4260 options.transport_options.enable_ice_renomination =
4261 configuration_.enable_ice_renomination;
4262 }
4263
4264 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004265 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004266 session_options->pooled_ice_credentials =
4267 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4268 RTC_FROM_HERE,
4269 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4270 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004271 session_options->offer_extmap_allow_mixed =
4272 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004273
4274 if (configuration_.enable_dtls_srtp &&
4275 !configuration_.enable_dtls_srtp.value()) {
4276 session_options->media_transport_settings =
4277 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4278 }
Steve Antondcc3c022017-12-22 16:02:54 -08004279}
4280
4281void PeerConnection::GetOptionsForPlanBOffer(
4282 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4283 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004284 // Figure out transceiver directional preferences.
4285 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4286 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4287
4288 // By default, generate sendrecv/recvonly m= sections.
4289 bool recv_audio = true;
4290 bool recv_video = true;
4291
4292 // By default, only offer a new m= section if we have media to send with it.
4293 bool offer_new_audio_description = send_audio;
4294 bool offer_new_video_description = send_video;
4295 bool offer_new_data_description = HasDataChannels();
4296
4297 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004298 if (offer_answer_options.offer_to_receive_audio !=
4299 RTCOfferAnswerOptions::kUndefined) {
4300 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004301 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004302 offer_new_audio_description ||
4303 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004304 }
Steve Antondcc3c022017-12-22 16:02:54 -08004305 if (offer_answer_options.offer_to_receive_video !=
4306 RTCOfferAnswerOptions::kUndefined) {
4307 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004308 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004309 offer_new_video_description ||
4310 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004311 }
4312
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004313 absl::optional<size_t> audio_index;
4314 absl::optional<size_t> video_index;
4315 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004316 // If a current description exists, generate m= sections in the same order,
4317 // using the first audio/video/data section that appears and rejecting
4318 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004319 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004320 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004321 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004322 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4323 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4324 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004325 }
4326
zhihuang1c378ed2017-08-17 14:10:50 -07004327 // Add audio/video/data m= sections to the end if needed.
4328 if (!audio_index && offer_new_audio_description) {
4329 session_options->media_description_options.push_back(
4330 cricket::MediaDescriptionOptions(
4331 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004332 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4333 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004334 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004335 }
zhihuang1c378ed2017-08-17 14:10:50 -07004336 if (!video_index && offer_new_video_description) {
4337 session_options->media_description_options.push_back(
4338 cricket::MediaDescriptionOptions(
4339 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004340 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4341 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004342 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004343 }
zhihuang1c378ed2017-08-17 14:10:50 -07004344 if (!data_index && offer_new_data_description) {
4345 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004346 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004347 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004348 }
4349
4350 cricket::MediaDescriptionOptions* audio_media_description_options =
4351 !audio_index ? nullptr
4352 : &session_options->media_description_options[*audio_index];
4353 cricket::MediaDescriptionOptions* video_media_description_options =
4354 !video_index ? nullptr
4355 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004356
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004357 AddPlanBRtpSenderOptions(GetSendersInternal(),
4358 audio_media_description_options,
4359 video_media_description_options,
4360 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004361}
4362
Steve Antondcc3c022017-12-22 16:02:54 -08004363static cricket::MediaDescriptionOptions
4364GetMediaDescriptionOptionsForTransceiver(
4365 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4366 transceiver,
4367 const std::string& mid) {
4368 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004369 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004370 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004371 // This behavior is specified in JSEP. The gist is that:
4372 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4373 // sendrecv.
4374 // 2. If the MSID is included, then it must be included in any subsequent
4375 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004376 if (transceiver->stopped() ||
4377 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4378 !transceiver->internal()->has_ever_been_used_to_send())) {
4379 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004380 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004381
4382 cricket::SenderOptions sender_options;
4383 sender_options.track_id = transceiver->sender()->id();
4384 sender_options.stream_ids = transceiver->sender()->stream_ids();
4385
4386 // The following sets up RIDs and Simulcast.
4387 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004388 RtpParameters send_parameters =
4389 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004390 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4391 send_parameters.encodings.end(),
4392 [](const RtpEncodingParameters& encoding) {
4393 return !encoding.rid.empty();
4394 });
4395
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004396 std::vector<RidDescription> send_rids;
4397 SimulcastLayerList send_layers;
4398 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4399 if (encoding.rid.empty()) {
4400 continue;
4401 }
4402 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4403 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4404 }
4405
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004406 if (has_rids) {
4407 sender_options.rids = send_rids;
4408 }
4409
4410 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004411 // When RIDs are configured, we must set num_sim_layers to 0 to.
4412 // Otherwise, num_sim_layers must be 1 because either there is no
4413 // simulcast, or simulcast is acheived by munging the SDP.
4414 sender_options.num_sim_layers = has_rids ? 0 : 1;
4415 media_description_options.sender_options.push_back(sender_options);
4416
Steve Antondcc3c022017-12-22 16:02:54 -08004417 return media_description_options;
4418}
4419
Steve Anton5c72e712018-12-10 14:25:30 -08004420// Returns the ContentInfo at mline index |i|, or null if none exists.
4421static const ContentInfo* GetContentByIndex(
4422 const SessionDescriptionInterface* sdesc,
4423 size_t i) {
4424 if (!sdesc) {
4425 return nullptr;
4426 }
4427 const ContentInfos& contents = sdesc->description()->contents();
4428 return (i < contents.size() ? &contents[i] : nullptr);
4429}
4430
Steve Antondcc3c022017-12-22 16:02:54 -08004431void PeerConnection::GetOptionsForUnifiedPlanOffer(
4432 const RTCOfferAnswerOptions& offer_answer_options,
4433 cricket::MediaSessionOptions* session_options) {
4434 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4435 // Offers) and 5.2.2 (Subsequent Offers).
4436 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4437 const ContentInfos& local_contents =
4438 (local_description() ? local_description()->description()->contents()
4439 : ContentInfos());
4440 const ContentInfos& remote_contents =
4441 (remote_description() ? remote_description()->description()->contents()
4442 : ContentInfos());
4443 // The mline indices that can be recycled. New transceivers should reuse these
4444 // slots first.
4445 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004446 // First, go through each media section that exists in either the local or
4447 // remote description and generate a media section in this offer for the
4448 // associated transceiver. If a media section can be recycled, generate a
4449 // default, rejected media section here that can be later overwritten.
4450 for (size_t i = 0;
4451 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4452 // Either |local_content| or |remote_content| is non-null.
4453 const ContentInfo* local_content =
4454 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004455 const ContentInfo* current_local_content =
4456 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004457 const ContentInfo* remote_content =
4458 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004459 const ContentInfo* current_remote_content =
4460 GetContentByIndex(current_remote_description(), i);
4461 bool had_been_rejected =
4462 (current_local_content && current_local_content->rejected) ||
4463 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004464 const std::string& mid =
4465 (local_content ? local_content->name : remote_content->name);
4466 cricket::MediaType media_type =
4467 (local_content ? local_content->media_description()->type()
4468 : remote_content->media_description()->type());
4469 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4470 media_type == cricket::MEDIA_TYPE_VIDEO) {
4471 auto transceiver = GetAssociatedTransceiver(mid);
4472 RTC_CHECK(transceiver);
4473 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004474 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004475 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004476 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004477 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4478 RtpTransceiverDirection::kInactive,
4479 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004480 recycleable_mline_indices.push(i);
4481 } else {
4482 session_options->media_description_options.push_back(
4483 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4484 // CreateOffer shouldn't really cause any state changes in
4485 // PeerConnection, but we need a way to match new transceivers to new
4486 // media sections in SetLocalDescription and JSEP specifies this is done
4487 // by recording the index of the media section generated for the
4488 // transceiver in the offer.
4489 transceiver->internal()->set_mline_index(i);
4490 }
4491 } else {
4492 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004493 RTC_CHECK(GetDataMid());
4494 if (had_been_rejected || mid != *GetDataMid()) {
4495 session_options->media_description_options.push_back(
4496 GetMediaDescriptionOptionsForRejectedData(mid));
4497 } else {
4498 session_options->media_description_options.push_back(
4499 GetMediaDescriptionOptionsForActiveData(mid));
4500 }
Steve Antondcc3c022017-12-22 16:02:54 -08004501 }
4502 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004503
Steve Antondcc3c022017-12-22 16:02:54 -08004504 // Next, look for transceivers that are newly added (that is, are not stopped
4505 // and not associated). Reuse media sections marked as recyclable first,
4506 // otherwise append to the end of the offer. New media sections should be
4507 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004508 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004509 if (transceiver->mid() || transceiver->stopped()) {
4510 continue;
4511 }
4512 size_t mline_index;
4513 if (!recycleable_mline_indices.empty()) {
4514 mline_index = recycleable_mline_indices.front();
4515 recycleable_mline_indices.pop();
4516 session_options->media_description_options[mline_index] =
4517 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004518 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004519 } else {
4520 mline_index = session_options->media_description_options.size();
4521 session_options->media_description_options.push_back(
4522 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004523 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004524 }
4525 // See comment above for why CreateOffer changes the transceiver's state.
4526 transceiver->internal()->set_mline_index(mline_index);
4527 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004528 // Lastly, add a m-section if we have local data channels and an m section
4529 // does not already exist.
4530 if (!GetDataMid() && HasDataChannels()) {
4531 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004532 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004533 }
Steve Antondcc3c022017-12-22 16:02:54 -08004534}
4535
4536void PeerConnection::GetOptionsForAnswer(
4537 const RTCOfferAnswerOptions& offer_answer_options,
4538 cricket::MediaSessionOptions* session_options) {
4539 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4540
4541 if (IsUnifiedPlan()) {
4542 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4543 } else {
4544 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4545 }
4546
Steve Antonfa2260d2017-12-28 16:38:23 -08004547 // Intentionally unset the data channel type for RTP data channel. Otherwise
4548 // the RTP data channels would be successfully negotiated by default and the
4549 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4550 // We want to leave RTP data channels broken, so people won't try to use them.
4551 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4552 session_options->data_channel_type = data_channel_type();
4553 }
4554
Steve Antondcc3c022017-12-22 16:02:54 -08004555 // Apply ICE renomination flag.
4556 for (auto& options : session_options->media_description_options) {
4557 options.transport_options.enable_ice_renomination =
4558 configuration_.enable_ice_renomination;
4559 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004560
4561 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004562 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004563 session_options->pooled_ice_credentials =
4564 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4565 RTC_FROM_HERE,
4566 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4567 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004568}
4569
Steve Antondcc3c022017-12-22 16:02:54 -08004570void PeerConnection::GetOptionsForPlanBAnswer(
4571 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004572 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004573 // Figure out transceiver directional preferences.
4574 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4575 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4576
4577 // By default, generate sendrecv/recvonly m= sections. The direction is also
4578 // restricted by the direction in the offer.
4579 bool recv_audio = true;
4580 bool recv_video = true;
4581
4582 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004583 if (offer_answer_options.offer_to_receive_audio !=
4584 RTCOfferAnswerOptions::kUndefined) {
4585 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004586 }
Steve Antondcc3c022017-12-22 16:02:54 -08004587 if (offer_answer_options.offer_to_receive_video !=
4588 RTCOfferAnswerOptions::kUndefined) {
4589 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004590 }
4591
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004592 absl::optional<size_t> audio_index;
4593 absl::optional<size_t> video_index;
4594 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004595
4596 // Generate m= sections that match those in the offer.
4597 // Note that mediasession.cc will handle intersection our preferred
4598 // direction with the offered direction.
4599 GenerateMediaDescriptionOptions(
4600 remote_description(),
4601 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4602 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4603 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004604
4605 cricket::MediaDescriptionOptions* audio_media_description_options =
4606 !audio_index ? nullptr
4607 : &session_options->media_description_options[*audio_index];
4608 cricket::MediaDescriptionOptions* video_media_description_options =
4609 !video_index ? nullptr
4610 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004611
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004612 AddPlanBRtpSenderOptions(GetSendersInternal(),
4613 audio_media_description_options,
4614 video_media_description_options,
4615 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004616}
zhihuangaf388472016-11-02 16:49:48 -07004617
Steve Antondcc3c022017-12-22 16:02:54 -08004618void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4619 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4620 cricket::MediaSessionOptions* session_options) {
4621 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4622 // Answers) and 5.3.2 (Subsequent Answers).
4623 RTC_DCHECK(remote_description());
4624 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4625 for (const ContentInfo& content :
4626 remote_description()->description()->contents()) {
4627 cricket::MediaType media_type = content.media_description()->type();
4628 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4629 media_type == cricket::MEDIA_TYPE_VIDEO) {
4630 auto transceiver = GetAssociatedTransceiver(content.name);
4631 RTC_CHECK(transceiver);
4632 session_options->media_description_options.push_back(
4633 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4634 } else {
4635 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004636 // Reject all data sections if data channels are disabled.
4637 // Reject a data section if it has already been rejected.
4638 // Reject all data sections except for the first one.
4639 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4640 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004641 session_options->media_description_options.push_back(
4642 GetMediaDescriptionOptionsForRejectedData(content.name));
4643 } else {
4644 session_options->media_description_options.push_back(
4645 GetMediaDescriptionOptionsForActiveData(content.name));
4646 }
Steve Antondcc3c022017-12-22 16:02:54 -08004647 }
4648 }
htaa2a49d92016-03-04 02:51:39 -08004649}
4650
zhihuang1c378ed2017-08-17 14:10:50 -07004651void PeerConnection::GenerateMediaDescriptionOptions(
4652 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004653 RtpTransceiverDirection audio_direction,
4654 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004655 absl::optional<size_t>* audio_index,
4656 absl::optional<size_t>* video_index,
4657 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004658 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004659 for (const cricket::ContentInfo& content :
4660 session_desc->description()->contents()) {
4661 if (IsAudioContent(&content)) {
4662 // If we already have an audio m= section, reject this extra one.
4663 if (*audio_index) {
4664 session_options->media_description_options.push_back(
4665 cricket::MediaDescriptionOptions(
4666 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004667 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004668 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004669 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004670 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004671 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4672 content.name, audio_direction,
4673 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004674 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004675 }
4676 } else if (IsVideoContent(&content)) {
4677 // If we already have an video m= section, reject this extra one.
4678 if (*video_index) {
4679 session_options->media_description_options.push_back(
4680 cricket::MediaDescriptionOptions(
4681 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004682 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004683 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004684 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004685 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004686 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4687 content.name, video_direction,
4688 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004689 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004690 }
4691 } else {
4692 RTC_DCHECK(IsDataContent(&content));
4693 // If we already have an data m= section, reject this extra one.
4694 if (*data_index) {
4695 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004696 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004697 } else {
4698 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004699 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004700 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004701 }
4702 }
htaa2a49d92016-03-04 02:51:39 -08004703 }
deadbeefab9b2d12015-10-14 11:33:11 -07004704}
4705
Steve Antonfa2260d2017-12-28 16:38:23 -08004706cricket::MediaDescriptionOptions
4707PeerConnection::GetMediaDescriptionOptionsForActiveData(
4708 const std::string& mid) const {
4709 // Direction for data sections is meaningless, but legacy endpoints might
4710 // expect sendrecv.
4711 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4712 RtpTransceiverDirection::kSendRecv,
4713 /*stopped=*/false);
4714 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4715 return options;
4716}
4717
4718cricket::MediaDescriptionOptions
4719PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4720 const std::string& mid) const {
4721 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4722 RtpTransceiverDirection::kInactive,
4723 /*stopped=*/true);
4724 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4725 return options;
4726}
4727
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004728absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004729 switch (data_channel_type_) {
4730 case cricket::DCT_RTP:
4731 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004732 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004733 }
4734 return rtp_data_channel_->content_name();
4735 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004736 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004737 case cricket::DCT_MEDIA_TRANSPORT:
4738 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004739 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004740 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004741 }
4742}
4743
Steve Anton4171afb2017-11-20 10:20:22 -08004744void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4745 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4746 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004747 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004748}
4749
Steve Anton4171afb2017-11-20 10:20:22 -08004750void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004751 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004752 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004753 cricket::MediaType media_type,
4754 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004755 RTC_DCHECK(!IsUnifiedPlan());
4756
Steve Anton4171afb2017-11-20 10:20:22 -08004757 std::vector<RtpSenderInfo>* current_senders =
4758 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004759
Steve Anton4171afb2017-11-20 10:20:22 -08004760 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004761 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004762 for (auto sender_it = current_senders->begin();
4763 sender_it != current_senders->end();
4764 /* incremented manually */) {
4765 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004766 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004767 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004768 std::string params_stream_id;
4769 if (params) {
4770 params_stream_id =
4771 (!params->first_stream_id().empty() ? params->first_stream_id()
4772 : kDefaultStreamId);
4773 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004774 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004775 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004776 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004777 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004778 sender_exists) {
4779 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004780 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004781 OnRemoteSenderRemoved(info, media_type);
4782 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004783 }
4784 }
4785
Steve Anton4171afb2017-11-20 10:20:22 -08004786 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004787 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004788 if (!params.has_ssrcs()) {
4789 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4790 // sender, this means it is coming from a Unified Plan endpoint,so we just
4791 // create a default.
4792 default_sender_needed = true;
4793 break;
4794 }
4795
Seth Hampson845e8782018-03-02 11:34:10 -08004796 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004797 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004798 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4799 // not supported in Plan B, we just take the first here and create the
4800 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004801 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004802 (!params.first_stream_id().empty() ? params.first_stream_id()
4803 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004804 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004805 uint32_t ssrc = params.first_ssrc();
4806
4807 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004808 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004809 if (!stream) {
4810 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004811 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004812 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004813 remote_streams_->AddStream(stream);
4814 new_streams->AddStream(stream);
4815 }
4816
Steve Anton4171afb2017-11-20 10:20:22 -08004817 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004818 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004819 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004820 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004821 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004822 }
4823 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004824
Steve Anton4171afb2017-11-20 10:20:22 -08004825 // Add default sender if necessary.
4826 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004827 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004828 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004829 if (!default_stream) {
4830 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004831 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004832 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004833 remote_streams_->AddStream(default_stream);
4834 new_streams->AddStream(default_stream);
4835 }
Steve Anton4171afb2017-11-20 10:20:22 -08004836 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4837 ? kDefaultAudioSenderId
4838 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004839 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004840 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004841 if (!default_sender_info) {
4842 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004843 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004844 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004845 }
4846 }
deadbeefab9b2d12015-10-14 11:33:11 -07004847}
4848
Steve Anton4171afb2017-11-20 10:20:22 -08004849void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4850 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004851 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4852 << " receiver for track_id=" << sender_info.sender_id
4853 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004854
Steve Anton3d954a62018-04-02 11:27:23 -07004855 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004856 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004857 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004858 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004859 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004860 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004861 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004862 }
4863}
4864
Steve Anton4171afb2017-11-20 10:20:22 -08004865void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4866 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004867 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4868 << " receiver for track_id=" << sender_info.sender_id
4869 << " and stream_id=" << sender_info.stream_id;
4870
Seth Hampson845e8782018-03-02 11:34:10 -08004871 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004872
Henrik Boström933d8b02017-10-10 10:05:16 -07004873 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004874 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004875 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4876 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004877 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004878 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004879 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004880 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004881 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004882 }
4883 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004884 // Stopping or destroying a VideoRtpReceiver will end the
4885 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004886 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004887 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004888 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004889 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004890 // There's no guarantee the track is still available, e.g. the track may
4891 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004892 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004893 }
4894 } else {
nisseede5da42017-01-12 05:15:36 -08004895 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004896 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004897 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004898 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004899 }
deadbeefab9b2d12015-10-14 11:33:11 -07004900}
4901
4902void PeerConnection::UpdateEndedRemoteMediaStreams() {
4903 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4904 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4905 MediaStreamInterface* stream = remote_streams_->at(i);
4906 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4907 streams_to_remove.push_back(stream);
4908 }
4909 }
4910
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004911 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004912 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004913 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004914 }
4915}
4916
Steve Anton4171afb2017-11-20 10:20:22 -08004917void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004918 const std::vector<cricket::StreamParams>& streams,
4919 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004920 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004921
Seth Hampson845e8782018-03-02 11:34:10 -08004922 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004923 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004924 for (auto sender_it = current_senders->begin();
4925 sender_it != current_senders->end();
4926 /* incremented manually */) {
4927 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004928 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004929 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4930 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004931 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004932 OnLocalSenderRemoved(info, media_type);
4933 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004934 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004935 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004936 }
4937 }
4938
Steve Anton4171afb2017-11-20 10:20:22 -08004939 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004940 for (const cricket::StreamParams& params : streams) {
4941 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004942 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004943 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004944 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004945 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004946 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004947 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004948 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004949 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004950 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004951 }
4952 }
4953}
4954
Steve Anton4171afb2017-11-20 10:20:22 -08004955void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4956 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004957 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004958 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004959 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004960 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4961 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004962 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004963 return;
4964 }
4965
deadbeeffac06552015-11-25 11:26:01 -08004966 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004967 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004968 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004969 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004970 }
deadbeeffac06552015-11-25 11:26:01 -08004971
Seth Hampson5b4f0752018-04-02 16:31:36 -07004972 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004973 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004974}
4975
Steve Anton4171afb2017-11-20 10:20:22 -08004976void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4977 cricket::MediaType media_type) {
4978 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004979 if (!sender) {
4980 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004981 // SessionDescriptions has been renegotiated.
4982 return;
4983 }
deadbeeffac06552015-11-25 11:26:01 -08004984
4985 // A sender has been removed from the SessionDescription but it's still
4986 // associated with the PeerConnection. This only occurs if the SDP doesn't
4987 // match with the calls to CreateSender, AddStream and RemoveStream.
4988 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004989 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004990 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004991 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004992 }
deadbeeffac06552015-11-25 11:26:01 -08004993
Steve Anton4171afb2017-11-20 10:20:22 -08004994 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004995}
4996
4997void PeerConnection::UpdateLocalRtpDataChannels(
4998 const cricket::StreamParamsVec& streams) {
4999 std::vector<std::string> existing_channels;
5000
5001 // Find new and active data channels.
5002 for (const cricket::StreamParams& params : streams) {
5003 // |it->sync_label| is actually the data channel label. The reason is that
5004 // we use the same naming of data channels as we do for
5005 // MediaStreams and Tracks.
5006 // For MediaStreams, the sync_label is the MediaStream label and the
5007 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005008 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005009 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005010 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005011 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005012 continue;
5013 }
5014 // Set the SSRC the data channel should use for sending.
5015 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5016 existing_channels.push_back(data_channel_it->first);
5017 }
5018
5019 UpdateClosingRtpDataChannels(existing_channels, true);
5020}
5021
5022void PeerConnection::UpdateRemoteRtpDataChannels(
5023 const cricket::StreamParamsVec& streams) {
5024 std::vector<std::string> existing_channels;
5025
5026 // Find new and active data channels.
5027 for (const cricket::StreamParams& params : streams) {
5028 // The data channel label is either the mslabel or the SSRC if the mslabel
5029 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005030 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005031 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005032 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005033 auto data_channel_it = rtp_data_channels_.find(label);
5034 if (data_channel_it == rtp_data_channels_.end()) {
5035 // This is a new data channel.
5036 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5037 } else {
5038 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5039 }
5040 existing_channels.push_back(label);
5041 }
5042
5043 UpdateClosingRtpDataChannels(existing_channels, false);
5044}
5045
5046void PeerConnection::UpdateClosingRtpDataChannels(
5047 const std::vector<std::string>& active_channels,
5048 bool is_local_update) {
5049 auto it = rtp_data_channels_.begin();
5050 while (it != rtp_data_channels_.end()) {
5051 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005052 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005053 ++it;
5054 continue;
5055 }
5056
5057 if (is_local_update) {
5058 data_channel->SetSendSsrc(0);
5059 } else {
5060 data_channel->RemotePeerRequestClose();
5061 }
5062
5063 if (data_channel->state() == DataChannel::kClosed) {
5064 rtp_data_channels_.erase(it);
5065 it = rtp_data_channels_.begin();
5066 } else {
5067 ++it;
5068 }
5069 }
5070}
5071
5072void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5073 uint32_t remote_ssrc) {
5074 rtc::scoped_refptr<DataChannel> channel(
5075 InternalCreateDataChannel(label, nullptr));
5076 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005077 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005078 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005079 return;
5080 }
5081 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005082 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5083 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005084 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005085}
5086
5087rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5088 const std::string& label,
5089 const InternalDataChannelInit* config) {
5090 if (IsClosed()) {
5091 return nullptr;
5092 }
Steve Anton75737c02017-11-06 10:37:17 -08005093 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005094 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005095 << "InternalCreateDataChannel: Data is not supported in this call.";
5096 return nullptr;
5097 }
5098 InternalDataChannelInit new_config =
5099 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005100 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005101 if (new_config.id < 0) {
5102 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005103 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005104 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005105 RTC_LOG(LS_ERROR)
5106 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005107 return nullptr;
5108 }
5109 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005110 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005111 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005112 return nullptr;
5113 }
5114 }
5115
Steve Anton75737c02017-11-06 10:37:17 -08005116 rtc::scoped_refptr<DataChannel> channel(
5117 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005118 if (!channel) {
5119 sid_allocator_.ReleaseSid(new_config.id);
5120 return nullptr;
5121 }
5122
5123 if (channel->data_channel_type() == cricket::DCT_RTP) {
5124 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005125 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5126 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005127 return nullptr;
5128 }
5129 rtp_data_channels_[channel->label()] = channel;
5130 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005131 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005132 sctp_data_channels_.push_back(channel);
5133 channel->SignalClosed.connect(this,
5134 &PeerConnection::OnSctpDataChannelClosed);
5135 }
5136
Steve Anton2d8609c2018-01-23 16:38:46 -08005137 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005138 return channel;
5139}
5140
5141bool PeerConnection::HasDataChannels() const {
5142 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5143}
5144
5145void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005146 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005147 for (const auto& channel : sctp_data_channels_) {
5148 if (channel->id() < 0) {
5149 int sid;
5150 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005151 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5152 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005153 continue;
5154 }
5155 channel->SetSctpSid(sid);
5156 }
5157 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005158 // Since closing modifies the list of channels, we have to do the actual
5159 // closing outside the loop.
5160 for (const auto& channel : channels_to_close) {
5161 channel->CloseAbruptly();
5162 }
deadbeefab9b2d12015-10-14 11:33:11 -07005163}
5164
5165void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005166 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005167 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5168 ++it) {
5169 if (it->get() == channel) {
5170 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005171 // After the closing procedure is done, it's safe to use this ID for
5172 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005173 sid_allocator_.ReleaseSid(channel->id());
5174 }
deadbeefbd292462015-12-14 18:15:29 -08005175 // Since this method is triggered by a signal from the DataChannel,
5176 // we can't free it directly here; we need to free it asynchronously.
5177 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005178 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005179 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5180 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005181 return;
5182 }
5183 }
5184}
5185
deadbeefab9b2d12015-10-14 11:33:11 -07005186void PeerConnection::OnDataChannelDestroyed() {
5187 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5188 // DataChannel may callback to us and try to modify the list.
5189 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5190 temp_rtp_dcs.swap(rtp_data_channels_);
5191 for (const auto& kv : temp_rtp_dcs) {
5192 kv.second->OnTransportChannelDestroyed();
5193 }
5194
5195 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5196 temp_sctp_dcs.swap(sctp_data_channels_);
5197 for (const auto& channel : temp_sctp_dcs) {
5198 channel->OnTransportChannelDestroyed();
5199 }
5200}
5201
5202void PeerConnection::OnDataChannelOpenMessage(
5203 const std::string& label,
5204 const InternalDataChannelInit& config) {
5205 rtc::scoped_refptr<DataChannel> channel(
5206 InternalCreateDataChannel(label, &config));
5207 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005208 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005209 return;
5210 }
5211
deadbeefa601f5c2016-06-06 14:27:39 -07005212 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5213 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005214 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005215 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005216}
5217
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005218bool PeerConnection::HandleOpenMessage_s(
5219 const cricket::ReceiveDataParams& params,
5220 const rtc::CopyOnWriteBuffer& buffer) {
5221 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5222 // Received OPEN message; parse and signal that a new data channel should
5223 // be created.
5224 std::string label;
5225 InternalDataChannelInit config;
5226 config.id = params.ssrc;
5227 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5228 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5229 << params.ssrc;
5230 return true;
5231 }
5232 config.open_handshake_role = InternalDataChannelInit::kAcker;
5233 OnDataChannelOpenMessage(label, config);
5234 return true;
5235 }
5236 return false;
5237}
5238
Steve Anton4171afb2017-11-20 10:20:22 -08005239rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5240PeerConnection::GetAudioTransceiver() const {
5241 // This method only works with Plan B SDP, where there is a single
5242 // audio/video transceiver.
5243 RTC_DCHECK(!IsUnifiedPlan());
5244 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005245 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005246 return transceiver;
5247 }
5248 }
5249 RTC_NOTREACHED();
5250 return nullptr;
5251}
5252
5253rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5254PeerConnection::GetVideoTransceiver() const {
5255 // This method only works with Plan B SDP, where there is a single
5256 // audio/video transceiver.
5257 RTC_DCHECK(!IsUnifiedPlan());
5258 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005259 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005260 return transceiver;
5261 }
5262 }
5263 RTC_NOTREACHED();
5264 return nullptr;
5265}
5266
5267// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5268// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005269bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005270 switch (type) {
5271 case cricket::MEDIA_TYPE_AUDIO:
5272 return !GetAudioTransceiver()->internal()->senders().empty();
5273 case cricket::MEDIA_TYPE_VIDEO:
5274 return !GetVideoTransceiver()->internal()->senders().empty();
5275 case cricket::MEDIA_TYPE_DATA:
5276 return false;
5277 }
5278 RTC_NOTREACHED();
5279 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005280}
5281
Steve Anton4171afb2017-11-20 10:20:22 -08005282rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5283PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005284 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005285 for (auto sender : transceiver->internal()->senders()) {
5286 if (sender->track() == track) {
5287 return sender;
5288 }
5289 }
5290 }
5291 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005292}
5293
Steve Anton4171afb2017-11-20 10:20:22 -08005294rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5295PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005296 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005297 for (auto sender : transceiver->internal()->senders()) {
5298 if (sender->id() == sender_id) {
5299 return sender;
5300 }
5301 }
5302 }
5303 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005304}
5305
Steve Anton4171afb2017-11-20 10:20:22 -08005306rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5307PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005308 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005309 for (auto receiver : transceiver->internal()->receivers()) {
5310 if (receiver->id() == receiver_id) {
5311 return receiver;
5312 }
5313 }
5314 }
5315 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005316}
5317
Steve Anton4171afb2017-11-20 10:20:22 -08005318std::vector<PeerConnection::RtpSenderInfo>*
5319PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5320 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5321 media_type == cricket::MEDIA_TYPE_VIDEO);
5322 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5323 ? &remote_audio_sender_infos_
5324 : &remote_video_sender_infos_;
5325}
5326
5327std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005328 cricket::MediaType media_type) {
5329 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5330 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005331 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5332 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005333}
5334
Steve Anton4171afb2017-11-20 10:20:22 -08005335const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5336 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005337 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005338 const std::string sender_id) const {
5339 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005340 if (sender_info.stream_id == stream_id &&
5341 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005342 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005343 }
5344 }
5345 return nullptr;
5346}
5347
5348DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5349 for (const auto& channel : sctp_data_channels_) {
5350 if (channel->id() == sid) {
5351 return channel;
5352 }
5353 }
5354 return nullptr;
5355}
5356
Karl Wibergfb3be392019-03-22 14:13:22 +01005357PeerConnection::InitializePortAllocatorResult
5358PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005359 const cricket::ServerAddresses& stun_servers,
5360 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005361 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005362 RTC_DCHECK_RUN_ON(network_thread());
5363
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005364 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005365 // To handle both internal and externally created port allocator, we will
5366 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005367 int port_allocator_flags = port_allocator_->flags();
5368 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5369 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5370 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005371 // If the disable-IPv6 flag was specified, we'll not override it
5372 // by experiment.
5373 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005374 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005375 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5376 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005377 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005378 }
5379
zhihuangb09b3f92017-03-07 14:40:51 -08005380 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005381 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005382 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005383 }
5384
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005385 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005386 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005387 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005388 }
5389
honghaiz60347052016-05-31 18:29:12 -07005390 if (configuration.candidate_network_policy ==
5391 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005392 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005393 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005394 }
5395
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005396 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005397 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005398 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5399 }
5400
Karl Wibergfb3be392019-03-22 14:13:22 +01005401 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005402 // No step delay is used while allocating ports.
5403 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5404 port_allocator_->set_candidate_filter(
5405 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005406 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005407
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005408 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005409 for (auto& turn_server : turn_servers_copy) {
5410 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005411 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005412 // Call this last since it may create pooled allocator sessions using the
5413 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005414 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005415 stun_servers, std::move(turn_servers_copy),
5416 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5417 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005418 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005419
5420 InitializePortAllocatorResult res;
5421 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5422 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005423}
5424
deadbeef91dd5672016-05-18 16:55:30 -07005425bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005426 const cricket::ServerAddresses& stun_servers,
5427 const std::vector<cricket::RelayServerConfig>& turn_servers,
5428 IceTransportsType type,
5429 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005430 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005431 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005432 absl::optional<int> stun_candidate_keepalive_interval,
5433 bool have_local_description) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005434 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005435 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005436 // According to JSEP, after setLocalDescription, changing the candidate pool
5437 // size is not allowed, and changing the set of ICE servers will not result
5438 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005439 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005440 port_allocator_->FreezeCandidatePool();
5441 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005442 // Add the custom tls turn servers if they exist.
5443 auto turn_servers_copy = turn_servers;
5444 for (auto& turn_server : turn_servers_copy) {
5445 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5446 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005447 // Call this last since it may create pooled allocator sessions using the
5448 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005449 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005450 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5451 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005452}
5453
Steve Antonba818672017-11-06 10:21:57 -08005454cricket::ChannelManager* PeerConnection::channel_manager() const {
5455 return factory_->channel_manager();
5456}
5457
Elad Alon99c3fe52017-10-13 16:29:40 +02005458bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005459 std::unique_ptr<RtcEventLogOutput> output,
5460 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005461 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005462 if (!event_log_) {
5463 return false;
5464 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005465 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005466}
5467
5468void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005469 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005470 if (event_log_) {
5471 event_log_->StopLogging();
5472 }
ivoc14d5dbe2016-07-04 07:06:55 -07005473}
nisseeaabdf62017-05-05 02:23:02 -07005474
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005475cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005476 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005477 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005478 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005479 if (channel && channel->content_name() == content_name) {
5480 return channel;
5481 }
Steve Anton75737c02017-11-06 10:37:17 -08005482 }
5483 if (rtp_data_channel() &&
5484 rtp_data_channel()->content_name() == content_name) {
5485 return rtp_data_channel();
5486 }
5487 return nullptr;
5488}
5489
5490bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005491 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005492 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005493 RTC_LOG(LS_INFO)
5494 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005495 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005496 return false;
5497 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005498 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005499 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005500 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005501 return false;
5502 }
5503
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005504 absl::optional<rtc::SSLRole> dtls_role;
5505 if (sctp_mid_) {
5506 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5507 } else if (is_caller_) {
5508 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5509 }
Zhi Huange830e682018-03-30 10:48:35 -07005510 if (dtls_role) {
5511 *role = *dtls_role;
5512 return true;
5513 }
5514 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005515}
5516
5517bool PeerConnection::GetSslRole(const std::string& content_name,
5518 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005519 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005520 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005521 RTC_LOG(LS_INFO)
5522 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005523 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005524 return false;
5525 }
5526
Zhi Huange830e682018-03-30 10:48:35 -07005527 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5528 if (dtls_role) {
5529 *role = *dtls_role;
5530 return true;
5531 }
5532 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005533}
5534
Steve Antonf8470812017-12-04 10:46:21 -08005535void PeerConnection::SetSessionError(SessionError error,
5536 const std::string& error_desc) {
5537 RTC_DCHECK_RUN_ON(signaling_thread());
5538 if (error != session_error_) {
5539 session_error_ = error;
5540 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005541 }
5542}
5543
Zhi Huange830e682018-03-30 10:48:35 -07005544RTCError PeerConnection::UpdateSessionState(
5545 SdpType type,
5546 cricket::ContentSource source,
5547 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005548 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005549
5550 // If there's already a pending error then no state transition should happen.
5551 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005552 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005553
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005554 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005555 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005556 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005557 }
5558
5559 // Update the signaling state according to the specified state machine (see
5560 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005561 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005562 ChangeSignalingState(source == cricket::CS_LOCAL
5563 ? PeerConnectionInterface::kHaveLocalOffer
5564 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005565 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005566 ChangeSignalingState(source == cricket::CS_LOCAL
5567 ? PeerConnectionInterface::kHaveLocalPrAnswer
5568 : PeerConnectionInterface::kHaveRemotePrAnswer);
5569 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005570 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005571 ChangeSignalingState(PeerConnectionInterface::kStable);
5572 }
5573
5574 // Update internal objects according to the session description's media
5575 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005576 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005577 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005578 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005579 }
5580
Steve Anton8a006912017-12-04 15:25:56 -08005581 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005582}
5583
Steve Anton8a006912017-12-04 15:25:56 -08005584RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005585 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005586 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005587 const SessionDescriptionInterface* sdesc =
5588 (source == cricket::CS_LOCAL ? local_description()
5589 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005590 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005591
5592 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005593 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005594 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005595 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005596 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005597 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005598 continue;
5599 }
5600 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005601 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005602 if (!content_desc) {
5603 continue;
5604 }
5605 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005606 bool success = (source == cricket::CS_LOCAL)
5607 ? channel->SetLocalContent(content_desc, type, &error)
5608 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005609 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005610 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005611 }
5612 }
5613
5614 // If using the RtpDataChannel, push down the new SDP section for it too.
5615 if (rtp_data_channel_) {
5616 const ContentInfo* data_content =
5617 cricket::GetFirstDataContent(sdesc->description());
5618 if (data_content && !data_content->rejected) {
5619 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005620 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005621 if (data_desc) {
5622 std::string error;
5623 bool success =
5624 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005625 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005626 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005627 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005628 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005629 }
Steve Anton75737c02017-11-06 10:37:17 -08005630 }
5631 }
5632 }
Steve Antoned10bd92017-12-05 10:52:59 -08005633
Steve Anton75737c02017-11-06 10:37:17 -08005634 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5635 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5636 if (sctp_transport_ && local_description() && remote_description() &&
5637 cricket::GetFirstDataContent(local_description()->description()) &&
5638 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005639 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005640 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 11:37:28 +02005641 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5642 GetSctpPort(local_description()->description()),
5643 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 15:25:56 -08005644 if (!success) {
5645 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5646 "Failed to push down SCTP parameters.");
5647 }
Steve Anton75737c02017-11-06 10:37:17 -08005648 }
Steve Antoned10bd92017-12-05 10:52:59 -08005649
Steve Anton8a006912017-12-04 15:25:56 -08005650 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005651}
5652
Karl Wiberg739506e2019-04-03 11:37:28 +02005653bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5654 int local_sctp_port,
5655 int remote_sctp_port) {
5656 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005657 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5658 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 11:37:28 +02005659 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 10:37:17 -08005660}
5661
Steve Anton8a006912017-12-04 15:25:56 -08005662RTCError PeerConnection::PushdownTransportDescription(
5663 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005664 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005665 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005666
Zhi Huange830e682018-03-30 10:48:35 -07005667 if (source == cricket::CS_LOCAL) {
5668 const SessionDescriptionInterface* sdesc = local_description();
5669 RTC_DCHECK(sdesc);
5670 return transport_controller_->SetLocalDescription(type,
5671 sdesc->description());
5672 } else {
5673 const SessionDescriptionInterface* sdesc = remote_description();
5674 RTC_DCHECK(sdesc);
5675 return transport_controller_->SetRemoteDescription(type,
5676 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005677 }
Steve Anton75737c02017-11-06 10:37:17 -08005678}
5679
5680bool PeerConnection::GetTransportDescription(
5681 const SessionDescription* description,
5682 const std::string& content_name,
5683 cricket::TransportDescription* tdesc) {
5684 if (!description || !tdesc) {
5685 return false;
5686 }
5687 const TransportInfo* transport_info =
5688 description->GetTransportInfoByName(content_name);
5689 if (!transport_info) {
5690 return false;
5691 }
5692 *tdesc = transport_info->description;
5693 return true;
5694}
5695
Steve Anton75737c02017-11-06 10:37:17 -08005696cricket::IceConfig PeerConnection::ParseIceConfig(
5697 const PeerConnectionInterface::RTCConfiguration& config) const {
5698 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005699 switch (config.continual_gathering_policy) {
5700 case PeerConnectionInterface::GATHER_ONCE:
5701 gathering_policy = cricket::GATHER_ONCE;
5702 break;
5703 case PeerConnectionInterface::GATHER_CONTINUALLY:
5704 gathering_policy = cricket::GATHER_CONTINUALLY;
5705 break;
5706 default:
5707 RTC_NOTREACHED();
5708 gathering_policy = cricket::GATHER_ONCE;
5709 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005710
Steve Anton75737c02017-11-06 10:37:17 -08005711 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005712 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5713 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005714 ice_config.prioritize_most_likely_candidate_pairs =
5715 config.prioritize_most_likely_ice_candidate_pairs;
5716 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005717 RTCConfigurationToIceConfigOptionalInt(
5718 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005719 ice_config.continual_gathering_policy = gathering_policy;
5720 ice_config.presume_writable_when_fully_relayed =
5721 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005722 ice_config.ice_check_interval_strong_connectivity =
5723 config.ice_check_interval_strong_connectivity;
5724 ice_config.ice_check_interval_weak_connectivity =
5725 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005726 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005727 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5728 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005729 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005730 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005731 ice_config.regather_all_networks_interval_range =
5732 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005733 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005734 return ice_config;
5735}
5736
Steve Anton75737c02017-11-06 10:37:17 -08005737bool PeerConnection::SendData(const cricket::SendDataParams& params,
5738 const rtc::CopyOnWriteBuffer& payload,
5739 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005740 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005741 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5742 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5743 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005744 return false;
5745 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005746 if (media_transport_) {
5747 SendDataParams send_params;
5748 send_params.type = ToWebrtcDataMessageType(params.type);
5749 send_params.ordered = params.ordered;
5750 if (params.max_rtx_count >= 0) {
5751 send_params.max_rtx_count = params.max_rtx_count;
5752 } else if (params.max_rtx_ms >= 0) {
5753 send_params.max_rtx_ms = params.max_rtx_ms;
5754 }
5755 return media_transport_->SendData(params.sid, send_params, payload).ok();
5756 }
Steve Anton75737c02017-11-06 10:37:17 -08005757 return rtp_data_channel_
5758 ? rtp_data_channel_->SendData(params, payload, result)
5759 : network_thread()->Invoke<bool>(
5760 RTC_FROM_HERE,
5761 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005762 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005763}
5764
5765bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005766 RTC_DCHECK_RUN_ON(signaling_thread());
5767 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005768 // Don't log an error here, because DataChannels are expected to call
5769 // ConnectDataChannel in this state. It's the only way to initially tell
5770 // whether or not the underlying transport is ready.
5771 return false;
5772 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005773 if (media_transport_) {
5774 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5775 &DataChannel::OnChannelReady);
5776 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5777 &DataChannel::OnDataReceived);
5778 SignalMediaTransportChannelClosing_s.connect(
5779 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5780 SignalMediaTransportChannelClosed_s.connect(
5781 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5782 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005783 rtp_data_channel_->SignalReadyToSendData.connect(
5784 webrtc_data_channel, &DataChannel::OnChannelReady);
5785 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5786 &DataChannel::OnDataReceived);
5787 } else {
5788 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5789 &DataChannel::OnChannelReady);
5790 SignalSctpDataReceived.connect(webrtc_data_channel,
5791 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005792 SignalSctpClosingProcedureStartedRemotely.connect(
5793 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5794 SignalSctpClosingProcedureComplete.connect(
5795 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005796 }
5797 return true;
5798}
5799
5800void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005801 RTC_DCHECK_RUN_ON(signaling_thread());
5802 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005803 RTC_LOG(LS_ERROR)
5804 << "DisconnectDataChannel called when rtp_data_channel_ and "
5805 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005806 return;
5807 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005808 if (media_transport_) {
5809 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5810 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5811 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5812 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5813 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005814 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5815 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5816 } else {
5817 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5818 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005819 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5820 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005821 }
5822}
5823
5824void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005825 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005826 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005827 return;
5828 }
Steve Anton75737c02017-11-06 10:37:17 -08005829 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005830 RTC_LOG(LS_ERROR)
5831 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005832 return;
5833 }
5834 network_thread()->Invoke<void>(
5835 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005836 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005837}
5838
5839void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005840 if (media_transport_) {
5841 media_transport_->CloseChannel(sid);
5842 return;
5843 }
Steve Anton75737c02017-11-06 10:37:17 -08005844 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005845 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005846 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005847 return;
5848 }
5849 network_thread()->Invoke<void>(
5850 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005851 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005852}
5853
5854bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005855 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005856 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005857 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005858 sctp_ready_to_send_data_;
5859}
5860
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005861void PeerConnection::OnDataReceived(int channel_id,
5862 DataMessageType type,
5863 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005864 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005865 cricket::ReceiveDataParams params;
5866 params.sid = channel_id;
5867 params.type = ToCricketDataMessageType(type);
5868 media_transport_invoker_->AsyncInvoke<void>(
5869 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5870 RTC_DCHECK_RUN_ON(signaling_thread());
5871 if (!HandleOpenMessage_s(params, buffer)) {
5872 SignalMediaTransportReceivedData_s(params, buffer);
5873 }
5874 });
5875}
5876
5877void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005878 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005879 media_transport_invoker_->AsyncInvoke<void>(
5880 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5881 RTC_DCHECK_RUN_ON(signaling_thread());
5882 SignalMediaTransportChannelClosing_s(channel_id);
5883 });
5884}
5885
5886void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005887 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005888 media_transport_invoker_->AsyncInvoke<void>(
5889 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5890 RTC_DCHECK_RUN_ON(signaling_thread());
5891 SignalMediaTransportChannelClosed_s(channel_id);
5892 });
5893}
5894
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005895absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005896 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005897 if (sctp_mid_ && transport_controller_) {
5898 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5899 if (dtls_transport) {
5900 return dtls_transport->transport_name();
5901 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005902 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005903 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005904 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005905}
5906
Qingsi Wang72a43a12018-02-20 16:03:18 -08005907cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5908 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005909 network_thread()->Invoke<void>(
5910 RTC_FROM_HERE,
5911 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5912 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005913 return candidate_states_list;
5914}
5915
Steve Anton5dfde182018-02-06 10:34:40 -08005916std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5917 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005918 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005919 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005920 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005921 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005922 if (channel) {
5923 transport_names_by_mid[channel->content_name()] =
5924 channel->transport_name();
5925 }
Steve Anton75737c02017-11-06 10:37:17 -08005926 }
Steve Anton5dfde182018-02-06 10:34:40 -08005927 if (rtp_data_channel_) {
5928 transport_names_by_mid[rtp_data_channel_->content_name()] =
5929 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005930 }
5931 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005932 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005933 RTC_DCHECK(transport_name);
5934 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005935 }
Steve Anton5dfde182018-02-06 10:34:40 -08005936 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005937}
5938
Steve Anton5dfde182018-02-06 10:34:40 -08005939std::map<std::string, cricket::TransportStats>
5940PeerConnection::GetTransportStatsByNames(
5941 const std::set<std::string>& transport_names) {
5942 if (!network_thread()->IsCurrent()) {
5943 return network_thread()
5944 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5945 RTC_FROM_HERE,
5946 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005947 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005948 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005949 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5950 for (const std::string& transport_name : transport_names) {
5951 cricket::TransportStats transport_stats;
5952 bool success =
5953 transport_controller_->GetStats(transport_name, &transport_stats);
5954 if (success) {
5955 transport_stats_by_name[transport_name] = std::move(transport_stats);
5956 } else {
5957 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5958 << transport_name;
5959 }
5960 }
5961 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005962}
5963
5964bool PeerConnection::GetLocalCertificate(
5965 const std::string& transport_name,
5966 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005967 if (!certificate) {
5968 return false;
5969 }
5970 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5971 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005972}
5973
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005974std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005975 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005976 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005977}
5978
5979cricket::DataChannelType PeerConnection::data_channel_type() const {
5980 return data_channel_type_;
5981}
5982
5983bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02005984 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005985 return pending_ice_restarts_.find(content_name) !=
5986 pending_ice_restarts_.end();
5987}
5988
Steve Anton75737c02017-11-06 10:37:17 -08005989bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5990 return transport_controller_->NeedsIceRestart(content_name);
5991}
5992
5993void PeerConnection::OnCertificateReady(
5994 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5995 transport_controller_->SetLocalCertificate(certificate);
5996}
5997
5998void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005999 SetSessionError(SessionError::kTransport,
6000 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006001}
6002
Alex Loiko9289eda2018-11-23 16:18:59 +00006003void PeerConnection::OnTransportControllerConnectionState(
6004 cricket::IceConnectionState state) {
6005 switch (state) {
6006 case cricket::kIceConnectionConnecting:
6007 // If the current state is Connected or Completed, then there were
6008 // writable channels but now there are not, so the next state must
6009 // be Disconnected.
6010 // kIceConnectionConnecting is currently used as the default,
6011 // un-connected state by the TransportController, so its only use is
6012 // detecting disconnections.
6013 if (ice_connection_state_ ==
6014 PeerConnectionInterface::kIceConnectionConnected ||
6015 ice_connection_state_ ==
6016 PeerConnectionInterface::kIceConnectionCompleted) {
6017 SetIceConnectionState(
6018 PeerConnectionInterface::kIceConnectionDisconnected);
6019 }
6020 break;
6021 case cricket::kIceConnectionFailed:
6022 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6023 break;
6024 case cricket::kIceConnectionConnected:
6025 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6026 "all transports are writable.";
6027 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6028 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6029 break;
6030 case cricket::kIceConnectionCompleted:
6031 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6032 "all transports are complete.";
6033 if (ice_connection_state_ !=
6034 PeerConnectionInterface::kIceConnectionConnected) {
6035 // If jumping directly from "checking" to "connected",
6036 // signal "connected" first.
6037 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6038 }
6039 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6040 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6041 ReportTransportStats();
6042 break;
6043 default:
6044 RTC_NOTREACHED();
6045 }
6046}
6047
Steve Anton75737c02017-11-06 10:37:17 -08006048void PeerConnection::OnTransportControllerCandidatesGathered(
6049 const std::string& transport_name,
6050 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006051 int sdp_mline_index;
6052 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006053 RTC_LOG(LS_ERROR)
6054 << "OnTransportControllerCandidatesGathered: content name "
6055 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006056 return;
6057 }
6058
6059 for (cricket::Candidates::const_iterator citer = candidates.begin();
6060 citer != candidates.end(); ++citer) {
6061 // Use transport_name as the candidate media id.
6062 std::unique_ptr<JsepIceCandidate> candidate(
6063 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6064 if (local_description()) {
6065 mutable_local_description()->AddCandidate(candidate.get());
6066 }
6067 OnIceCandidate(std::move(candidate));
6068 }
6069}
6070
6071void PeerConnection::OnTransportControllerCandidatesRemoved(
6072 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006073 // Sanity check.
6074 for (const cricket::Candidate& candidate : candidates) {
6075 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006076 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006077 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006078 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006079 return;
6080 }
6081 }
6082
6083 if (local_description()) {
6084 mutable_local_description()->RemoveCandidates(candidates);
6085 }
6086 OnIceCandidatesRemoved(candidates);
6087}
6088
6089void PeerConnection::OnTransportControllerDtlsHandshakeError(
6090 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006091 RTC_HISTOGRAM_ENUMERATION(
6092 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6093 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006094}
6095
Steve Antoned10bd92017-12-05 10:52:59 -08006096void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006097 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006098 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006099 if (channel && !channel->enabled()) {
6100 channel->Enable(true);
6101 }
Steve Anton75737c02017-11-06 10:37:17 -08006102 }
6103
Steve Anton4171afb2017-11-20 10:20:22 -08006104 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006105 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006106 }
Steve Anton75737c02017-11-06 10:37:17 -08006107}
6108
6109// Returns the media index for a local ice candidate given the content name.
6110bool PeerConnection::GetLocalCandidateMediaIndex(
6111 const std::string& content_name,
6112 int* sdp_mline_index) {
6113 if (!local_description() || !sdp_mline_index) {
6114 return false;
6115 }
6116
6117 bool content_found = false;
6118 const ContentInfos& contents = local_description()->description()->contents();
6119 for (size_t index = 0; index < contents.size(); ++index) {
6120 if (contents[index].name == content_name) {
6121 *sdp_mline_index = static_cast<int>(index);
6122 content_found = true;
6123 break;
6124 }
6125 }
6126 return content_found;
6127}
6128
6129bool PeerConnection::UseCandidatesInSessionDescription(
6130 const SessionDescriptionInterface* remote_desc) {
6131 if (!remote_desc) {
6132 return true;
6133 }
6134 bool ret = true;
6135
6136 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6137 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6138 for (size_t n = 0; n < candidates->count(); ++n) {
6139 const IceCandidateInterface* candidate = candidates->at(n);
6140 bool valid = false;
6141 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6142 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006143 RTC_LOG(LS_INFO)
6144 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006145 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006146 }
6147 continue;
6148 }
6149 ret = UseCandidate(candidate);
6150 if (!ret) {
6151 break;
6152 }
6153 }
6154 }
6155 return ret;
6156}
6157
6158bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6159 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6160 size_t remote_content_size =
6161 remote_description()->description()->contents().size();
6162 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006163 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006164 return false;
6165 }
6166
6167 cricket::ContentInfo content =
6168 remote_description()->description()->contents()[mediacontent_index];
6169 std::vector<cricket::Candidate> candidates;
6170 candidates.push_back(candidate->candidate());
6171 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006172 RTCError error =
6173 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006174 if (error.ok()) {
6175 // Candidates successfully submitted for checking.
6176 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6177 ice_connection_state_ ==
6178 PeerConnectionInterface::kIceConnectionDisconnected) {
6179 // If state is New, then the session has just gotten its first remote ICE
6180 // candidates, so go to Checking.
6181 // If state is Disconnected, the session is re-using old candidates or
6182 // receiving additional ones, so go to Checking.
6183 // If state is Connected, stay Connected.
6184 // TODO(bemasc): If state is Connected, and the new candidates are for a
6185 // newly added transport, then the state actually _should_ move to
6186 // checking. Add a way to distinguish that case.
6187 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6188 }
6189 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006190 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006191 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006192 }
6193 return true;
6194}
6195
6196void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006197 // Destroy video channel first since it may have a pointer to the
6198 // voice channel.
6199 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006200 if (!video_info || video_info->rejected) {
6201 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006202 }
6203
Steve Anton6fec8802017-12-04 10:37:29 -08006204 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6205 if (!audio_info || audio_info->rejected) {
6206 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006207 }
6208
6209 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6210 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006211 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006212 }
6213}
6214
Steve Antondcc3c022017-12-22 16:02:54 -08006215RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6216 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006217 const cricket::ContentGroup* bundle_group = nullptr;
6218 if (configuration_.bundle_policy ==
6219 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006220 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006221 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006222 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6223 "max-bundle configured but session description "
6224 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006225 }
6226 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006227 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006228}
6229
6230RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006231 // Creating the media channels. Transports should already have been created
6232 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006233 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006234 if (voice && !voice->rejected &&
6235 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006236 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006237 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006238 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6239 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006240 }
6241 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6242 }
6243
Steve Antondcc3c022017-12-22 16:02:54 -08006244 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006245 if (video && !video->rejected &&
6246 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006247 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006248 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006249 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6250 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006251 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006252 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006253 }
6254
Steve Antondcc3c022017-12-22 16:02:54 -08006255 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006256 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006257 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006258 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006259 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6260 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006261 }
6262 }
6263
Steve Anton8a006912017-12-04 15:25:56 -08006264 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006265}
6266
Steve Anton4171afb2017-11-20 10:20:22 -08006267// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006268cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006269 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006270 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006271 MediaTransportInterface* media_transport = nullptr;
6272 if (configuration_.use_media_transport) {
6273 media_transport = GetMediaTransport(mid);
6274 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006275
Steve Anton75737c02017-11-06 10:37:17 -08006276 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006277 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006278 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006279 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006280 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006281 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006282 }
Steve Anton75737c02017-11-06 10:37:17 -08006283 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6284 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006285 voice_channel->SignalSentPacket.connect(this,
6286 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006287 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006288
Steve Antoneda6ccd2017-12-04 10:21:55 -08006289 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006290}
6291
Steve Anton4171afb2017-11-20 10:20:22 -08006292// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006293cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006294 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006295 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006296 MediaTransportInterface* media_transport = nullptr;
6297 if (configuration_.use_media_transport) {
6298 media_transport = GetMediaTransport(mid);
6299 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006300
Steve Anton75737c02017-11-06 10:37:17 -08006301 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006302 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006303 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006304 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006305 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006306 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006307 }
Steve Anton75737c02017-11-06 10:37:17 -08006308 video_channel->SignalDtlsSrtpSetupFailure.connect(
6309 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006310 video_channel->SignalSentPacket.connect(this,
6311 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006312 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006313
Steve Antoneda6ccd2017-12-04 10:21:55 -08006314 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006315}
6316
Zhi Huange830e682018-03-30 10:48:35 -07006317bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006318 switch (data_channel_type_) {
6319 case cricket::DCT_MEDIA_TRANSPORT:
6320 if (network_thread()->Invoke<bool>(
6321 RTC_FROM_HERE,
6322 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6323 this, mid))) {
6324 for (const auto& channel : sctp_data_channels_) {
6325 channel->OnTransportChannelCreated();
6326 }
6327 return true;
6328 }
Steve Anton75737c02017-11-06 10:37:17 -08006329 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006330 case cricket::DCT_SCTP:
6331 if (!sctp_factory_) {
6332 RTC_LOG(LS_ERROR)
6333 << "Trying to create SCTP transport, but didn't compile with "
6334 "SCTP support (HAVE_SCTP)";
6335 return false;
6336 }
6337 if (!network_thread()->Invoke<bool>(
6338 RTC_FROM_HERE,
6339 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6340 return false;
6341 }
6342 for (const auto& channel : sctp_data_channels_) {
6343 channel->OnTransportChannelCreated();
6344 }
6345 return true;
6346 case cricket::DCT_RTP:
6347 default:
6348 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6349 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6350 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006351 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006352 if (!rtp_data_channel_) {
6353 return false;
6354 }
6355 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6356 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6357 rtp_data_channel_->SignalSentPacket.connect(
6358 this, &PeerConnection::OnSentPacket_w);
6359 rtp_data_channel_->SetRtpTransport(rtp_transport);
6360 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006361 }
6362
Steve Anton75737c02017-11-06 10:37:17 -08006363 return true;
6364}
6365
6366Call::Stats PeerConnection::GetCallStats() {
6367 if (!worker_thread()->IsCurrent()) {
6368 return worker_thread()->Invoke<Call::Stats>(
6369 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6370 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006371 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006372 if (call_) {
6373 return call_->GetStats();
6374 } else {
6375 return Call::Stats();
6376 }
6377}
6378
Zhi Huange830e682018-03-30 10:48:35 -07006379bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006380 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006381 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006382 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6383 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006384 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006385 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006386 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006387 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6388 sctp_factory_->CreateSctpTransport(dtls_transport);
6389 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006390 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006391 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006392 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006393 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006394 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006395 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6396 // another thread. Would be nice if there was a helper class similar to
6397 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6398 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006399 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006400 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006401 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006402 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006403 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006404 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6405 std::move(cricket_sctp_transport));
6406 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006407 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006408}
6409
6410void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006411 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006412 sctp_transport_->Clear();
6413 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006414 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006415 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006416}
6417
6418void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006419 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006420 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006421 // Note: Cannot use rtc::Bind here because it will grab a reference to
6422 // PeerConnection and potentially cause PeerConnection to live longer than
6423 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6424 // be destroyed before PeerConnection is destroyed, and at that point all
6425 // pending tasks will be cleared.
6426 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6427 OnSctpTransportReadyToSendData_s(true);
6428 });
6429}
6430
6431void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006432 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006433 sctp_ready_to_send_data_ = ready;
6434 SignalSctpReadyToSendData(ready);
6435}
6436
6437void PeerConnection::OnSctpTransportDataReceived_n(
6438 const cricket::ReceiveDataParams& params,
6439 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006440 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006441 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006442 // Note: Cannot use rtc::Bind here because it will grab a reference to
6443 // PeerConnection and potentially cause PeerConnection to live longer than
6444 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6445 // be destroyed before PeerConnection is destroyed, and at that point all
6446 // pending tasks will be cleared.
6447 sctp_invoker_->AsyncInvoke<void>(
6448 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6449 OnSctpTransportDataReceived_s(params, payload);
6450 });
6451}
6452
6453void PeerConnection::OnSctpTransportDataReceived_s(
6454 const cricket::ReceiveDataParams& params,
6455 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006456 RTC_DCHECK_RUN_ON(signaling_thread());
6457 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006458 SignalSctpDataReceived(params, payload);
6459 }
6460}
6461
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006462void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006463 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006464 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006465 sctp_invoker_->AsyncInvoke<void>(
6466 RTC_FROM_HERE, signaling_thread(),
6467 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006468 &SignalSctpClosingProcedureStartedRemotely, sid));
6469}
6470
6471void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006472 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006473 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006474 sctp_invoker_->AsyncInvoke<void>(
6475 RTC_FROM_HERE, signaling_thread(),
6476 rtc::Bind(&sigslot::signal1<int>::operator(),
6477 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006478}
6479
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006480bool PeerConnection::SetupMediaTransportForDataChannels_n(
6481 const std::string& mid) {
6482 media_transport_ = transport_controller_->GetMediaTransport(mid);
6483 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006484 RTC_LOG(LS_ERROR)
6485 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006486 return false;
6487 }
6488
6489 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6490 media_transport_->SetDataSink(this);
6491 media_transport_data_mid_ = mid;
6492 transport_controller_->SignalMediaTransportStateChanged.connect(
6493 this, &PeerConnection::OnMediaTransportStateChanged_n);
6494 // Check the initial state right away, in case transport is already writable.
6495 OnMediaTransportStateChanged_n();
6496 return true;
6497}
6498
6499void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6500 if (!media_transport_) {
6501 return;
6502 }
6503 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6504 media_transport_data_mid_.reset();
6505 media_transport_->SetDataSink(nullptr);
6506 media_transport_invoker_ = nullptr;
6507 media_transport_ = nullptr;
6508}
6509
6510void PeerConnection::OnMediaTransportStateChanged_n() {
6511 if (!media_transport_data_mid_ ||
6512 transport_controller_->GetMediaTransportState(
6513 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6514 return;
6515 }
6516 media_transport_invoker_->AsyncInvoke<void>(
6517 RTC_FROM_HERE, signaling_thread(), [this] {
6518 RTC_DCHECK_RUN_ON(signaling_thread());
6519 media_transport_ready_to_send_data_ = true;
6520 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6521 });
6522}
6523
Steve Anton75737c02017-11-06 10:37:17 -08006524// Returns false if bundle is enabled and rtcp_mux is disabled.
6525bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6526 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6527 if (!bundle_enabled)
6528 return true;
6529
6530 const cricket::ContentGroup* bundle_group =
6531 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6532 RTC_DCHECK(bundle_group != NULL);
6533
6534 const cricket::ContentInfos& contents = desc->contents();
6535 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6536 citer != contents.end(); ++citer) {
6537 const cricket::ContentInfo* content = (&*citer);
6538 RTC_DCHECK(content != NULL);
6539 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006540 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006541 if (!HasRtcpMuxEnabled(content))
6542 return false;
6543 }
6544 }
6545 // RTCP-MUX is enabled in all the contents.
6546 return true;
6547}
6548
6549bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006550 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006551}
6552
Steve Anton06817cd2018-12-18 15:55:30 -08006553static RTCError ValidateMids(const cricket::SessionDescription& description) {
6554 std::set<std::string> mids;
6555 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006556 if (content.name.empty()) {
6557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6558 "A media section is missing a MID attribute.");
6559 }
Steve Anton06817cd2018-12-18 15:55:30 -08006560 if (!mids.insert(content.name).second) {
6561 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6562 "Duplicate a=mid value '" + content.name + "'.");
6563 }
6564 }
6565 return RTCError::OK();
6566}
6567
Steve Anton8a006912017-12-04 15:25:56 -08006568RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006569 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006570 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006571 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006572 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006573 }
6574
6575 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006576 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006577 }
6578
Steve Anton3828c062017-12-06 10:34:51 -08006579 SdpType type = sdesc->GetType();
6580 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6581 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006582 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006583 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006584 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006585 }
6586
Steve Anton06817cd2018-12-18 15:55:30 -08006587 RTCError error = ValidateMids(*sdesc->description());
6588 if (!error.ok()) {
6589 return error;
6590 }
6591
Steve Anton75737c02017-11-06 10:37:17 -08006592 // Verify crypto settings.
6593 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006594 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6595 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006596 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006597 if (!crypto_error.ok()) {
6598 return crypto_error;
6599 }
Steve Anton75737c02017-11-06 10:37:17 -08006600 }
6601
6602 // Verify ice-ufrag and ice-pwd.
6603 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006604 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6605 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006606 }
6607
6608 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006609 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6610 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006611 }
6612
6613 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6614 // m-lines that do not rtcp-mux enabled.
6615
6616 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006617 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006618 // With an answer we want to compare the new answer session description with
6619 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006620 const cricket::SessionDescription* offer_desc =
6621 (source == cricket::CS_LOCAL) ? remote_description()->description()
6622 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006623 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6624 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6625 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006626 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6627 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006628 }
6629 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006630 // The re-offers should respect the order of m= sections in current
6631 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006632 // With a re-offer, either the current local or current remote descriptions
6633 // could be the most up to date, so we would like to check against both of
6634 // them if they exist. It could be the case that one of them has a 0 port
6635 // for a media section, but the other does not. This is important to check
6636 // against in the case that we are recycling an m= section.
6637 const cricket::SessionDescription* current_desc = nullptr;
6638 const cricket::SessionDescription* secondary_current_desc = nullptr;
6639 if (local_description()) {
6640 current_desc = local_description()->description();
6641 if (remote_description()) {
6642 secondary_current_desc = remote_description()->description();
6643 }
6644 } else if (remote_description()) {
6645 current_desc = remote_description()->description();
6646 }
Steve Anton75737c02017-11-06 10:37:17 -08006647 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006648 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6649 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006650 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6651 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006652 }
6653 }
6654
Steve Antonba42e992018-04-09 14:10:01 -07006655 if (IsUnifiedPlan()) {
6656 // Ensure that each audio and video media section has at most one
6657 // "StreamParams". This will return an error if receiving a session
6658 // description from a "Plan B" endpoint which adds multiple tracks of the
6659 // same type. With Unified Plan, there can only be at most one track per
6660 // media section.
6661 for (const ContentInfo& content : sdesc->description()->contents()) {
6662 const MediaContentDescription& desc = *content.description;
6663 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6664 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6665 desc.streams().size() > 1u) {
6666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6667 "Media section has more than one track specified "
6668 "with a=ssrc lines which is not supported with "
6669 "Unified Plan.");
6670 }
6671 }
6672 }
6673
Steve Anton8a006912017-12-04 15:25:56 -08006674 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006675}
6676
Steve Anton3828c062017-12-06 10:34:51 -08006677bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006678 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006679 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006680 return (state == PeerConnectionInterface::kStable) ||
6681 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006682 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006683 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006684 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6685 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6686 }
6687}
6688
Steve Anton3828c062017-12-06 10:34:51 -08006689bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006690 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006691 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006692 return (state == PeerConnectionInterface::kStable) ||
6693 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006694 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006695 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006696 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6697 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6698 }
6699}
6700
Steve Antonf8470812017-12-04 10:46:21 -08006701const char* PeerConnection::SessionErrorToString(SessionError error) const {
6702 switch (error) {
6703 case SessionError::kNone:
6704 return "ERROR_NONE";
6705 case SessionError::kContent:
6706 return "ERROR_CONTENT";
6707 case SessionError::kTransport:
6708 return "ERROR_TRANSPORT";
6709 }
6710 RTC_NOTREACHED();
6711 return "";
6712}
6713
Steve Anton75737c02017-11-06 10:37:17 -08006714std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006715 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006716 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6717 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006718 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006719}
6720
Steve Anton8e20f172018-03-06 10:55:04 -08006721void PeerConnection::ReportSdpFormatReceived(
6722 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006723 int num_audio_mlines = 0;
6724 int num_video_mlines = 0;
6725 int num_audio_tracks = 0;
6726 int num_video_tracks = 0;
6727 for (const ContentInfo& content : remote_offer.description()->contents()) {
6728 cricket::MediaType media_type = content.media_description()->type();
6729 int num_tracks = std::max(
6730 1, static_cast<int>(content.media_description()->streams().size()));
6731 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6732 num_audio_mlines += 1;
6733 num_audio_tracks += num_tracks;
6734 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6735 num_video_mlines += 1;
6736 num_video_tracks += num_tracks;
6737 }
6738 }
6739 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6740 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6741 format = kSdpFormatReceivedComplexUnifiedPlan;
6742 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6743 format = kSdpFormatReceivedComplexPlanB;
6744 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6745 format = kSdpFormatReceivedSimple;
6746 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006747 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6748 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006749}
6750
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006751void PeerConnection::NoteUsageEvent(UsageEvent event) {
6752 RTC_DCHECK_RUN_ON(signaling_thread());
6753 usage_event_accumulator_ |= static_cast<int>(event);
6754}
6755
6756void PeerConnection::ReportUsagePattern() const {
6757 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006758 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6759 usage_event_accumulator_,
6760 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006761 const int bad_bits =
6762 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6763 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6764 const int good_bits =
6765 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6766 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6767 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6768 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6769 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006770 // If called after close(), we can't report, because observer may have
6771 // been deallocated, and therefore pointer is null. Write to log instead.
6772 if (observer_) {
6773 Observer()->OnInterestingUsage(usage_event_accumulator_);
6774 } else {
6775 RTC_LOG(LS_INFO) << "Interesting usage signature "
6776 << usage_event_accumulator_
6777 << " observed after observer shutdown";
6778 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006779 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006780}
6781
Steve Anton0ffaaa22018-02-23 10:31:30 -08006782void PeerConnection::ReportNegotiatedSdpSemantics(
6783 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006784 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006785 switch (answer.description()->msid_signaling()) {
6786 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006787 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006788 break;
6789 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006790 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006791 break;
6792 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006793 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006794 break;
6795 case cricket::kMsidSignalingMediaSection |
6796 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006797 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006798 break;
6799 default:
6800 RTC_NOTREACHED();
6801 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006802 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6803 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006804}
6805
Steve Anton75737c02017-11-06 10:37:17 -08006806// We need to check the local/remote description for the Transport instead of
6807// the session, because a new Transport added during renegotiation may have
6808// them unset while the session has them set from the previous negotiation.
6809// Not doing so may trigger the auto generation of transport description and
6810// mess up DTLS identity information, ICE credential, etc.
6811bool PeerConnection::ReadyToUseRemoteCandidate(
6812 const IceCandidateInterface* candidate,
6813 const SessionDescriptionInterface* remote_desc,
6814 bool* valid) {
6815 *valid = true;
6816
6817 const SessionDescriptionInterface* current_remote_desc =
6818 remote_desc ? remote_desc : remote_description();
6819
6820 if (!current_remote_desc) {
6821 return false;
6822 }
6823
6824 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6825 size_t remote_content_size =
6826 current_remote_desc->description()->contents().size();
6827 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006828 RTC_LOG(LS_ERROR)
6829 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6830 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006831
6832 *valid = false;
6833 return false;
6834 }
6835
6836 cricket::ContentInfo content =
6837 current_remote_desc->description()->contents()[mediacontent_index];
6838
6839 const std::string transport_name = GetTransportName(content.name);
6840 if (transport_name.empty()) {
6841 return false;
6842 }
Zhi Huange830e682018-03-30 10:48:35 -07006843 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006844}
6845
6846bool PeerConnection::SrtpRequired() const {
6847 return dtls_enabled_ ||
6848 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6849}
6850
6851void PeerConnection::OnTransportControllerGatheringState(
6852 cricket::IceGatheringState state) {
6853 RTC_DCHECK(signaling_thread()->IsCurrent());
6854 if (state == cricket::kIceGatheringGathering) {
6855 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6856 } else if (state == cricket::kIceGatheringComplete) {
6857 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6858 }
6859}
6860
6861void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006862 std::map<std::string, std::set<cricket::MediaType>>
6863 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006864 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006865 if (transceiver->internal()->channel()) {
6866 const std::string& transport_name =
6867 transceiver->internal()->channel()->transport_name();
6868 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006869 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006870 }
Steve Anton75737c02017-11-06 10:37:17 -08006871 }
6872 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006873 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6874 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006875 }
Zhi Huange830e682018-03-30 10:48:35 -07006876
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006877 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006878 if (transport_name) {
6879 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006880 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006881 }
Zhi Huange830e682018-03-30 10:48:35 -07006882
Steve Antonc7b964c2018-02-01 14:39:45 -08006883 for (const auto& entry : media_types_by_transport_name) {
6884 const std::string& transport_name = entry.first;
6885 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006886 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006887 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006888 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006889 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006890 }
6891 }
6892}
6893// Walk through the ConnectionInfos to gather best connection usage
6894// for IPv4 and IPv6.
6895void PeerConnection::ReportBestConnectionState(
6896 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006897 for (const cricket::TransportChannelStats& channel_stats :
6898 stats.channel_stats) {
6899 for (const cricket::ConnectionInfo& connection_info :
6900 channel_stats.connection_infos) {
6901 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006902 continue;
6903 }
6904
Steve Antonc7b964c2018-02-01 14:39:45 -08006905 const cricket::Candidate& local = connection_info.local_candidate;
6906 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006907
6908 // Increment the counter for IceCandidatePairType.
6909 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6910 (local.type() == RELAY_PORT_TYPE &&
6911 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006912 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6913 GetIceCandidatePairCounter(local, remote),
6914 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006915 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006916 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6917 GetIceCandidatePairCounter(local, remote),
6918 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006919 } else {
6920 RTC_CHECK(0);
6921 }
Steve Anton75737c02017-11-06 10:37:17 -08006922
6923 // Increment the counter for IP type.
6924 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006925 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6926 kBestConnections_IPv4,
6927 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006928 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006929 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6930 kBestConnections_IPv6,
6931 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006932 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006933 RTC_CHECK(!local.address().hostname().empty() &&
6934 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006935 }
6936
6937 return;
6938 }
6939 }
6940}
6941
6942void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006943 const cricket::TransportStats& stats,
6944 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006945 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6946 return;
6947 }
6948
6949 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6950 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6951 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6952 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6953 return;
6954 }
6955
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006956 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6957 for (cricket::MediaType media_type : media_types) {
6958 switch (media_type) {
6959 case cricket::MEDIA_TYPE_AUDIO:
6960 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6961 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6962 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6963 break;
6964 case cricket::MEDIA_TYPE_VIDEO:
6965 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6966 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6967 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6968 break;
6969 case cricket::MEDIA_TYPE_DATA:
6970 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6971 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6972 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6973 break;
6974 default:
6975 RTC_NOTREACHED();
6976 continue;
6977 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006978 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006979 }
6980
6981 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6982 for (cricket::MediaType media_type : media_types) {
6983 switch (media_type) {
6984 case cricket::MEDIA_TYPE_AUDIO:
6985 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6986 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6987 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6988 break;
6989 case cricket::MEDIA_TYPE_VIDEO:
6990 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6991 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6992 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6993 break;
6994 case cricket::MEDIA_TYPE_DATA:
6995 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6996 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6997 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6998 break;
6999 default:
7000 RTC_NOTREACHED();
7001 continue;
7002 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007003 }
Steve Anton75737c02017-11-06 10:37:17 -08007004 }
7005}
7006
7007void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007008 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007009 RTC_DCHECK(call_);
7010 call_->OnSentPacket(sent_packet);
7011}
7012
7013const std::string PeerConnection::GetTransportName(
7014 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007015 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007016 if (channel) {
7017 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007018 }
Steve Anton6fec8802017-12-04 10:37:29 -08007019 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007020 RTC_DCHECK(sctp_mid_);
7021 if (content_name == *sctp_mid_) {
7022 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007023 }
7024 }
7025 // Return an empty string if failed to retrieve the transport name.
7026 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007027}
7028
Steve Anton6fec8802017-12-04 10:37:29 -08007029void PeerConnection::DestroyTransceiverChannel(
7030 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7031 transceiver) {
7032 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007033
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007034 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007035 if (channel) {
7036 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007037 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007038 }
7039}
7040
7041void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007042 if (rtp_data_channel_) {
7043 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007044 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007045 rtp_data_channel_ = nullptr;
7046 }
7047
7048 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7049 // grab a reference to this PeerConnection. If this is called from the
7050 // PeerConnection destructor, the RefCountedObject vtable will have already
7051 // been destroyed (since it is a subclass of PeerConnection) and using
7052 // rtc::Bind will cause "Pure virtual function called" error to appear.
7053
7054 if (sctp_transport_) {
7055 OnDataChannelDestroyed();
7056 network_thread()->Invoke<void>(RTC_FROM_HERE,
7057 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007058 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007059 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007060
7061 if (media_transport_) {
7062 OnDataChannelDestroyed();
7063 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7064 RTC_DCHECK_RUN_ON(network_thread());
7065 TeardownMediaTransportForDataChannels_n();
7066 });
7067 }
Steve Anton6fec8802017-12-04 10:37:29 -08007068}
7069
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007070void PeerConnection::DestroyChannelInterface(
7071 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007072 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007073 switch (channel->media_type()) {
7074 case cricket::MEDIA_TYPE_AUDIO:
7075 channel_manager()->DestroyVoiceChannel(
7076 static_cast<cricket::VoiceChannel*>(channel));
7077 break;
7078 case cricket::MEDIA_TYPE_VIDEO:
7079 channel_manager()->DestroyVideoChannel(
7080 static_cast<cricket::VideoChannel*>(channel));
7081 break;
7082 case cricket::MEDIA_TYPE_DATA:
7083 channel_manager()->DestroyRtpDataChannel(
7084 static_cast<cricket::RtpDataChannel*>(channel));
7085 break;
7086 default:
7087 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7088 break;
7089 }
Zhi Huange830e682018-03-30 10:48:35 -07007090}
Steve Anton6fec8802017-12-04 10:37:29 -08007091
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007092bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007093 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007094 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007095 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007096 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007097 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007098 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007099 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007100 auto base_channel = GetChannel(mid);
7101 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007102 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007103 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007104 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007105 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007106 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007107
Karl Wiberg5966c502019-02-21 23:55:09 +01007108 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007109 // Only pass media transport to call object if media transport is used
7110 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007111 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007112 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007113
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007114 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007115}
7116
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007117PeerConnectionObserver* PeerConnection::Observer() const {
7118 // In earlier production code, the pointer was not cleared on close,
7119 // which might have led to undefined behavior if the observer was not
7120 // deallocated, or strange crashes if it was.
7121 // We use CHECK in order to catch such behavior if it exists.
7122 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7123 RTC_CHECK(observer_);
7124 return observer_;
7125}
7126
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007127CryptoOptions PeerConnection::GetCryptoOptions() {
7128 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7129 // after it has been removed.
7130 return configuration_.crypto_options.has_value()
7131 ? *configuration_.crypto_options
7132 : factory_->options().crypto_options;
7133}
7134
Harald Alvestrand89061872018-01-02 14:08:34 +01007135void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007136 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007137 if (stats_collector_) {
7138 stats_collector_->ClearCachedStatsReport();
7139 }
7140}
7141
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007142void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007143 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7144 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007145}
7146
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007147void PeerConnection::UpdateNegotiationNeeded() {
7148 RTC_DCHECK_RUN_ON(signaling_thread());
7149 if (!IsUnifiedPlan()) {
7150 Observer()->OnRenegotiationNeeded();
7151 return;
7152 }
7153
7154 // If connection's [[IsClosed]] slot is true, abort these steps.
7155 if (IsClosed())
7156 return;
7157
7158 // If connection's signaling state is not "stable", abort these steps.
7159 if (signaling_state() != kStable)
7160 return;
7161
7162 // NOTE
7163 // The negotiation-needed flag will be updated once the state transitions to
7164 // "stable", as part of the steps for setting an RTCSessionDescription.
7165
7166 // If the result of checking if negotiation is needed is false, clear the
7167 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7168 // to false, and abort these steps.
7169 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7170 if (!is_negotiation_needed) {
7171 is_negotiation_needed_ = false;
7172 return;
7173 }
7174
7175 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7176 // steps.
7177 if (is_negotiation_needed_)
7178 return;
7179
7180 // Set connection's [[NegotiationNeeded]] slot to true.
7181 is_negotiation_needed_ = true;
7182
7183 // Queue a task that runs the following steps:
7184 // If connection's [[IsClosed]] slot is true, abort these steps.
7185 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7186 // Fire an event named negotiationneeded at connection.
7187 Observer()->OnRenegotiationNeeded();
7188}
7189
7190bool PeerConnection::CheckIfNegotiationIsNeeded() {
7191 RTC_DCHECK_RUN_ON(signaling_thread());
7192 // 1. If any implementation-specific negotiation is required, as described at
7193 // the start of this section, return true.
7194
7195 // 2. Let description be connection.[[CurrentLocalDescription]].
7196 const SessionDescriptionInterface* description = current_local_description();
7197 if (!description)
7198 return true;
7199
7200 // 3. If connection has created any RTCDataChannels, and no m= section in
7201 // description has been negotiated yet for data, return true.
7202 if (!sctp_data_channels_.empty()) {
7203 if (!cricket::GetFirstDataContent(description->description()->contents()))
7204 return true;
7205 }
7206
7207 // 4. For each transceiver in connection's set of transceivers, perform the
7208 // following checks:
7209 for (const auto& transceiver : transceivers_) {
7210 const ContentInfo* current_local_msection =
7211 FindTransceiverMSection(transceiver.get(), description);
7212
7213 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7214 transceiver.get(), current_remote_description());
7215
7216 // 4.3 If transceiver is stopped and is associated with an m= section,
7217 // but the associated m= section is not yet rejected in
7218 // connection.[[CurrentLocalDescription]] or
7219 // connection.[[CurrentRemoteDescription]], return true.
7220 if (transceiver->stopped()) {
7221 if (current_local_msection && !current_local_msection->rejected &&
7222 ((current_remote_msection && !current_remote_msection->rejected) ||
7223 !current_remote_msection)) {
7224 return true;
7225 }
7226 continue;
7227 }
7228
7229 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7230 // section in description, return true.
7231 if (!current_local_msection)
7232 return true;
7233
7234 const MediaContentDescription* current_local_media_description =
7235 current_local_msection->media_description();
7236 // 4.2 If transceiver isn't stopped and is associated with an m= section
7237 // in description then perform the following checks:
7238
7239 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7240 // associated m= section in description either doesn't contain a single
7241 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7242 // m= section, or the MSID values themselves, differ from what is in
7243 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7244 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7245 if (current_local_media_description->streams().size() == 0)
7246 return true;
7247
7248 std::vector<std::string> msection_msids;
7249 for (const auto& stream : current_local_media_description->streams()) {
7250 for (const std::string& msid : stream.stream_ids())
7251 msection_msids.push_back(msid);
7252 }
7253
7254 std::vector<std::string> transceiver_msids =
7255 transceiver->sender()->stream_ids();
7256 if (msection_msids.size() != transceiver_msids.size())
7257 return true;
7258
7259 absl::c_sort(transceiver_msids);
7260 absl::c_sort(msection_msids);
7261 if (transceiver_msids != msection_msids)
7262 return true;
7263 }
7264
7265 // 4.2.2 If description is of type "offer", and the direction of the
7266 // associated m= section in neither connection.[[CurrentLocalDescription]]
7267 // nor connection.[[CurrentRemoteDescription]] matches
7268 // transceiver.[[Direction]], return true.
7269 if (description->GetType() == SdpType::kOffer) {
7270 if (!current_remote_description())
7271 return true;
7272
7273 if (!current_remote_msection)
7274 return true;
7275
7276 RtpTransceiverDirection current_local_direction =
7277 current_local_media_description->direction();
7278 RtpTransceiverDirection current_remote_direction =
7279 current_remote_msection->media_description()->direction();
7280 if (transceiver->direction() != current_local_direction &&
7281 transceiver->direction() !=
7282 RtpTransceiverDirectionReversed(current_remote_direction)) {
7283 return true;
7284 }
7285 }
7286
7287 // 4.2.3 If description is of type "answer", and the direction of the
7288 // associated m= section in the description does not match
7289 // transceiver.[[Direction]] intersected with the offered direction (as
7290 // described in [JSEP] (section 5.3.1.)), return true.
7291 if (description->GetType() == SdpType::kAnswer) {
7292 if (!remote_description())
7293 return true;
7294
7295 const ContentInfo* offered_remote_msection =
7296 FindTransceiverMSection(transceiver.get(), remote_description());
7297
7298 RtpTransceiverDirection offered_direction =
7299 offered_remote_msection
7300 ? offered_remote_msection->media_description()->direction()
7301 : RtpTransceiverDirection::kInactive;
7302
7303 if (current_local_media_description->direction() !=
7304 (RtpTransceiverDirectionIntersection(
7305 transceiver->direction(),
7306 RtpTransceiverDirectionReversed(offered_direction)))) {
7307 return true;
7308 }
7309 }
7310 }
7311
7312 // If all the preceding checks were performed and true was not returned,
7313 // nothing remains to be negotiated; return false.
7314 return false;
7315}
7316
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007317} // namespace webrtc