blob: e7a1a1115798ad12af9a78ddb9a5012574068e38 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
28#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020032#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070034#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010036#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080037#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080038#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "pc/channel_manager.h"
40#include "pc/dtmf_sender.h"
41#include "pc/media_stream.h"
42#include "pc/media_stream_observer.h"
43#include "pc/remote_audio_source.h"
44#include "pc/rtp_media_utils.h"
45#include "pc/rtp_receiver.h"
46#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010047#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "pc/sctp_utils.h"
49#include "pc/sdp_utils.h"
50#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010051#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080052#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#include "rtc_base/bind.h"
54#include "rtc_base/checks.h"
55#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010056#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070062#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080073using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080074using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080075using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
78using cricket::STUN_PORT_TYPE;
79using cricket::RELAY_PORT_TYPE;
80using cricket::PRFLX_PORT_TYPE;
81
Steve Antonba818672017-11-06 10:21:57 -080082namespace webrtc {
83
Steve Anton75737c02017-11-06 10:37:17 -080084// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080088const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080096const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
Steve Anton75737c02017-11-06 10:37:17 -0800108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800110// UMA metric names.
111const char kSimulcastVersionApplyLocalDescription[] =
112 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
113const char kSimulcastVersionApplyRemoteDescription[] =
114 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
115const char kSimulcastNumberOfEncodings[] =
116 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
117const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
118
Seth Hampson845e8782018-03-02 11:34:10 -0800119static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800120static const char kDefaultAudioSenderId[] = "defaulta0";
121static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700122
zhihuang8f65cdf2016-05-06 18:40:30 -0700123// The length of RTCP CNAMEs.
124static const int kRtcpCnameLength = 16;
125
Steve Antonad182762018-09-05 20:22:40 +0000126enum {
127 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
128 MSG_SET_SESSIONDESCRIPTION_FAILED,
129 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
130 MSG_GETSTATS,
131 MSG_FREE_DATACHANNELS,
132 MSG_REPORT_USAGE_PATTERN,
133};
134
Harald Alvestrand19793842018-06-25 12:03:50 +0200135static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
136
Steve Antonad182762018-09-05 20:22:40 +0000137struct SetSessionDescriptionMsg : public rtc::MessageData {
138 explicit SetSessionDescriptionMsg(
139 webrtc::SetSessionDescriptionObserver* observer)
140 : observer(observer) {}
141
142 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
143 RTCError error;
144};
145
146struct CreateSessionDescriptionMsg : public rtc::MessageData {
147 explicit CreateSessionDescriptionMsg(
148 webrtc::CreateSessionDescriptionObserver* observer)
149 : observer(observer) {}
150
151 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
152 RTCError error;
153};
154
155struct GetStatsMsg : public rtc::MessageData {
156 GetStatsMsg(webrtc::StatsObserver* observer,
157 webrtc::MediaStreamTrackInterface* track)
158 : observer(observer), track(track) {}
159 rtc::scoped_refptr<webrtc::StatsObserver> observer;
160 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
161};
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163// Check if we can send |new_stream| on a PeerConnection.
164bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
165 webrtc::MediaStreamInterface* new_stream) {
166 if (!new_stream || !current_streams) {
167 return false;
168 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700169 if (current_streams->find(new_stream->id()) != nullptr) {
170 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100171 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700172 return false;
173 }
174 return true;
175}
176
deadbeef5e97fb52015-10-15 12:49:08 -0700177// If the direction is "recvonly" or "inactive", treat the description
178// as containing no streams.
179// See: https://code.google.com/p/webrtc/issues/detail?id=5054
180std::vector<cricket::StreamParams> GetActiveStreams(
181 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800182 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700183 ? desc->streams()
184 : std::vector<cricket::StreamParams>();
185}
186
deadbeefab9b2d12015-10-14 11:33:11 -0700187bool IsValidOfferToReceiveMedia(int value) {
188 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
189 return (value >= Options::kUndefined) &&
190 (value <= Options::kMaxOfferToReceiveMedia);
191}
192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800194void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700195 const std::vector<rtc::scoped_refptr<
196 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700197 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200198 cricket::MediaDescriptionOptions* video_media_description_options,
199 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700200 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700201 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
202 if (audio_media_description_options) {
203 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700204 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700205 }
206 } else {
207 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
208 if (video_media_description_options) {
209 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800210 sender->id(), sender->internal()->stream_ids(), {},
211 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700212 }
213 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700214 }
zhihuang1c378ed2017-08-17 14:10:50 -0700215}
olka3c747662017-08-17 06:50:32 -0700216
zhihuang1c378ed2017-08-17 14:10:50 -0700217// Add options to |session_options| from |rtp_data_channels|.
218void AddRtpDataChannelOptions(
219 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
220 rtp_data_channels,
221 cricket::MediaDescriptionOptions* data_media_description_options) {
222 if (!data_media_description_options) {
223 return;
224 }
deadbeefab9b2d12015-10-14 11:33:11 -0700225 // Check for data channels.
226 for (const auto& kv : rtp_data_channels) {
227 const DataChannel* channel = kv.second;
228 if (channel->state() == DataChannel::kConnecting ||
229 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700230 // Legacy RTP data channels are signaled with the track/stream ID set to
231 // the data channel's label.
232 data_media_description_options->AddRtpDataChannel(channel->label(),
233 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700234 }
235 }
236}
237
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238uint32_t ConvertIceTransportTypeToCandidateFilter(
239 PeerConnectionInterface::IceTransportsType type) {
240 switch (type) {
241 case PeerConnectionInterface::kNone:
242 return cricket::CF_NONE;
243 case PeerConnectionInterface::kRelay:
244 return cricket::CF_RELAY;
245 case PeerConnectionInterface::kNoHost:
246 return (cricket::CF_ALL & ~cricket::CF_HOST);
247 case PeerConnectionInterface::kAll:
248 return cricket::CF_ALL;
249 default:
nissec80e7412017-01-11 05:56:46 -0800250 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700251 }
252 return cricket::CF_NONE;
253}
254
deadbeef293e9262017-01-11 12:28:30 -0800255// Helper to set an error and return from a method.
256bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
257 if (error) {
258 error->set_type(type);
259 }
260 return type == webrtc::RTCErrorType::NONE;
261}
262
Steve Anton038834f2017-07-14 15:59:59 -0700263bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700264 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700265 if (error_out) {
266 *error_out = std::move(error);
267 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700269}
270
Steve Antonba818672017-11-06 10:21:57 -0800271std::string GetSignalingStateString(
272 PeerConnectionInterface::SignalingState state) {
273 switch (state) {
274 case PeerConnectionInterface::kStable:
275 return "kStable";
276 case PeerConnectionInterface::kHaveLocalOffer:
277 return "kHaveLocalOffer";
278 case PeerConnectionInterface::kHaveLocalPrAnswer:
279 return "kHavePrAnswer";
280 case PeerConnectionInterface::kHaveRemoteOffer:
281 return "kHaveRemoteOffer";
282 case PeerConnectionInterface::kHaveRemotePrAnswer:
283 return "kHaveRemotePrAnswer";
284 case PeerConnectionInterface::kClosed:
285 return "kClosed";
286 }
287 RTC_NOTREACHED();
288 return "";
289}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290
Steve Anton75737c02017-11-06 10:37:17 -0800291IceCandidatePairType GetIceCandidatePairCounter(
292 const cricket::Candidate& local,
293 const cricket::Candidate& remote) {
294 const auto& l = local.type();
295 const auto& r = remote.type();
296 const auto& host = LOCAL_PORT_TYPE;
297 const auto& srflx = STUN_PORT_TYPE;
298 const auto& relay = RELAY_PORT_TYPE;
299 const auto& prflx = PRFLX_PORT_TYPE;
300 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800301 bool local_hostname =
302 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
303 bool remote_hostname = !remote.address().hostname().empty() &&
304 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800305 bool local_private = IPIsPrivate(local.address().ipaddr());
306 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800307 if (local_hostname) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostNameHostName;
310 } else if (remote_private) {
311 return kIceCandidatePairHostNameHostPrivate;
312 } else {
313 return kIceCandidatePairHostNameHostPublic;
314 }
315 } else if (local_private) {
316 if (remote_hostname) {
317 return kIceCandidatePairHostPrivateHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPrivateHostPrivate;
320 } else {
321 return kIceCandidatePairHostPrivateHostPublic;
322 }
323 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800324 if (remote_hostname) {
325 return kIceCandidatePairHostPublicHostName;
326 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800327 return kIceCandidatePairHostPublicHostPrivate;
328 } else {
329 return kIceCandidatePairHostPublicHostPublic;
330 }
331 }
332 }
333 if (l == host && r == srflx)
334 return kIceCandidatePairHostSrflx;
335 if (l == host && r == relay)
336 return kIceCandidatePairHostRelay;
337 if (l == host && r == prflx)
338 return kIceCandidatePairHostPrflx;
339 if (l == srflx && r == host)
340 return kIceCandidatePairSrflxHost;
341 if (l == srflx && r == srflx)
342 return kIceCandidatePairSrflxSrflx;
343 if (l == srflx && r == relay)
344 return kIceCandidatePairSrflxRelay;
345 if (l == srflx && r == prflx)
346 return kIceCandidatePairSrflxPrflx;
347 if (l == relay && r == host)
348 return kIceCandidatePairRelayHost;
349 if (l == relay && r == srflx)
350 return kIceCandidatePairRelaySrflx;
351 if (l == relay && r == relay)
352 return kIceCandidatePairRelayRelay;
353 if (l == relay && r == prflx)
354 return kIceCandidatePairRelayPrflx;
355 if (l == prflx && r == host)
356 return kIceCandidatePairPrflxHost;
357 if (l == prflx && r == srflx)
358 return kIceCandidatePairPrflxSrflx;
359 if (l == prflx && r == relay)
360 return kIceCandidatePairPrflxRelay;
361 return kIceCandidatePairMax;
362}
363
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800364// Logic to decide if an m= section can be recycled. This means that the new
365// m= section is not rejected, but the old local or remote m= section is
366// rejected. |old_content_one| and |old_content_two| refer to the m= section
367// of the old remote and old local descriptions in no particular order.
368// We need to check both the old local and remote because either
369// could be the most current from the latest negotation.
370bool IsMediaSectionBeingRecycled(SdpType type,
371 const ContentInfo& content,
372 const ContentInfo* old_content_one,
373 const ContentInfo* old_content_two) {
374 return type == SdpType::kOffer && !content.rejected &&
375 ((old_content_one && old_content_one->rejected) ||
376 (old_content_two && old_content_two->rejected));
377}
378
Steve Anton75737c02017-11-06 10:37:17 -0800379// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380// |current_desc|. The number of m= sections in |new_desc| should be no
381// less than |current_desc|. In the case of checking an answer's
382// |new_desc|, the |current_desc| is the last offer that was set as the
383// local or remote. In the case of checking an offer's |new_desc| we
384// check against the local and remote descriptions stored from the last
385// negotiation, because either of these could be the most up to date for
386// possible rejected m sections. These are the |current_desc| and
387// |secondary_current_desc|.
388bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
389 const SessionDescription* secondary_current_desc,
390 const SessionDescription& new_desc,
391 const SdpType type) {
392 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800393 return false;
394 }
395
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
397 const cricket::ContentInfo* secondary_content_info = nullptr;
398 if (secondary_current_desc &&
399 i < secondary_current_desc->contents().size()) {
400 secondary_content_info = &secondary_current_desc->contents()[i];
401 }
402 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
403 &current_desc.contents()[i],
404 secondary_content_info)) {
405 // For new offer descriptions, if the media section can be recycled, it's
406 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800407 continue;
408 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800409 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800410 return false;
411 }
412 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 new_desc.contents()[i].media_description();
414 const MediaContentDescription* current_desc_mdesc =
415 current_desc.contents()[i].media_description();
416 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800417 return false;
418 }
419 }
420 return true;
421}
422
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800423bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
424 const SessionDescription& desc2) {
425 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800426}
427
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700428void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
429 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200430 // Array of structs needed to map {KeyExchangeProtocolType,
431 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
432 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
433 static constexpr struct {
434 KeyExchangeProtocolType protocol_type;
435 cricket::MediaType media_type;
436 KeyExchangeProtocolMedia protocol_media;
437 } kEnumCounterKeyProtocolMediaMap[] = {
438 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
439 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
440 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
441 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
443 kEnumCounterKeyProtocolMediaTypeDtlsData},
444 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
445 kEnumCounterKeyProtocolMediaTypeSdesAudio},
446 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
447 kEnumCounterKeyProtocolMediaTypeSdesVideo},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
449 kEnumCounterKeyProtocolMediaTypeSdesData},
450 };
451
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
453 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100454
Mirko Bonadeiab499822018-09-11 10:43:20 +0200455 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
456 if (i.protocol_type == protocol_type && i.media_type == media_type) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
458 i.protocol_media,
459 kEnumCounterKeyProtocolMediaTypeMax);
460 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100461 }
462}
463
Harald Alvestrand76829d72018-07-18 23:24:36 +0200464void NoteAddIceCandidateResult(int result) {
465 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
466 kAddIceCandidateMax);
467}
468
Steve Anton75737c02017-11-06 10:37:17 -0800469// Checks that each non-rejected content has SDES crypto keys or a DTLS
470// fingerprint, unless it's in a BUNDLE group, in which case only the
471// BUNDLE-tag section (first media section/description in the BUNDLE group)
472// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
473// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
474// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700475RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100482 // Note what media is used with each crypto protocol, for all sections.
483 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
484 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700485 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800486 const std::string& mid = content_info.name;
487 if (bundle && bundle->HasContentName(mid) &&
488 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800489 // This isn't the first media section in the BUNDLE group, so it's not
490 // required to have crypto attributes, since only the crypto attributes
491 // from the first section actually get used.
492 continue;
493 }
494
495 // If the content isn't rejected or bundled into another m= section, crypto
496 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800498 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800499 if (!media || !tinfo) {
500 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 if (dtls_enabled) {
504 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
506 << "Session description must have DTLS fingerprint if "
507 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800508 return RTCError(RTCErrorType::INVALID_PARAMETER,
509 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800510 }
511 } else {
512 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100513 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800514 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800515 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800516 }
517 }
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800520}
521
522// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
523// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
524// media section/description in the BUNDLE group) needs a ufrag and pwd.
525bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
526 const cricket::ContentGroup* bundle =
527 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800528 for (const cricket::ContentInfo& content_info : desc->contents()) {
529 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800530 continue;
531 }
Steve Anton8a006912017-12-04 15:25:56 -0800532 const std::string& mid = content_info.name;
533 if (bundle && bundle->HasContentName(mid) &&
534 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800535 // This isn't the first media section in the BUNDLE group, so it's not
536 // required to have ufrag/password, since only the ufrag/password from
537 // the first section actually get used.
538 continue;
539 }
540
541 // If the content isn't rejected or bundled into another m= section,
542 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800543 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800544 if (!tinfo) {
545 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800547 return false;
548 }
549 if (tinfo->description.ice_ufrag.empty() ||
550 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100551 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800552 return false;
553 }
554 }
555 return true;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Get the SCTP port out of a SessionDescription.
559// Return -1 if not found.
560int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800561 const cricket::DataContentDescription* data_desc =
562 GetFirstDataContentDescription(session_description);
563 RTC_DCHECK(data_desc);
564 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800565 return -1;
566 }
Steve Anton75737c02017-11-06 10:37:17 -0800567 std::string value;
568 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
569 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800570 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800571 if (!codec.Matches(match_pattern)) {
572 continue;
573 }
574 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
575 return rtc::FromString<int>(value);
576 }
577 }
578 return -1;
579}
580
Steve Anton75737c02017-11-06 10:37:17 -0800581// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
582bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
583 const SessionDescriptionInterface* new_desc,
584 const std::string& content_name) {
585 if (!old_desc) {
586 return false;
587 }
588 const SessionDescription* new_sd = new_desc->description();
589 const SessionDescription* old_sd = old_desc->description();
590 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
591 if (!cinfo || cinfo->rejected) {
592 return false;
593 }
594 // If the content isn't rejected, check if ufrag and password has changed.
595 const cricket::TransportDescription* new_transport_desc =
596 new_sd->GetTransportDescriptionByName(content_name);
597 const cricket::TransportDescription* old_transport_desc =
598 old_sd->GetTransportDescriptionByName(content_name);
599 if (!new_transport_desc || !old_transport_desc) {
600 // No transport description exists. This is not an ICE restart.
601 return false;
602 }
603 if (cricket::IceCredentialsChanged(
604 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
605 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100606 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
607 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800608 return true;
609 }
610 return false;
611}
612
Steve Anton80dd7b52018-02-16 17:08:42 -0800613// Generates a string error message for SetLocalDescription/SetRemoteDescription
614// from an RTCError.
615std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
616 SdpType type,
617 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200618 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800619 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
620 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200621 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800622}
623
Seth Hampson5b4f0752018-04-02 16:31:36 -0700624std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
625 std::string output = "streams=[";
626 const char* separator = "";
627 for (const auto& stream_id : stream_ids) {
628 output.append(separator).append(stream_id);
629 separator = ", ";
630 }
631 output.append("]");
632 return output;
633}
634
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200635absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700636 int rtc_configuration_parameter) {
637 if (rtc_configuration_parameter ==
638 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200639 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700640 }
641 return rtc_configuration_parameter;
642}
643
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800644cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
645 switch (type) {
646 case DataMessageType::kText:
647 return cricket::DMT_TEXT;
648 case DataMessageType::kBinary:
649 return cricket::DMT_BINARY;
650 case DataMessageType::kControl:
651 return cricket::DMT_CONTROL;
652 default:
653 return cricket::DMT_NONE;
654 }
655 return cricket::DMT_NONE;
656}
657
658DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
659 switch (type) {
660 case cricket::DMT_TEXT:
661 return DataMessageType::kText;
662 case cricket::DMT_BINARY:
663 return DataMessageType::kBinary;
664 case cricket::DMT_CONTROL:
665 return DataMessageType::kControl;
666 case cricket::DMT_NONE:
667 default:
668 RTC_NOTREACHED();
669 }
670 return DataMessageType::kControl;
671}
672
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800673void ReportSimulcastApiVersion(const char* name,
674 const SessionDescription& session) {
675 bool has_legacy = false;
676 bool has_spec_compliant = false;
677 for (const ContentInfo& content : session.contents()) {
678 if (!content.description) {
679 continue;
680 }
681 has_spec_compliant |= content.description->HasSimulcast();
682 for (const StreamParams& sp : content.description->streams()) {
683 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
684 }
685 }
686
687 if (has_legacy) {
688 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
689 kSimulcastApiVersionMax);
690 }
691 if (has_spec_compliant) {
692 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
693 kSimulcastApiVersionMax);
694 }
695 if (!has_legacy && !has_spec_compliant) {
696 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
697 kSimulcastApiVersionMax);
698 }
699}
700
Steve Anton75737c02017-11-06 10:37:17 -0800701} // namespace
702
Henrik Boström31638672017-11-23 17:48:32 +0100703// Upon completion, posts a task to execute the callback of the
704// SetSessionDescriptionObserver asynchronously on the same thread. At this
705// point, the state of the peer connection might no longer reflect the effects
706// of the SetRemoteDescription operation, as the peer connection could have been
707// modified during the post.
708// TODO(hbos): Remove this class once we remove the version of
709// PeerConnectionInterface::SetRemoteDescription() that takes a
710// SetSessionDescriptionObserver as an argument.
711class PeerConnection::SetRemoteDescriptionObserverAdapter
712 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
713 public:
714 SetRemoteDescriptionObserverAdapter(
715 rtc::scoped_refptr<PeerConnection> pc,
716 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
717 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
718
719 // SetRemoteDescriptionObserverInterface implementation.
720 void OnSetRemoteDescriptionComplete(RTCError error) override {
721 if (error.ok())
722 pc_->PostSetSessionDescriptionSuccess(wrapper_);
723 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100724 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100725 }
726
727 private:
728 rtc::scoped_refptr<PeerConnection> pc_;
729 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
730};
731
deadbeef293e9262017-01-11 12:28:30 -0800732bool PeerConnectionInterface::RTCConfiguration::operator==(
733 const PeerConnectionInterface::RTCConfiguration& o) const {
734 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700735 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800736 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000737 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700738 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800739 BundlePolicy bundle_policy;
740 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700741 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
742 int ice_candidate_pool_size;
743 bool disable_ipv6;
744 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700745 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100746 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700747 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200748 absl::optional<int> screencast_min_bitrate;
749 absl::optional<bool> combined_audio_video_bwe;
750 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800751 TcpCandidatePolicy tcp_candidate_policy;
752 CandidateNetworkPolicy candidate_network_policy;
753 int audio_jitter_buffer_max_packets;
754 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100755 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100756 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800757 int ice_connection_receiving_timeout;
758 int ice_backup_candidate_pair_ping_interval;
759 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800760 bool prioritize_most_likely_ice_candidate_pairs;
761 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800762 bool prune_turn_ports;
763 bool presume_writable_when_fully_relayed;
764 bool enable_ice_renomination;
765 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200766 absl::optional<int> ice_check_interval_strong_connectivity;
767 absl::optional<int> ice_check_interval_weak_connectivity;
768 absl::optional<int> ice_check_min_interval;
769 absl::optional<int> ice_unwritable_timeout;
770 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800771 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200772 absl::optional<int> stun_candidate_keepalive_interval;
773 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200774 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800775 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200776 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700777 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700778 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700779 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700780 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100781 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800782 };
783 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
784 "Did you add something to RTCConfiguration and forget to "
785 "update operator==?");
786 return type == o.type && servers == o.servers &&
787 bundle_policy == o.bundle_policy &&
788 rtcp_mux_policy == o.rtcp_mux_policy &&
789 tcp_candidate_policy == o.tcp_candidate_policy &&
790 candidate_network_policy == o.candidate_network_policy &&
791 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
792 audio_jitter_buffer_fast_accelerate ==
793 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100794 audio_jitter_buffer_min_delay_ms ==
795 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100796 audio_jitter_buffer_enable_rtx_handling ==
797 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800798 ice_connection_receiving_timeout ==
799 o.ice_connection_receiving_timeout &&
800 ice_backup_candidate_pair_ping_interval ==
801 o.ice_backup_candidate_pair_ping_interval &&
802 continual_gathering_policy == o.continual_gathering_policy &&
803 certificates == o.certificates &&
804 prioritize_most_likely_ice_candidate_pairs ==
805 o.prioritize_most_likely_ice_candidate_pairs &&
806 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800807 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700808 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100809 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800810 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800811 screencast_min_bitrate == o.screencast_min_bitrate &&
812 combined_audio_video_bwe == o.combined_audio_video_bwe &&
813 enable_dtls_srtp == o.enable_dtls_srtp &&
814 ice_candidate_pool_size == o.ice_candidate_pool_size &&
815 prune_turn_ports == o.prune_turn_ports &&
816 presume_writable_when_fully_relayed ==
817 o.presume_writable_when_fully_relayed &&
818 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800819 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800820 ice_check_interval_strong_connectivity ==
821 o.ice_check_interval_strong_connectivity &&
822 ice_check_interval_weak_connectivity ==
823 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700824 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700825 ice_unwritable_timeout == o.ice_unwritable_timeout &&
826 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800827 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800828 stun_candidate_keepalive_interval ==
829 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200830 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800831 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800832 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700833 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700834 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700835 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700836 use_media_transport_for_data_channels ==
837 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100838 crypto_options == o.crypto_options &&
839 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800840}
841
842bool PeerConnectionInterface::RTCConfiguration::operator!=(
843 const PeerConnectionInterface::RTCConfiguration& o) const {
844 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800845}
846
zhihuang8f65cdf2016-05-06 18:40:30 -0700847// Generate a RTCP CNAME when a PeerConnection is created.
848std::string GenerateRtcpCname() {
849 std::string cname;
850 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100851 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800852 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700853 }
854 return cname;
855}
856
zhihuang1c378ed2017-08-17 14:10:50 -0700857bool ValidateOfferAnswerOptions(
858 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
859 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
860 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700861}
862
zhihuang1c378ed2017-08-17 14:10:50 -0700863// From |rtc_options|, fill parts of |session_options| shared by all generated
864// m= sections (in other words, nothing that involves a map/array).
865void ExtractSharedMediaSessionOptions(
866 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
867 cricket::MediaSessionOptions* session_options) {
868 session_options->vad_enabled = rtc_options.voice_activity_detection;
869 session_options->bundle_enabled = rtc_options.use_rtp_mux;
870}
zhihuanga77e6bb2017-08-14 18:17:48 -0700871
zhihuang38ede132017-06-15 12:52:32 -0700872PeerConnection::PeerConnection(PeerConnectionFactory* factory,
873 std::unique_ptr<RtcEventLog> event_log,
874 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700876 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100877 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700878 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700879 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700880 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100881 call_(std::move(call)),
882 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883
884PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100885 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800886 RTC_DCHECK_RUN_ON(signaling_thread());
887
Steve Anton8af21862017-12-15 11:20:13 -0800888 // Need to stop transceivers before destroying the stats collector because
889 // AudioRtpSender has a reference to the StatsCollector it will update when
890 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100891 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800892 transceiver->Stop();
893 }
Steve Anton4171afb2017-11-20 10:20:22 -0800894
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700895 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800896 if (stats_collector_) {
897 stats_collector_->WaitForPendingRequest();
898 stats_collector_ = nullptr;
899 }
Steve Anton75737c02017-11-06 10:37:17 -0800900
Steve Anton8af21862017-12-15 11:20:13 -0800901 // Don't destroy BaseChannels until after stats has been cleaned up so that
902 // the last stats request can still read from the channels.
903 DestroyAllChannels();
904
Mirko Bonadei675513b2017-11-09 11:09:25 +0100905 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800906
907 webrtc_session_desc_factory_.reset();
908 sctp_invoker_.reset();
909 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800910 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800911 transport_controller_.reset();
912
deadbeef91dd5672016-05-18 16:55:30 -0700913 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100914 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
915 RTC_DCHECK_RUN_ON(network_thread());
916 port_allocator_.reset();
917 });
eladalon248fd4f2017-09-06 05:18:15 -0700918 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700919 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100920 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700921 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800922 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700923 event_log_.reset();
924 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925}
926
Steve Anton8af21862017-12-15 11:20:13 -0800927void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800928 // Destroy video channels first since they may have a pointer to a voice
929 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100930 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800931 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800932 DestroyTransceiverChannel(transceiver);
933 }
934 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100935 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800936 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800937 DestroyTransceiverChannel(transceiver);
938 }
939 }
940 DestroyDataChannel();
941}
942
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000944 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700945 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100946 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100947 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100948 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700949
950 RTCError config_error = ValidateConfiguration(configuration);
951 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100952 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700953 return false;
954 }
955
Benjamin Wrightcab58882018-05-02 15:12:47 -0700956 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100957 RTC_LOG(LS_ERROR)
958 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100959 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800960 return false;
961 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200962
Benjamin Wrightcab58882018-05-02 15:12:47 -0700963 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800964 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100965 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100966 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800967 return false;
968 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700969
Benjamin Wrightcab58882018-05-02 15:12:47 -0700970 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700971 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700972 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700973 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800974
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200975 cricket::ServerAddresses stun_servers;
976 std::vector<cricket::RelayServerConfig> turn_servers;
977
978 RTCErrorType parse_error =
979 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
980 if (parse_error != RTCErrorType::NONE) {
981 return false;
982 }
983
deadbeef91dd5672016-05-18 16:55:30 -0700984 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700985 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100986 const auto pa_result =
987 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200988 RTC_FROM_HERE,
989 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100990 stun_servers, turn_servers, configuration));
991
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200992 // If initialization was successful, note if STUN or TURN servers
993 // were supplied.
994 if (!stun_servers.empty()) {
995 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
996 }
997 if (!turn_servers.empty()) {
998 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
999 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001001 // Send information about IPv4/IPv6 status.
1002 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001003 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001004 address_family = kPeerConnection_IPv6;
1005 } else {
1006 address_family = kPeerConnection_IPv4;
1007 }
1008 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1009 kPeerConnectionAddressFamilyCounter_Max);
1010
Zhi Huange830e682018-03-30 10:48:35 -07001011 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1012
Steve Anton75737c02017-11-06 10:37:17 -08001013 // RFC 3264: The numeric value of the session id and version in the
1014 // o line MUST be representable with a "64 bit signed integer".
1015 // Due to this constraint session id |session_id_| is max limited to
1016 // LLONG_MAX.
1017 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001018 JsepTransportController::Config config;
1019 config.redetermine_role_on_ice_restart =
1020 configuration.redetermine_role_on_ice_restart;
1021 config.ssl_max_version = factory_->options().ssl_max_version;
1022 config.disable_encryption = options.disable_encryption;
1023 config.bundle_policy = configuration.bundle_policy;
1024 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001025 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1026 // stub.
1027 config.crypto_options = configuration.crypto_options.has_value()
1028 ? *configuration.crypto_options
1029 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001030 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001031 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001032#if defined(ENABLE_EXTERNAL_AUTH)
1033 config.enable_external_auth = true;
1034#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001035 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001036
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001037 if (configuration.use_media_transport ||
1038 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001039 if (!factory_->media_transport_factory()) {
1040 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001041 << "PeerConnecton is initialized with use_media_transport = true or "
1042 << "use_media_transport_for_data_channels = true "
1043 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001044 return false;
1045 }
1046
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001047 if (configuration.use_media_transport ||
1048 configuration.use_media_transport_for_data_channels) {
1049 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1050 // RTP media transport is introduced. But until then, we require SDES to
1051 // be enabled.
1052 if (configuration.enable_dtls_srtp.has_value() &&
1053 configuration.enable_dtls_srtp.value()) {
1054 RTC_LOG(LS_WARNING)
1055 << "When media transport is used, SDES must be enabled. Set "
1056 "configuration.enable_dtls_srtp to false. use_media_transport="
1057 << configuration.use_media_transport
1058 << ", use_media_transport_for_data_channels="
1059 << configuration.use_media_transport_for_data_channels;
1060 return false;
1061 }
1062 }
1063
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001064 config.use_media_transport_for_media = configuration.use_media_transport;
1065 config.use_media_transport_for_data_channels =
1066 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001067 config.media_transport_factory = factory_->media_transport_factory();
1068 }
1069
Zhi Huange830e682018-03-30 10:48:35 -07001070 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001071 signaling_thread(), network_thread(), port_allocator_.get(),
1072 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001073 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001074 this, &PeerConnection::OnTransportControllerConnectionState);
1075 transport_controller_->SignalStandardizedIceConnectionState.connect(
1076 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001077 transport_controller_->SignalConnectionState.connect(
1078 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001079 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001080 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001081 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001082 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001083 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001084 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1085 transport_controller_->SignalDtlsHandshakeError.connect(
1086 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1087
1088 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001089
deadbeefab9b2d12015-10-14 11:33:11 -07001090 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001091 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092
Steve Antonba818672017-11-06 10:21:57 -08001093 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001094 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001095
Steve Anton75737c02017-11-06 10:37:17 -08001096 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1097 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1098 if (!configuration.certificates.empty()) {
1099 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1100 // just picking the first one. The decision should be made based on the DTLS
1101 // handshake. The DTLS negotiations need to know about all certificates.
1102 certificate = configuration.certificates[0];
1103 }
1104
Steve Antond25da372017-11-06 14:50:29 -08001105 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001106
1107 if (options.disable_encryption) {
1108 dtls_enabled_ = false;
1109 } else {
1110 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001111 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001112 // |configuration| can override the default |dtls_enabled_| value.
1113 if (configuration.enable_dtls_srtp) {
1114 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1115 }
1116 }
1117
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001118 if (configuration.use_media_transport_for_data_channels) {
1119 if (configuration.enable_rtp_data_channel) {
1120 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1121 "use_media_transport_for_data_channels are "
1122 "incompatible and cannot both be set to true";
1123 return false;
1124 }
1125 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1126 } else if (configuration.enable_rtp_data_channel) {
1127 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1128 // set. It takes precendence over the disable_sctp_data_channels
1129 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001130 data_channel_type_ = cricket::DCT_RTP;
1131 } else {
1132 // DTLS has to be enabled to use SCTP.
1133 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1134 data_channel_type_ = cricket::DCT_SCTP;
1135 }
1136 }
1137
1138 video_options_.screencast_min_bitrate_kbps =
1139 configuration.screencast_min_bitrate;
1140 audio_options_.combined_audio_video_bwe =
1141 configuration.combined_audio_video_bwe;
1142
1143 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001144 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001145
1146 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001147 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001148
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001149 audio_options_.audio_jitter_buffer_min_delay_ms =
1150 configuration.audio_jitter_buffer_min_delay_ms;
1151
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001152 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1153 configuration.audio_jitter_buffer_enable_rtx_handling;
1154
Steve Anton75737c02017-11-06 10:37:17 -08001155 // Whether the certificate generator/certificate is null or not determines
1156 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1157 // the right instructions by clearing the variables if needed.
1158 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001159 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001160 certificate = nullptr;
1161 } else if (certificate) {
1162 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001163 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001164 }
1165
1166 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1167 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001168 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001169 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1170 this, &PeerConnection::OnCertificateReady);
1171
1172 if (options.disable_encryption) {
1173 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1174 }
1175
1176 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001177 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001178 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001179
Steve Anton4171afb2017-11-20 10:20:22 -08001180 // Add default audio/video transceivers for Plan B SDP.
1181 if (!IsUnifiedPlan()) {
1182 transceivers_.push_back(
1183 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1184 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1185 transceivers_.push_back(
1186 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1187 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1188 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001189 int delay_ms =
1190 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001191 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1192 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193 return true;
1194}
1195
Steve Anton038834f2017-07-14 15:59:59 -07001196RTCError PeerConnection::ValidateConfiguration(
1197 const RTCConfiguration& config) const {
1198 if (config.ice_regather_interval_range &&
1199 config.continual_gathering_policy == GATHER_ONCE) {
1200 return RTCError(RTCErrorType::INVALID_PARAMETER,
1201 "ice_regather_interval_range specified but continual "
1202 "gathering policy is GATHER_ONCE");
1203 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001204 auto result =
1205 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1206 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001207}
1208
Yves Gerey665174f2018-06-19 15:03:05 +02001209rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001210 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001211 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1212 "Plan SdpSemantics. Please use GetSenders "
1213 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001214 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001215}
1216
Yves Gerey665174f2018-06-19 15:03:05 +02001217rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001218 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001219 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1220 "Plan SdpSemantics. Please use GetReceivers "
1221 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001222 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223}
1224
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001225bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001226 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001227 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1228 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001229 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230 if (IsClosed()) {
1231 return false;
1232 }
deadbeefab9b2d12015-10-14 11:33:11 -07001233 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001234 return false;
1235 }
deadbeefab9b2d12015-10-14 11:33:11 -07001236
1237 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001238 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1239 observer->SignalAudioTrackAdded.connect(this,
1240 &PeerConnection::OnAudioTrackAdded);
1241 observer->SignalAudioTrackRemoved.connect(
1242 this, &PeerConnection::OnAudioTrackRemoved);
1243 observer->SignalVideoTrackAdded.connect(this,
1244 &PeerConnection::OnVideoTrackAdded);
1245 observer->SignalVideoTrackRemoved.connect(
1246 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001247 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001248
deadbeefab9b2d12015-10-14 11:33:11 -07001249 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001250 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001251 }
1252 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001253 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001254 }
1255
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001256 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001257 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 return true;
1259}
1260
1261void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001262 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001263 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1264 "Plan SdpSemantics. Please use RemoveTrack "
1265 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001266 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001267 if (!IsClosed()) {
1268 for (const auto& track : local_stream->GetAudioTracks()) {
1269 RemoveAudioTrack(track.get(), local_stream);
1270 }
1271 for (const auto& track : local_stream->GetVideoTracks()) {
1272 RemoveVideoTrack(track.get(), local_stream);
1273 }
deadbeefab9b2d12015-10-14 11:33:11 -07001274 }
deadbeefab9b2d12015-10-14 11:33:11 -07001275 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001276 stream_observers_.erase(
1277 std::remove_if(
1278 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001279 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001280 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001281 }),
1282 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001283
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284 if (IsClosed()) {
1285 return;
1286 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001287 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288}
1289
Steve Anton2d6c76a2018-01-05 17:10:52 -08001290RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001291 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001292 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001293 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001294 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001295 if (!track) {
1296 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1297 }
1298 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1299 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1300 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1301 "Track has invalid kind: " + track->kind());
1302 }
Steve Antonf9381f02017-12-14 10:23:57 -08001303 if (IsClosed()) {
1304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1305 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001306 }
Steve Anton4171afb2017-11-20 10:20:22 -08001307 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001308 LOG_AND_RETURN_ERROR(
1309 RTCErrorType::INVALID_PARAMETER,
1310 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001311 }
Steve Antonf9381f02017-12-14 10:23:57 -08001312 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001313 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1314 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001315 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001316 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001317 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001318 }
1319 return sender_or_error;
1320}
deadbeefe1f9d832016-01-14 15:35:42 -08001321
Steve Antonf9381f02017-12-14 10:23:57 -08001322RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1323PeerConnection::AddTrackPlanB(
1324 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001325 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001326 if (stream_ids.size() > 1u) {
1327 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1328 "AddTrack with more than one stream is not "
1329 "supported with Plan B semantics.");
1330 }
1331 std::vector<std::string> adjusted_stream_ids = stream_ids;
1332 if (adjusted_stream_ids.empty()) {
1333 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1334 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001335 cricket::MediaType media_type =
1336 (track->kind() == MediaStreamTrackInterface::kAudioKind
1337 ? cricket::MEDIA_TYPE_AUDIO
1338 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001339 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001340 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001341 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001342 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001343 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001344 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001345 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001346 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001347 if (sender_info) {
1348 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001349 }
Steve Antonf9381f02017-12-14 10:23:57 -08001350 } else {
1351 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001352 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001353 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001354 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001355 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001356 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001357 if (sender_info) {
1358 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001359 }
deadbeefe1f9d832016-01-14 15:35:42 -08001360 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001361 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001362}
deadbeefe1f9d832016-01-14 15:35:42 -08001363
Steve Antonf9381f02017-12-14 10:23:57 -08001364RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1365PeerConnection::AddTrackUnifiedPlan(
1366 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001367 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001368 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1369 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001370 RTC_LOG(LS_INFO) << "Reusing an existing "
1371 << cricket::MediaTypeToString(transceiver->media_type())
1372 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001373 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001374 transceiver->internal()->set_direction(
1375 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001376 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001377 transceiver->internal()->set_direction(
1378 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001379 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001380 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001381 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001382 } else {
1383 cricket::MediaType media_type =
1384 (track->kind() == MediaStreamTrackInterface::kAudioKind
1385 ? cricket::MEDIA_TYPE_AUDIO
1386 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001387 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1388 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001389 std::string sender_id = track->id();
1390 // Avoid creating a sender with an existing ID by generating a random ID.
1391 // This can happen if this is the second time AddTrack has created a sender
1392 // for this track.
1393 if (FindSenderById(sender_id)) {
1394 sender_id = rtc::CreateRandomUuid();
1395 }
Florent Castelli892acf02018-10-01 22:47:20 +02001396 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001397 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1398 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001399 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001400 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001401 }
Steve Antonf9381f02017-12-14 10:23:57 -08001402 return transceiver->sender();
1403}
1404
1405rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1406PeerConnection::FindFirstTransceiverForAddedTrack(
1407 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1408 RTC_DCHECK(track);
1409 for (auto transceiver : transceivers_) {
1410 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001411 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001412 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001413 !transceiver->internal()->has_ever_been_used_to_send() &&
1414 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001415 return transceiver;
1416 }
1417 }
1418 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001419}
1420
1421bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1422 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001423 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001424}
1425
Steve Anton24db5732018-07-23 10:27:33 -07001426RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001427 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001428 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001429 if (!sender) {
1430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1431 }
deadbeefe1f9d832016-01-14 15:35:42 -08001432 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001433 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1434 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001435 }
Steve Antonf9381f02017-12-14 10:23:57 -08001436 if (IsUnifiedPlan()) {
1437 auto transceiver = FindTransceiverBySender(sender);
1438 if (!transceiver || !sender->track()) {
1439 return RTCError::OK();
1440 }
1441 sender->SetTrack(nullptr);
1442 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001443 transceiver->internal()->set_direction(
1444 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001445 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001446 transceiver->internal()->set_direction(
1447 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001448 }
Steve Anton4171afb2017-11-20 10:20:22 -08001449 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001450 bool removed;
1451 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1452 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1453 } else {
1454 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1455 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1456 }
1457 if (!removed) {
1458 LOG_AND_RETURN_ERROR(
1459 RTCErrorType::INVALID_PARAMETER,
1460 "Couldn't find sender " + sender->id() + " to remove.");
1461 }
Steve Anton4171afb2017-11-20 10:20:22 -08001462 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001463 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001464 return RTCError::OK();
1465}
1466
1467rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1468PeerConnection::FindTransceiverBySender(
1469 rtc::scoped_refptr<RtpSenderInterface> sender) {
1470 for (auto transceiver : transceivers_) {
1471 if (transceiver->sender() == sender) {
1472 return transceiver;
1473 }
1474 }
1475 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001476}
1477
Steve Anton9158ef62017-11-27 13:01:52 -08001478RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1479PeerConnection::AddTransceiver(
1480 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1481 return AddTransceiver(track, RtpTransceiverInit());
1482}
1483
1484RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1485PeerConnection::AddTransceiver(
1486 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1487 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001488 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001489 RTC_CHECK(IsUnifiedPlan())
1490 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001491 if (!track) {
1492 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1493 }
1494 cricket::MediaType media_type;
1495 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1496 media_type = cricket::MEDIA_TYPE_AUDIO;
1497 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1498 media_type = cricket::MEDIA_TYPE_VIDEO;
1499 } else {
1500 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1501 "Track kind is not audio or video");
1502 }
1503 return AddTransceiver(media_type, track, init);
1504}
1505
1506RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1507PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1508 return AddTransceiver(media_type, RtpTransceiverInit());
1509}
1510
1511RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1512PeerConnection::AddTransceiver(cricket::MediaType media_type,
1513 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001514 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001515 RTC_CHECK(IsUnifiedPlan())
1516 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001517 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1518 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1519 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1520 "media type is not audio or video");
1521 }
1522 return AddTransceiver(media_type, nullptr, init);
1523}
1524
1525RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1526PeerConnection::AddTransceiver(
1527 cricket::MediaType media_type,
1528 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001529 const RtpTransceiverInit& init,
1530 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001531 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1532 media_type == cricket::MEDIA_TYPE_VIDEO));
1533 if (track) {
1534 RTC_DCHECK_EQ(media_type,
1535 (track->kind() == MediaStreamTrackInterface::kAudioKind
1536 ? cricket::MEDIA_TYPE_AUDIO
1537 : cricket::MEDIA_TYPE_VIDEO));
1538 }
1539
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001540 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1541 init.send_encodings.size(), 0, 7, 8);
1542
Amit Hilbuchaa584152019-02-06 17:09:52 -08001543 size_t num_rids = absl::c_count_if(init.send_encodings,
1544 [](const RtpEncodingParameters& encoding) {
1545 return !encoding.rid.empty();
1546 });
1547 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001548 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001549 RTCErrorType::INVALID_PARAMETER,
1550 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001551 }
1552
Amit Hilbuchf4770402019-04-08 14:11:57 -07001553 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1554 [](const RtpEncodingParameters& encoding) {
1555 return !IsLegalRsidName(encoding.rid);
1556 })) {
1557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1558 "Invalid RID value provided.");
1559 }
1560
Amit Hilbuchaa584152019-02-06 17:09:52 -08001561 if (absl::c_any_of(init.send_encodings,
1562 [](const RtpEncodingParameters& encoding) {
1563 return encoding.ssrc.has_value();
1564 })) {
1565 LOG_AND_RETURN_ERROR(
1566 RTCErrorType::UNSUPPORTED_PARAMETER,
1567 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001568 }
1569
1570 RtpParameters parameters;
1571 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001572
1573 // Encodings are dropped from the tail if too many are provided.
1574 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1575 parameters.encodings.erase(
1576 parameters.encodings.begin() + kMaxSimulcastStreams,
1577 parameters.encodings.end());
1578 }
1579
1580 // Single RID should be removed.
1581 if (parameters.encodings.size() == 1 &&
1582 !parameters.encodings[0].rid.empty()) {
1583 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1584 parameters.encodings[0].rid.clear();
1585 }
1586
1587 // If RIDs were not provided, they are generated for simulcast scenario.
1588 if (parameters.encodings.size() > 1 && num_rids == 0) {
1589 rtc::UniqueStringGenerator rid_generator;
1590 for (RtpEncodingParameters& encoding : parameters.encodings) {
1591 encoding.rid = rid_generator();
1592 }
1593 }
1594
Florent Castelli892acf02018-10-01 22:47:20 +02001595 if (UnimplementedRtpParameterHasValue(parameters)) {
1596 LOG_AND_RETURN_ERROR(
1597 RTCErrorType::UNSUPPORTED_PARAMETER,
1598 "Attempted to set an unimplemented parameter of RtpParameters.");
1599 }
Steve Anton9158ef62017-11-27 13:01:52 -08001600
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001601 auto result = cricket::CheckRtpParametersValues(parameters);
1602 if (!result.ok()) {
1603 LOG_AND_RETURN_ERROR(result.type(), result.message());
1604 }
1605
Steve Anton3d954a62018-04-02 11:27:23 -07001606 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1607 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001608 // Set the sender ID equal to the track ID if the track is specified unless
1609 // that sender ID is already in use.
1610 std::string sender_id =
1611 (track && !FindSenderById(track->id()) ? track->id()
1612 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001613 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001614 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001615 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1616 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1617 transceiver->internal()->set_direction(init.direction);
1618
Steve Anton22da89f2018-01-25 13:58:07 -08001619 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001620 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001621 }
Steve Antonf9381f02017-12-14 10:23:57 -08001622
1623 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1624}
1625
Steve Anton02ee47c2018-01-10 16:26:06 -08001626rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1627PeerConnection::CreateSender(
1628 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001629 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001630 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001631 const std::vector<std::string>& stream_ids,
1632 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001633 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001634 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001635 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1636 RTC_DCHECK(!track ||
1637 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1638 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1639 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001640 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001641 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001642 } else {
1643 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1644 RTC_DCHECK(!track ||
1645 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1646 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001647 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001648 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001649 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001650 bool set_track_succeeded = sender->SetTrack(track);
1651 RTC_DCHECK(set_track_succeeded);
1652 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001653 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001654 return sender;
1655}
1656
1657rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1658PeerConnection::CreateReceiver(cricket::MediaType media_type,
1659 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001660 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1661 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001662 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001663 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001664 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1665 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001666 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001667 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001668 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001669 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001670 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1671 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001672 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001673 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001674 return receiver;
1675}
1676
1677rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1678PeerConnection::CreateAndAddTransceiver(
1679 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1680 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1681 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001682 // Ensure that the new sender does not have an ID that is already in use by
1683 // another sender.
1684 // Allow receiver IDs to conflict since those come from remote SDP (which
1685 // could be invalid, but should not cause a crash).
1686 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001687 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1688 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001689 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001690 transceiver->internal()->SignalNegotiationNeeded.connect(
1691 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001692 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001693}
1694
Steve Anton52d86772018-02-20 15:48:12 -08001695void PeerConnection::OnNegotiationNeeded() {
1696 RTC_DCHECK_RUN_ON(signaling_thread());
1697 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001698 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001699}
1700
deadbeeffac06552015-11-25 11:26:01 -08001701rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001702 const std::string& kind,
1703 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001704 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001705 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1706 "Plan SdpSemantics. Please use AddTransceiver "
1707 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001708 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001709 if (IsClosed()) {
1710 return nullptr;
1711 }
Steve Anton4171afb2017-11-20 10:20:22 -08001712
Seth Hampson5b4f0752018-04-02 16:31:36 -07001713 // Internally we need to have one stream with Plan B semantics, so we
1714 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001715 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001716 if (stream_id.empty()) {
1717 stream_ids.push_back(rtc::CreateRandomUuid());
1718 RTC_LOG(LS_INFO)
1719 << "No stream_id specified for sender. Generated stream ID: "
1720 << stream_ids[0];
1721 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001722 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001723 }
1724
Steve Anton4171afb2017-11-20 10:20:22 -08001725 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001726 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001727 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001728 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001729 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001730 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001731 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001732 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001733 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001734 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001735 auto video_sender =
1736 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001737 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001738 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001739 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001740 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001741 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001742 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001743 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001744 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001745 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001746
deadbeefe1f9d832016-01-14 15:35:42 -08001747 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001748}
1749
deadbeef70ab1a12015-09-28 16:53:55 -07001750std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1751 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001752 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001753 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001754 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001755 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001756 }
1757 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001758}
1759
Steve Anton4171afb2017-11-20 10:20:22 -08001760std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1761PeerConnection::GetSendersInternal() const {
1762 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1763 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001764 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001765 auto senders = transceiver->internal()->senders();
1766 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1767 }
1768 return all_senders;
1769}
1770
deadbeef70ab1a12015-09-28 16:53:55 -07001771std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1772PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001773 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001774 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001775 for (const auto& receiver : GetReceiversInternal()) {
1776 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001777 }
1778 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001779}
1780
Steve Anton4171afb2017-11-20 10:20:22 -08001781std::vector<
1782 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1783PeerConnection::GetReceiversInternal() const {
1784 std::vector<
1785 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1786 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001787 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001788 auto receivers = transceiver->internal()->receivers();
1789 all_receivers.insert(all_receivers.end(), receivers.begin(),
1790 receivers.end());
1791 }
1792 return all_receivers;
1793}
1794
Steve Anton9158ef62017-11-27 13:01:52 -08001795std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1796PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001797 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001798 RTC_CHECK(IsUnifiedPlan())
1799 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001800 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001801 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001802 all_transceivers.push_back(transceiver);
1803 }
1804 return all_transceivers;
1805}
1806
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001808 MediaStreamTrackInterface* track,
1809 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001810 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001811 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001812 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001813 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 return false;
1815 }
1816
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001817 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001818 // The StatsCollector is used to tell if a track is valid because it may
1819 // remember tracks that the PeerConnection previously removed.
1820 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001821 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1822 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001823 return false;
1824 }
Steve Antonad182762018-09-05 20:22:40 +00001825 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1826 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 return true;
1828}
1829
hbos74e1a4f2016-09-15 23:33:01 -07001830void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001831 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001832 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001833 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001834 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001835 stats_collector_->GetStatsReport(callback);
1836}
1837
Henrik Boström1df1bf82018-03-20 13:24:20 +01001838void PeerConnection::GetStats(
1839 rtc::scoped_refptr<RtpSenderInterface> selector,
1840 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1841 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001842 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001843 RTC_DCHECK(callback);
1844 RTC_DCHECK(stats_collector_);
1845 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1846 if (selector) {
1847 for (const auto& proxy_transceiver : transceivers_) {
1848 for (const auto& proxy_sender :
1849 proxy_transceiver->internal()->senders()) {
1850 if (proxy_sender == selector) {
1851 internal_sender = proxy_sender->internal();
1852 break;
1853 }
1854 }
1855 if (internal_sender)
1856 break;
1857 }
1858 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001859 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001860 // belong to the PeerConnection (in Plan B, senders can be removed from the
1861 // PeerConnection). This means that "all the stats objects representing the
1862 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1863 // produces an empty stats report.
1864 stats_collector_->GetStatsReport(internal_sender, callback);
1865}
1866
1867void PeerConnection::GetStats(
1868 rtc::scoped_refptr<RtpReceiverInterface> selector,
1869 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1870 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001871 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001872 RTC_DCHECK(callback);
1873 RTC_DCHECK(stats_collector_);
1874 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1875 if (selector) {
1876 for (const auto& proxy_transceiver : transceivers_) {
1877 for (const auto& proxy_receiver :
1878 proxy_transceiver->internal()->receivers()) {
1879 if (proxy_receiver == selector) {
1880 internal_receiver = proxy_receiver->internal();
1881 break;
1882 }
1883 }
1884 if (internal_receiver)
1885 break;
1886 }
1887 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001888 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001889 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1890 // the PeerConnection). This means that "all the stats objects representing
1891 // the selector" is an empty set. Invoking GetStatsReport() with a null
1892 // selector produces an empty stats report.
1893 stats_collector_->GetStatsReport(internal_receiver, callback);
1894}
1895
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001897 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 return signaling_state_;
1899}
1900
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001901PeerConnectionInterface::IceConnectionState
1902PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001903 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001904 return ice_connection_state_;
1905}
1906
Alex Loiko9289eda2018-11-23 16:18:59 +00001907PeerConnectionInterface::IceConnectionState
1908PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001909 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001910 return standardized_ice_connection_state_;
1911}
1912
Jonas Olsson635474e2018-10-18 15:58:17 +02001913PeerConnectionInterface::PeerConnectionState
1914PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001915 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001916 return connection_state_;
1917}
1918
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919PeerConnectionInterface::IceGatheringState
1920PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922 return ice_gathering_state_;
1923}
1924
Yves Gerey665174f2018-06-19 15:03:05 +02001925rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 const std::string& label,
1927 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001928 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001929 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001930
deadbeefab9b2d12015-10-14 11:33:11 -07001931 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001932
kwibergd1fe2812016-04-27 06:47:29 -07001933 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001934 if (config) {
1935 internal_config.reset(new InternalDataChannelInit(*config));
1936 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001937 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001938 InternalCreateDataChannel(label, internal_config.get()));
1939 if (!channel.get()) {
1940 return nullptr;
1941 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001943 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1944 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001945 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001946 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001947 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001948 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 return DataChannelProxy::Create(signaling_thread(), channel.get());
1950}
1951
1952void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001953 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001954 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001955 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001956
nisse7ce109a2017-01-31 00:57:56 -08001957 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001958 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001959 return;
1960 }
deadbeefab9b2d12015-10-14 11:33:11 -07001961
Steve Anton8d3444d2017-10-20 15:30:51 -07001962 if (IsClosed()) {
1963 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001964 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001965 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001966 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001967 return;
1968 }
1969
zhihuang1c378ed2017-08-17 14:10:50 -07001970 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001971 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001973 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001974 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001975 return;
1976 }
1977
Steve Anton22da89f2018-01-25 13:58:07 -08001978 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1979 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1980 if (IsUnifiedPlan()) {
1981 RTCError error = HandleLegacyOfferOptions(options);
1982 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001983 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001984 return;
1985 }
1986 }
1987
zhihuang1c378ed2017-08-17 14:10:50 -07001988 cricket::MediaSessionOptions session_options;
1989 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001990 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991}
1992
Steve Anton22da89f2018-01-25 13:58:07 -08001993RTCError PeerConnection::HandleLegacyOfferOptions(
1994 const RTCOfferAnswerOptions& options) {
1995 RTC_DCHECK(IsUnifiedPlan());
1996
1997 if (options.offer_to_receive_audio == 0) {
1998 RemoveRecvDirectionFromReceivingTransceiversOfType(
1999 cricket::MEDIA_TYPE_AUDIO);
2000 } else if (options.offer_to_receive_audio == 1) {
2001 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2002 } else if (options.offer_to_receive_audio > 1) {
2003 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2004 "offer_to_receive_audio > 1 is not supported.");
2005 }
2006
2007 if (options.offer_to_receive_video == 0) {
2008 RemoveRecvDirectionFromReceivingTransceiversOfType(
2009 cricket::MEDIA_TYPE_VIDEO);
2010 } else if (options.offer_to_receive_video == 1) {
2011 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2012 } else if (options.offer_to_receive_video > 1) {
2013 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2014 "offer_to_receive_video > 1 is not supported.");
2015 }
2016
2017 return RTCError::OK();
2018}
2019
2020void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2021 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002022 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002023 RtpTransceiverDirection new_direction =
2024 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2025 if (new_direction != transceiver->direction()) {
2026 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2027 << " transceiver (MID="
2028 << transceiver->mid().value_or("<not set>") << ") from "
2029 << RtpTransceiverDirectionToString(
2030 transceiver->direction())
2031 << " to "
2032 << RtpTransceiverDirectionToString(new_direction)
2033 << " since CreateOffer specified offer_to_receive=0";
2034 transceiver->internal()->set_direction(new_direction);
2035 }
Steve Anton22da89f2018-01-25 13:58:07 -08002036 }
2037}
2038
2039void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2040 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002041 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002042 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002043 RTC_LOG(LS_INFO)
2044 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2045 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002046 RtpTransceiverInit init;
2047 init.direction = RtpTransceiverDirection::kRecvOnly;
2048 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
2049 }
2050}
2051
2052std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2053PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2054 std::vector<
2055 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2056 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002057 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002058 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002059 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2060 receiving_transceivers.push_back(transceiver);
2061 }
2062 }
2063 return receiving_transceivers;
2064}
2065
htaa2a49d92016-03-04 02:51:39 -08002066void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2067 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002068 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002069 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002070 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002071 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002072 return;
2073 }
2074
Steve Antondffead82018-02-06 10:31:29 -08002075 if (!(signaling_state_ == kHaveRemoteOffer ||
2076 signaling_state_ == kHaveLocalPrAnswer)) {
2077 std::string error =
2078 "PeerConnection cannot create an answer in a state other than "
2079 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002080 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002081 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002082 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002083 return;
2084 }
2085
Steve Antondffead82018-02-06 10:31:29 -08002086 // The remote description should be set if we're in the right state.
2087 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002088
Steve Anton22da89f2018-01-25 13:58:07 -08002089 if (IsUnifiedPlan()) {
2090 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2091 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2092 "supported with Unified Plan semantics. Use the "
2093 "RtpTransceiver API instead.";
2094 }
2095 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2096 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2097 "supported with Unified Plan semantics. Use the "
2098 "RtpTransceiver API instead.";
2099 }
2100 }
2101
htaa2a49d92016-03-04 02:51:39 -08002102 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002103 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002104
Steve Antond25da372017-11-06 14:50:29 -08002105 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002106}
2107
2108void PeerConnection::SetLocalDescription(
2109 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002110 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002111 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002112 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002113
Steve Anton80dd7b52018-02-16 17:08:42 -08002114 // The SetLocalDescription contract is that we take ownership of the session
2115 // description regardless of the outcome, so wrap it in a unique_ptr right
2116 // away. Ideally, SetLocalDescription's signature will be changed to take the
2117 // description as a unique_ptr argument to formalize this agreement.
2118 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2119
nisse7ce109a2017-01-31 00:57:56 -08002120 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002121 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122 return;
2123 }
Steve Anton8a006912017-12-04 15:25:56 -08002124
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002126 PostSetSessionDescriptionFailure(
2127 observer,
2128 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129 return;
2130 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002131
Steve Anton80dd7b52018-02-16 17:08:42 -08002132 // If a session error has occurred the PeerConnection is in a possibly
2133 // inconsistent state so fail right away.
2134 if (session_error() != SessionError::kNone) {
2135 std::string error_message = GetSessionErrorMsg();
2136 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002137 PostSetSessionDescriptionFailure(
2138 observer,
2139 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002140 return;
2141 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002142
Steve Anton80dd7b52018-02-16 17:08:42 -08002143 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2144 if (!error.ok()) {
2145 std::string error_message = GetSetDescriptionErrorMessage(
2146 cricket::CS_LOCAL, desc->GetType(), error);
2147 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002148 PostSetSessionDescriptionFailure(
2149 observer,
2150 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 return;
2152 }
2153
2154 // Grab the description type before moving ownership to ApplyLocalDescription,
2155 // which may destroy it before returning.
2156 const SdpType type = desc->GetType();
2157
2158 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002159 // |desc| may be destroyed at this point.
2160
2161 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002162 // If ApplyLocalDescription fails, the PeerConnection could be in an
2163 // inconsistent state, so act conservatively here and set the session error
2164 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2165 SetSessionError(SessionError::kContent, error.message());
2166 std::string error_message =
2167 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2168 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002169 PostSetSessionDescriptionFailure(
2170 observer,
2171 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002172 return;
2173 }
Steve Anton8a006912017-12-04 15:25:56 -08002174 RTC_DCHECK(local_description());
2175
2176 PostSetSessionDescriptionSuccess(observer);
2177
Steve Antonad182762018-09-05 20:22:40 +00002178 // MaybeStartGathering needs to be called after posting
2179 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2180 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002181 transport_controller_->MaybeStartGathering();
2182
Steve Antona3a92c22017-12-07 10:27:41 -08002183 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002184 // TODO(deadbeef): We already had to hop to the network thread for
2185 // MaybeStartGathering...
2186 network_thread()->Invoke<void>(
2187 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2188 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002189 // Make UMA notes about what was agreed to.
2190 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002191 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002192 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002193}
2194
2195RTCError PeerConnection::ApplyLocalDescription(
2196 std::unique_ptr<SessionDescriptionInterface> desc) {
2197 RTC_DCHECK_RUN_ON(signaling_thread());
2198 RTC_DCHECK(desc);
2199
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200 // Update stats here so that we have the most recent stats for tracks and
2201 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002202 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002203
Steve Antondcc3c022017-12-22 16:02:54 -08002204 // Take a reference to the old local description since it's used below to
2205 // compare against the new local description. When setting the new local
2206 // description, grab ownership of the replaced session description in case it
2207 // is the same as |old_local_description|, to keep it alive for the duration
2208 // of the method.
2209 const SessionDescriptionInterface* old_local_description =
2210 local_description();
2211 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002212 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002213 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002214 replaced_local_description = pending_local_description_
2215 ? std::move(pending_local_description_)
2216 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002217 current_local_description_ = std::move(desc);
2218 pending_local_description_ = nullptr;
2219 current_remote_description_ = std::move(pending_remote_description_);
2220 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002221 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002222 pending_local_description_ = std::move(desc);
2223 }
2224 // The session description to apply now must be accessed by
2225 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002226 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002227
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002228 // Report statistics about any use of simulcast.
2229 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2230 *local_description()->description());
2231
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002232 if (!is_caller_) {
2233 if (remote_description()) {
2234 // Remote description was applied first, so this PC is the callee.
2235 is_caller_ = false;
2236 } else {
2237 // Local description is applied first, so this PC is the caller.
2238 is_caller_ = true;
2239 }
2240 }
2241
Zhi Huange830e682018-03-30 10:48:35 -07002242 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2243 if (!error.ok()) {
2244 return error;
2245 }
2246
Steve Antondcc3c022017-12-22 16:02:54 -08002247 if (IsUnifiedPlan()) {
2248 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002249 cricket::CS_LOCAL, *local_description(), old_local_description,
2250 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002251 if (!error.ok()) {
2252 return error;
2253 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002254 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2255 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002256 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002257 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2258 // Note that code paths that don't set MID won't be able to use
2259 // information about DTLS transports.
2260 if (transceiver->mid()) {
2261 auto dtls_transport =
2262 LookupDtlsTransportByMidInternal(*transceiver->mid());
2263 transceiver->internal()->sender_internal()->set_transport(
2264 dtls_transport);
2265 transceiver->internal()->receiver_internal()->set_transport(
2266 dtls_transport);
2267 }
2268
Steve Antondcc3c022017-12-22 16:02:54 -08002269 const ContentInfo* content =
2270 FindMediaSectionForTransceiver(transceiver, local_description());
2271 if (!content) {
2272 continue;
2273 }
2274 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002275 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2276 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002277 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002278 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2279 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2280 // "recvonly", process the removal of a remote track for the media
2281 // description, given transceiver, removeList, and muteTracks.
2282 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2283 (transceiver->internal()->fired_direction() &&
2284 RtpTransceiverDirectionHasRecv(
2285 *transceiver->internal()->fired_direction()))) {
2286 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2287 &removed_streams);
2288 }
2289 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2290 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002291 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002292 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002293 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002294 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002295 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002296 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002297 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002298 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002299 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002300 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002301 }
2302 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002303 // Media channels will be created only when offer is set. These may use new
2304 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002305 if (type == SdpType::kOffer) {
2306 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2307 // description is applied. Restore back to old description.
2308 RTCError error = CreateChannels(*local_description()->description());
2309 if (!error.ok()) {
2310 return error;
2311 }
2312 }
Steve Antondcc3c022017-12-22 16:02:54 -08002313 // Remove unused channels if MediaContentDescription is rejected.
2314 RemoveUnusedChannels(local_description()->description());
2315 }
Steve Anton8a006912017-12-04 15:25:56 -08002316
Zhi Huange830e682018-03-30 10:48:35 -07002317 error = UpdateSessionState(type, cricket::CS_LOCAL,
2318 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002319 if (!error.ok()) {
2320 return error;
2321 }
Steve Antondcc3c022017-12-22 16:02:54 -08002322
Steve Anton8a006912017-12-04 15:25:56 -08002323 if (remote_description()) {
2324 // Now that we have a local description, we can push down remote candidates.
2325 UseCandidatesInSessionDescription(remote_description());
2326 }
2327
2328 pending_ice_restarts_.clear();
2329 if (session_error() != SessionError::kNone) {
2330 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2331 }
2332
deadbeefab9b2d12015-10-14 11:33:11 -07002333 // If setting the description decided our SSL role, allocate any necessary
2334 // SCTP sids.
2335 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002336 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002337 AllocateSctpSids(role);
2338 }
2339
Steve Antond3679212018-01-17 17:41:02 -08002340 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002341 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002342 const ContentInfo* content =
2343 FindMediaSectionForTransceiver(transceiver, local_description());
2344 if (!content) {
2345 continue;
2346 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002347 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2348 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002349 // 0 is a special value meaning "this sender has no associated send
2350 // stream". Need to call this so the sender won't attempt to configure
2351 // a no longer existing stream and run into DCHECKs in the lower
2352 // layers.
2353 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002354 } else {
2355 // Get the StreamParams from the channel which could generate SSRCs.
2356 const std::vector<StreamParams>& streams = channel->local_streams();
2357 transceiver->internal()->sender_internal()->set_stream_ids(
2358 streams[0].stream_ids());
2359 transceiver->internal()->sender_internal()->SetSsrc(
2360 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002361 }
2362 }
2363 } else {
2364 // Plan B semantics.
2365
Steve Antondcc3c022017-12-22 16:02:54 -08002366 // Update state and SSRC of local MediaStreams and DataChannels based on the
2367 // local session description.
2368 const cricket::ContentInfo* audio_content =
2369 GetFirstAudioContent(local_description()->description());
2370 if (audio_content) {
2371 if (audio_content->rejected) {
2372 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2373 } else {
2374 const cricket::AudioContentDescription* audio_desc =
2375 audio_content->media_description()->as_audio();
2376 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2377 }
deadbeeffaac4972015-11-12 15:33:07 -08002378 }
deadbeefab9b2d12015-10-14 11:33:11 -07002379
Steve Antondcc3c022017-12-22 16:02:54 -08002380 const cricket::ContentInfo* video_content =
2381 GetFirstVideoContent(local_description()->description());
2382 if (video_content) {
2383 if (video_content->rejected) {
2384 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2385 } else {
2386 const cricket::VideoContentDescription* video_desc =
2387 video_content->media_description()->as_video();
2388 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2389 }
deadbeeffaac4972015-11-12 15:33:07 -08002390 }
deadbeefab9b2d12015-10-14 11:33:11 -07002391 }
2392
2393 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002394 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002395 if (data_content) {
2396 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002397 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002398 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002399 cricket::kMediaProtocolRtpPrefix)) {
2400 UpdateLocalRtpDataChannels(data_desc->streams());
2401 }
2402 }
2403
Steve Anton8a006912017-12-04 15:25:56 -08002404 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002405}
2406
Steve Anton06817cd2018-12-18 15:55:30 -08002407// The SDP parser used to populate these values by default for the 'content
2408// name' if an a=mid line was absent.
2409static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2410 switch (media_type) {
2411 case cricket::MEDIA_TYPE_AUDIO:
2412 return cricket::CN_AUDIO;
2413 case cricket::MEDIA_TYPE_VIDEO:
2414 return cricket::CN_VIDEO;
2415 case cricket::MEDIA_TYPE_DATA:
2416 return cricket::CN_DATA;
2417 }
2418 RTC_NOTREACHED();
2419 return "";
2420}
2421
2422void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002423 cricket::SessionDescription* new_remote_description) {
2424 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002425 const cricket::ContentInfos& local_contents =
2426 (local_description() ? local_description()->description()->contents()
2427 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002428 const cricket::ContentInfos& remote_contents =
2429 (remote_description() ? remote_description()->description()->contents()
2430 : cricket::ContentInfos());
2431 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2432 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002433 if (!content.name.empty()) {
2434 continue;
2435 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002436 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002437 absl::string_view source_explanation;
2438 if (IsUnifiedPlan()) {
2439 if (i < local_contents.size()) {
2440 new_mid = local_contents[i].name;
2441 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002442 } else if (i < remote_contents.size()) {
2443 new_mid = remote_contents[i].name;
2444 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002445 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002446 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002447 source_explanation = "generated just now";
2448 }
2449 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002450 new_mid = std::string(
2451 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002452 source_explanation = "to match pre-existing behavior";
2453 }
Steve Antond7180cc2019-02-07 10:44:53 -08002454 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002455 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002456 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002457 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2458 << " is missing an a=mid line. Filling in the value '"
2459 << new_mid << "' " << source_explanation << ".";
2460 }
2461}
2462
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002464 SetSessionDescriptionObserver* observer,
2465 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002466 SetRemoteDescription(
2467 std::unique_ptr<SessionDescriptionInterface>(desc),
2468 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2469 new SetRemoteDescriptionObserverAdapter(this, observer)));
2470}
2471
2472void PeerConnection::SetRemoteDescription(
2473 std::unique_ptr<SessionDescriptionInterface> desc,
2474 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002475 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002476 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002477
nisse7ce109a2017-01-31 00:57:56 -08002478 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002479 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002480 return;
2481 }
Steve Anton8a006912017-12-04 15:25:56 -08002482
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002483 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002484 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002485 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002486 return;
2487 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002488
Steve Anton80dd7b52018-02-16 17:08:42 -08002489 // If a session error has occurred the PeerConnection is in a possibly
2490 // inconsistent state so fail right away.
2491 if (session_error() != SessionError::kNone) {
2492 std::string error_message = GetSessionErrorMsg();
2493 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2494 observer->OnSetRemoteDescriptionComplete(
2495 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2496 return;
2497 }
Steve Anton71439a62018-02-15 11:53:06 -08002498
Steve Antonba42e992018-04-09 14:10:01 -07002499 if (desc->GetType() == SdpType::kOffer) {
2500 // Report to UMA the format of the received offer.
2501 ReportSdpFormatReceived(*desc);
2502 }
2503
Steve Anton06817cd2018-12-18 15:55:30 -08002504 // Handle remote descriptions missing a=mid lines for interop with legacy end
2505 // points.
2506 FillInMissingRemoteMids(desc->description());
2507
Steve Anton80dd7b52018-02-16 17:08:42 -08002508 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002509 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002510 std::string error_message = GetSetDescriptionErrorMessage(
2511 cricket::CS_REMOTE, desc->GetType(), error);
2512 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002513 observer->OnSetRemoteDescriptionComplete(
2514 RTCError(error.type(), std::move(error_message)));
2515 return;
2516 }
Steve Anton71439a62018-02-15 11:53:06 -08002517
Steve Anton80dd7b52018-02-16 17:08:42 -08002518 // Grab the description type before moving ownership to
2519 // ApplyRemoteDescription, which may destroy it before returning.
2520 const SdpType type = desc->GetType();
2521
2522 error = ApplyRemoteDescription(std::move(desc));
2523 // |desc| may be destroyed at this point.
2524
2525 if (!error.ok()) {
2526 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2527 // inconsistent state, so act conservatively here and set the session error
2528 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2529 SetSessionError(SessionError::kContent, error.message());
2530 std::string error_message =
2531 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2532 RTC_LOG(LS_ERROR) << error_message;
2533 observer->OnSetRemoteDescriptionComplete(
2534 RTCError(error.type(), std::move(error_message)));
2535 return;
2536 }
2537 RTC_DCHECK(remote_description());
2538
2539 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002540 // TODO(deadbeef): We already had to hop to the network thread for
2541 // MaybeStartGathering...
2542 network_thread()->Invoke<void>(
2543 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2544 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002545 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002546 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002547 }
2548
2549 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002550 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002551}
2552
2553RTCError PeerConnection::ApplyRemoteDescription(
2554 std::unique_ptr<SessionDescriptionInterface> desc) {
2555 RTC_DCHECK_RUN_ON(signaling_thread());
2556 RTC_DCHECK(desc);
2557
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002558 // Update stats here so that we have the most recent stats for tracks and
2559 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002560 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002561
Steve Antondcc3c022017-12-22 16:02:54 -08002562 // Take a reference to the old remote description since it's used below to
2563 // compare against the new remote description. When setting the new remote
2564 // description, grab ownership of the replaced session description in case it
2565 // is the same as |old_remote_description|, to keep it alive for the duration
2566 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002567 const SessionDescriptionInterface* old_remote_description =
2568 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002569 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002570 SdpType type = desc->GetType();
2571 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002572 replaced_remote_description = pending_remote_description_
2573 ? std::move(pending_remote_description_)
2574 : std::move(current_remote_description_);
2575 current_remote_description_ = std::move(desc);
2576 pending_remote_description_ = nullptr;
2577 current_local_description_ = std::move(pending_local_description_);
2578 } else {
2579 replaced_remote_description = std::move(pending_remote_description_);
2580 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002581 }
Steve Anton8a006912017-12-04 15:25:56 -08002582 // The session description to apply now must be accessed by
2583 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002584 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002585
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002586 // Report statistics about any use of simulcast.
2587 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2588 *remote_description()->description());
2589
Zhi Huange830e682018-03-30 10:48:35 -07002590 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2591 if (!error.ok()) {
2592 return error;
2593 }
Steve Anton8a006912017-12-04 15:25:56 -08002594 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002595 if (IsUnifiedPlan()) {
2596 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002597 cricket::CS_REMOTE, *remote_description(), local_description(),
2598 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002599 if (!error.ok()) {
2600 return error;
2601 }
Steve Antondcc3c022017-12-22 16:02:54 -08002602 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002603 // Media channels will be created only when offer is set. These may use new
2604 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002605 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002606 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002607 // description is applied. Restore back to old description.
2608 RTCError error = CreateChannels(*remote_description()->description());
2609 if (!error.ok()) {
2610 return error;
2611 }
2612 }
Steve Antondcc3c022017-12-22 16:02:54 -08002613 // Remove unused channels if MediaContentDescription is rejected.
2614 RemoveUnusedChannels(remote_description()->description());
2615 }
Steve Anton8a006912017-12-04 15:25:56 -08002616
Zhi Huange830e682018-03-30 10:48:35 -07002617 // NOTE: Candidates allocation will be initiated only when
2618 // SetLocalDescription is called.
2619 error = UpdateSessionState(type, cricket::CS_REMOTE,
2620 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002621 if (!error.ok()) {
2622 return error;
2623 }
2624
2625 if (local_description() &&
2626 !UseCandidatesInSessionDescription(remote_description())) {
2627 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2628 }
2629
2630 if (old_remote_description) {
2631 for (const cricket::ContentInfo& content :
2632 old_remote_description->description()->contents()) {
2633 // Check if this new SessionDescription contains new ICE ufrag and
2634 // password that indicates the remote peer requests an ICE restart.
2635 // TODO(deadbeef): When we start storing both the current and pending
2636 // remote description, this should reset pending_ice_restarts and compare
2637 // against the current description.
2638 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2639 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002640 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002641 pending_ice_restarts_.insert(content.name);
2642 }
2643 } else {
2644 // We retain all received candidates only if ICE is not restarted.
2645 // When ICE is restarted, all previous candidates belong to an old
2646 // generation and should not be kept.
2647 // TODO(deadbeef): This goes against the W3C spec which says the remote
2648 // description should only contain candidates from the last set remote
2649 // description plus any candidates added since then. We should remove
2650 // this once we're sure it won't break anything.
2651 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2652 old_remote_description, content.name, mutable_remote_description());
2653 }
2654 }
2655 }
2656
2657 if (session_error() != SessionError::kNone) {
2658 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2659 }
2660
2661 // Set the the ICE connection state to connecting since the connection may
2662 // become writable with peer reflexive candidates before any remote candidate
2663 // is signaled.
2664 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2665 // is to have a new signal the indicates a change in checking state from the
2666 // transport and expose a new checking() member from transport that can be
2667 // read to determine the current checking state. The existing SignalConnecting
2668 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002669 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002670 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002671 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2672 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2673 }
2674
deadbeefab9b2d12015-10-14 11:33:11 -07002675 // If setting the description decided our SSL role, allocate any necessary
2676 // SCTP sids.
2677 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002678 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002679 AllocateSctpSids(role);
2680 }
2681
Steve Antondcc3c022017-12-22 16:02:54 -08002682 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002683 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002684 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002685 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002686 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002687 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002688 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002689 const ContentInfo* content =
2690 FindMediaSectionForTransceiver(transceiver, remote_description());
2691 if (!content) {
2692 continue;
2693 }
2694 const MediaContentDescription* media_desc = content->media_description();
2695 RtpTransceiverDirection local_direction =
2696 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002697 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2698 // RTCSessionDescription: Set the associated remote streams given
2699 // transceiver.[[Receiver]], msids, addList, and removeList".
2700 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2701 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2702 std::vector<std::string> stream_ids;
2703 if (!media_desc->streams().empty()) {
2704 // The remote description has signaled the stream IDs.
2705 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002706 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002707 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2708 << " (" << GetStreamIdsString(stream_ids) << ").";
2709 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2710 stream_ids, &added_streams,
2711 &removed_streams);
2712 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2713 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2714 // and transceiver's current direction is neither sendrecv nor recvonly,
2715 // process the addition of a remote track for the media description.
2716 if (!transceiver->fired_direction() ||
2717 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2718 RTC_LOG(LS_INFO)
2719 << "Processing the addition of a remote track for MID="
2720 << content->name << ".";
2721 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002722 }
Steve Antondcc3c022017-12-22 16:02:54 -08002723 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002724 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002725 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2726 // removal of a remote track for the media description, given transceiver,
2727 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002728 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002729 (transceiver->fired_direction() &&
2730 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2731 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2732 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002733 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002734 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002735 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002736 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002737 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002738 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002739 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002740 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002741 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002742 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2743 if (transceiver->mid()) {
2744 auto dtls_transport =
2745 LookupDtlsTransportByMidInternal(*transceiver->mid());
2746 transceiver->internal()->sender_internal()->set_transport(
2747 dtls_transport);
2748 transceiver->internal()->receiver_internal()->set_transport(
2749 dtls_transport);
2750 }
Steve Antondcc3c022017-12-22 16:02:54 -08002751 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002752 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002753 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002754 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002755 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2756 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002757 transceiver->Stop();
2758 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002759 if (!content->rejected &&
2760 RtpTransceiverDirectionHasRecv(local_direction)) {
2761 // Set ssrc to 0 in the case of an unsignalled ssrc.
2762 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002763 if (!media_desc->streams().empty() &&
2764 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002765 ssrc = media_desc->streams()[0].first_ssrc();
2766 }
2767 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002768 }
Steve Antondcc3c022017-12-22 16:02:54 -08002769 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002770 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002771 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002772 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002773 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002774 observer->OnTrack(transceiver);
2775 observer->OnAddTrack(transceiver->receiver(),
2776 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002777 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002778 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002779 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002780 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002781 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002782 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002783 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002784 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002785 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002786 }
Steve Antondcc3c022017-12-22 16:02:54 -08002787 }
2788
Henrik Boströmfdb92012017-11-09 19:55:44 +01002789 const cricket::ContentInfo* audio_content =
2790 GetFirstAudioContent(remote_description()->description());
2791 const cricket::ContentInfo* video_content =
2792 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002793 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002794 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002795 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002796 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002797 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002798 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002799
2800 // Check if the descriptions include streams, just in case the peer supports
2801 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002802 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002803 (audio_desc && !audio_desc->streams().empty()) ||
2804 (video_desc && !video_desc->streams().empty())) {
2805 remote_peer_supports_msid_ = true;
2806 }
deadbeefab9b2d12015-10-14 11:33:11 -07002807
2808 // We wait to signal new streams until we finish processing the description,
2809 // since only at that point will new streams have all their tracks.
2810 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2811
Steve Antondcc3c022017-12-22 16:02:54 -08002812 if (!IsUnifiedPlan()) {
2813 // TODO(steveanton): When removing RTP senders/receivers in response to a
2814 // rejected media section, there is some cleanup logic that expects the
2815 // voice/ video channel to still be set. But in this method the voice/video
2816 // channel would have been destroyed by the SetRemoteDescription caller
2817 // above so the cleanup that relies on them fails to run. The RemoveSenders
2818 // calls should be moved to right before the DestroyChannel calls to fix
2819 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002820
Steve Antondcc3c022017-12-22 16:02:54 -08002821 // Find all audio rtp streams and create corresponding remote AudioTracks
2822 // and MediaStreams.
2823 if (audio_content) {
2824 if (audio_content->rejected) {
2825 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2826 } else {
2827 bool default_audio_track_needed =
2828 !remote_peer_supports_msid_ &&
2829 RtpTransceiverDirectionHasSend(audio_desc->direction());
2830 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2831 default_audio_track_needed, audio_desc->type(),
2832 new_streams);
2833 }
deadbeeffaac4972015-11-12 15:33:07 -08002834 }
deadbeefab9b2d12015-10-14 11:33:11 -07002835
Steve Antondcc3c022017-12-22 16:02:54 -08002836 // Find all video rtp streams and create corresponding remote VideoTracks
2837 // and MediaStreams.
2838 if (video_content) {
2839 if (video_content->rejected) {
2840 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2841 } else {
2842 bool default_video_track_needed =
2843 !remote_peer_supports_msid_ &&
2844 RtpTransceiverDirectionHasSend(video_desc->direction());
2845 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2846 default_video_track_needed, video_desc->type(),
2847 new_streams);
2848 }
deadbeeffaac4972015-11-12 15:33:07 -08002849 }
deadbeefab9b2d12015-10-14 11:33:11 -07002850
Steve Antondcc3c022017-12-22 16:02:54 -08002851 // Update the DataChannels with the information from the remote peer.
2852 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002853 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002854 cricket::kMediaProtocolRtpPrefix)) {
2855 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2856 }
deadbeefab9b2d12015-10-14 11:33:11 -07002857 }
deadbeefab9b2d12015-10-14 11:33:11 -07002858
Steve Antondcc3c022017-12-22 16:02:54 -08002859 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002860 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002861 for (size_t i = 0; i < new_streams->count(); ++i) {
2862 MediaStreamInterface* new_stream = new_streams->at(i);
2863 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002864 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002865 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2866 }
deadbeefab9b2d12015-10-14 11:33:11 -07002867
Steve Antondcc3c022017-12-22 16:02:54 -08002868 UpdateEndedRemoteMediaStreams();
2869 }
deadbeefab9b2d12015-10-14 11:33:11 -07002870
Steve Anton8a006912017-12-04 15:25:56 -08002871 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002872}
2873
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002874void PeerConnection::SetAssociatedRemoteStreams(
2875 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2876 const std::vector<std::string>& stream_ids,
2877 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2878 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2879 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2880 for (const std::string& stream_id : stream_ids) {
2881 rtc::scoped_refptr<MediaStreamInterface> stream =
2882 remote_streams_->find(stream_id);
2883 if (!stream) {
2884 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2885 MediaStream::Create(stream_id));
2886 remote_streams_->AddStream(stream);
2887 added_streams->push_back(stream);
2888 }
2889 media_streams.push_back(stream);
2890 }
2891 // Special case: "a=msid" missing, use random stream ID.
2892 if (media_streams.empty() &&
2893 !(remote_description()->description()->msid_signaling() &
2894 cricket::kMsidSignalingMediaSection)) {
2895 if (!missing_msid_default_stream_) {
2896 missing_msid_default_stream_ = MediaStreamProxy::Create(
2897 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2898 added_streams->push_back(missing_msid_default_stream_);
2899 }
2900 media_streams.push_back(missing_msid_default_stream_);
2901 }
2902 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2903 receiver->streams();
2904 // SetStreams() will add/remove the receiver's track to/from the streams. This
2905 // differs from the spec - the spec uses an "addList" and "removeList" to
2906 // update the stream-track relationships in a later step. We do this earlier,
2907 // changing the order of things, but the end-result is the same.
2908 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2909 // instead. https://crbug.com/webrtc/9480
2910 receiver->SetStreams(media_streams);
2911 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2912}
2913
Steve Anton0f5400a2018-07-17 14:25:36 -07002914void PeerConnection::ProcessRemovalOfRemoteTrack(
2915 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2916 transceiver,
2917 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2918 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2919 RTC_DCHECK(transceiver->mid());
2920 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2921 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002922 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002923 transceiver->internal()->receiver_internal()->streams();
2924 // This will remove the remote track from the streams.
2925 transceiver->internal()->receiver_internal()->set_stream_ids({});
2926 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002927 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2928}
2929
2930void PeerConnection::RemoveRemoteStreamsIfEmpty(
2931 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2932 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2933 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2934 // streams, see if the stream was removed by checking if this was the last
2935 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002936 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002937 if (remote_stream->GetAudioTracks().empty() &&
2938 remote_stream->GetVideoTracks().empty()) {
2939 remote_streams_->RemoveStream(remote_stream);
2940 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002941 }
2942 }
2943}
2944
Steve Antondcc3c022017-12-22 16:02:54 -08002945RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2946 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002947 const SessionDescriptionInterface& new_session,
2948 const SessionDescriptionInterface* old_local_description,
2949 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002950 RTC_DCHECK(IsUnifiedPlan());
2951
Steve Anton7464fca2018-01-19 11:10:37 -08002952 const cricket::ContentGroup* bundle_group = nullptr;
2953 if (new_session.GetType() == SdpType::kOffer) {
2954 auto bundle_group_or_error =
2955 GetEarlyBundleGroup(*new_session.description());
2956 if (!bundle_group_or_error.ok()) {
2957 return bundle_group_or_error.MoveError();
2958 }
2959 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002960 }
Steve Antondcc3c022017-12-22 16:02:54 -08002961
Steve Antondcc3c022017-12-22 16:02:54 -08002962 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002963 for (size_t i = 0; i < new_contents.size(); ++i) {
2964 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002965 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002966 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002967 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2968 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002969 const cricket::ContentInfo* old_local_content = nullptr;
2970 if (old_local_description &&
2971 i < old_local_description->description()->contents().size()) {
2972 old_local_content =
2973 &old_local_description->description()->contents()[i];
2974 }
2975 const cricket::ContentInfo* old_remote_content = nullptr;
2976 if (old_remote_description &&
2977 i < old_remote_description->description()->contents().size()) {
2978 old_remote_content =
2979 &old_remote_description->description()->contents()[i];
2980 }
Steve Antondcc3c022017-12-22 16:02:54 -08002981 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002982 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2983 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002984 if (!transceiver_or_error.ok()) {
2985 return transceiver_or_error.MoveError();
2986 }
2987 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002988 RTCError error =
2989 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2990 if (!error.ok()) {
2991 return error;
2992 }
2993 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002994 if (GetDataMid() && new_content.name != *GetDataMid()) {
2995 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002996 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2997 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002998 continue;
2999 }
3000 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3001 if (!error.ok()) {
3002 return error;
3003 }
Steve Antondcc3c022017-12-22 16:02:54 -08003004 } else {
3005 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3006 "Unknown section type.");
3007 }
3008 }
3009
3010 return RTCError::OK();
3011}
3012
3013RTCError PeerConnection::UpdateTransceiverChannel(
3014 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3015 transceiver,
3016 const cricket::ContentInfo& content,
3017 const cricket::ContentGroup* bundle_group) {
3018 RTC_DCHECK(IsUnifiedPlan());
3019 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003020 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003021 if (content.rejected) {
3022 if (channel) {
3023 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003024 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003025 }
3026 } else {
3027 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003028 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003029 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003030 } else {
Steve Anton69470252018-02-09 11:43:08 -08003031 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003032 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003033 }
3034 if (!channel) {
3035 LOG_AND_RETURN_ERROR(
3036 RTCErrorType::INTERNAL_ERROR,
3037 "Failed to create channel for mid=" + content.name);
3038 }
3039 transceiver->internal()->SetChannel(channel);
3040 }
3041 }
3042 return RTCError::OK();
3043}
3044
Steve Antonfa2260d2017-12-28 16:38:23 -08003045RTCError PeerConnection::UpdateDataChannel(
3046 cricket::ContentSource source,
3047 const cricket::ContentInfo& content,
3048 const cricket::ContentGroup* bundle_group) {
3049 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003050 // If data channels are disabled, ignore this media section. CreateAnswer
3051 // will take care of rejecting it.
3052 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003053 }
3054 if (content.rejected) {
3055 DestroyDataChannel();
3056 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003057 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003058 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003059 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3060 "Failed to create data channel.");
3061 }
3062 }
3063 if (source == cricket::CS_REMOTE) {
3064 const MediaContentDescription* data_desc = content.media_description();
3065 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3066 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3067 }
3068 }
3069 }
3070 return RTCError::OK();
3071}
3072
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003073// This method will extract any send encodings that were sent by the remote
3074// connection. This is currently only relevant for Simulcast scenario (where
3075// the number of layers may be communicated by the server).
3076static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3077 const MediaContentDescription& desc) {
3078 if (!desc.HasSimulcast()) {
3079 return {};
3080 }
3081 std::vector<RtpEncodingParameters> result;
3082 const SimulcastDescription& simulcast = desc.simulcast_description();
3083
3084 // This is a remote description, the parameters we are after should appear
3085 // as receive streams.
3086 for (const auto& alternatives : simulcast.receive_layers()) {
3087 RTC_DCHECK(!alternatives.empty());
3088 // There is currently no way to specify or choose from alternatives.
3089 // We will always use the first alternative, which is the most preferred.
3090 const SimulcastLayer& layer = alternatives[0];
3091 RtpEncodingParameters parameters;
3092 parameters.rid = layer.rid;
3093 parameters.active = !layer.is_paused;
3094 result.push_back(parameters);
3095 }
3096
3097 return result;
3098}
3099
3100static RTCError UpdateSimulcastLayerStatusInSender(
3101 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003102 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003103 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003104 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003105 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003106
3107 // The simulcast envelope cannot be changed, only the status of the streams.
3108 // So we will iterate over the send encodings rather than the layers.
3109 for (RtpEncodingParameters& encoding : parameters.encodings) {
3110 auto iter = std::find_if(layers.begin(), layers.end(),
3111 [&encoding](const SimulcastLayer& layer) {
3112 return layer.rid == encoding.rid;
3113 });
3114 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003115 if (iter == layers.end()) {
3116 disabled_layers.push_back(encoding.rid);
3117 continue;
3118 }
3119
3120 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003121 }
3122
Amit Hilbuch619b2942019-02-26 15:55:19 -08003123 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003124 if (result.ok()) {
3125 result = sender->DisableEncodingLayers(disabled_layers);
3126 }
3127
3128 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003129}
3130
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003131static bool SimulcastIsRejected(
3132 const ContentInfo* local_content,
3133 const MediaContentDescription& answer_media_desc) {
3134 bool simulcast_offered = local_content &&
3135 local_content->media_description() &&
3136 local_content->media_description()->HasSimulcast();
3137 bool simulcast_answered = answer_media_desc.HasSimulcast();
3138 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3139 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3140 return simulcast_offered && (!simulcast_answered || !rids_supported);
3141}
3142
Amit Hilbuch2297d332019-02-19 12:49:22 -08003143static RTCError DisableSimulcastInSender(
3144 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003145 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003146 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003147 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003148 return RTCError::OK();
3149 }
3150
Amit Hilbuch2297d332019-02-19 12:49:22 -08003151 std::vector<std::string> disabled_layers;
3152 std::transform(
3153 parameters.encodings.begin() + 1, parameters.encodings.end(),
3154 std::back_inserter(disabled_layers),
3155 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3156 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003157}
3158
Steve Antondcc3c022017-12-22 16:02:54 -08003159RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3160PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003161 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003162 size_t mline_index,
3163 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003164 const ContentInfo* old_local_content,
3165 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003166 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003167 // If this is an offer then the m= section might be recycled. If the m=
3168 // section is being recycled (defined as: rejected in the current local or
3169 // remote description and not rejected in new description), dissociate the
3170 // currently associated RtpTransceiver by setting its mid property to null,
3171 // and discard the mapping between the transceiver and its m= section index.
3172 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3173 old_remote_content)) {
3174 // We want to dissociate the transceiver that has the rejected mid.
3175 const std::string& old_mid =
3176 (old_local_content && old_local_content->rejected)
3177 ? old_local_content->name
3178 : old_remote_content->name;
3179 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003180 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003181 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3182 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003183 old_transceiver->internal()->set_mid(absl::nullopt);
3184 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003185 }
3186 }
3187 const MediaContentDescription* media_desc = content.media_description();
3188 auto transceiver = GetAssociatedTransceiver(content.name);
3189 if (source == cricket::CS_LOCAL) {
3190 // Find the RtpTransceiver that corresponds to this m= section, using the
3191 // mapping between transceivers and m= section indices established when
3192 // creating the offer.
3193 if (!transceiver) {
3194 transceiver = GetTransceiverByMLineIndex(mline_index);
3195 }
3196 if (!transceiver) {
3197 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3198 "Unknown transceiver");
3199 }
3200 } else {
3201 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3202 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3203 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003204 // When simulcast is requested, a transceiver cannot be associated because
3205 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003206 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003207 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3208 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003209 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3210 }
3211 // If no RtpTransceiver was found in the previous step, create one with a
3212 // recvonly direction.
3213 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003214 RTC_LOG(LS_INFO) << "Adding "
3215 << cricket::MediaTypeToString(media_desc->type())
3216 << " transceiver for MID=" << content.name
3217 << " at i=" << mline_index
3218 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003219 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003220 std::vector<RtpEncodingParameters> send_encodings =
3221 GetSendEncodingsFromRemoteDescription(*media_desc);
3222 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3223 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003224 std::string receiver_id;
3225 if (!media_desc->streams().empty()) {
3226 receiver_id = media_desc->streams()[0].id;
3227 } else {
3228 receiver_id = rtc::CreateRandomUuid();
3229 }
3230 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003231 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003232 transceiver->internal()->set_direction(
3233 RtpTransceiverDirection::kRecvOnly);
3234 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003235
3236 // Check if the offer indicated simulcast but the answer rejected it.
3237 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003238 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003239 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003240 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003241 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003242 if (!error.ok()) {
3243 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3244 return std::move(error);
3245 }
3246 }
Steve Antondcc3c022017-12-22 16:02:54 -08003247 }
3248 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003249 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003250 LOG_AND_RETURN_ERROR(
3251 RTCErrorType::INVALID_PARAMETER,
3252 "Transceiver type does not match media description type.");
3253 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003254 if (media_desc->HasSimulcast()) {
3255 std::vector<SimulcastLayer> layers =
3256 source == cricket::CS_LOCAL
3257 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3258 : media_desc->simulcast_description()
3259 .receive_layers()
3260 .GetAllLayers();
3261 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003262 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003263 if (!error.ok()) {
3264 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3265 return std::move(error);
3266 }
3267 }
Steve Antondcc3c022017-12-22 16:02:54 -08003268 // Associate the found or created RtpTransceiver with the m= section by
3269 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3270 // section, and establish a mapping between the transceiver and the index of
3271 // the m= section.
3272 transceiver->internal()->set_mid(content.name);
3273 transceiver->internal()->set_mline_index(mline_index);
3274 return std::move(transceiver);
3275}
3276
3277rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3278PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3279 RTC_DCHECK(IsUnifiedPlan());
3280 for (auto transceiver : transceivers_) {
3281 if (transceiver->mid() == mid) {
3282 return transceiver;
3283 }
3284 }
3285 return nullptr;
3286}
3287
3288rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3289PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3290 RTC_DCHECK(IsUnifiedPlan());
3291 for (auto transceiver : transceivers_) {
3292 if (transceiver->internal()->mline_index() == mline_index) {
3293 return transceiver;
3294 }
3295 }
3296 return nullptr;
3297}
3298
3299rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3300PeerConnection::FindAvailableTransceiverToReceive(
3301 cricket::MediaType media_type) const {
3302 RTC_DCHECK(IsUnifiedPlan());
3303 // From JSEP section 5.10 (Applying a Remote Description):
3304 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3305 // the same type that were added to the PeerConnection by addTrack and are not
3306 // associated with any m= section and are not stopped, find the first such
3307 // RtpTransceiver.
3308 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003309 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003310 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3311 !transceiver->stopped()) {
3312 return transceiver;
3313 }
3314 }
3315 return nullptr;
3316}
3317
Steve Antoned10bd92017-12-05 10:52:59 -08003318const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3319 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3320 transceiver,
3321 const SessionDescriptionInterface* sdesc) const {
3322 RTC_DCHECK(transceiver);
3323 RTC_DCHECK(sdesc);
3324 if (IsUnifiedPlan()) {
3325 if (!transceiver->internal()->mid()) {
3326 // This transceiver is not associated with a media section yet.
3327 return nullptr;
3328 }
3329 return sdesc->description()->GetContentByName(
3330 *transceiver->internal()->mid());
3331 } else {
3332 // Plan B only allows at most one audio and one video section, so use the
3333 // first media section of that type.
3334 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003335 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003336 }
3337}
3338
deadbeef46c73892016-11-16 19:42:04 -08003339PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003340 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003341 return configuration_;
3342}
3343
deadbeef293e9262017-01-11 12:28:30 -08003344bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3345 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003346 RTC_DCHECK_RUN_ON(signaling_thread());
3347 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003348 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003349 if (IsClosed()) {
3350 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3351 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3352 }
3353
Qingsi Wanga2d60672018-04-11 16:57:45 -07003354 // According to JSEP, after setLocalDescription, changing the candidate pool
3355 // size is not allowed, and changing the set of ICE servers will not result
3356 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003357 if (local_description() && configuration.ice_candidate_pool_size !=
3358 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003359 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3360 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003361 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003362 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003363
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003364 if (local_description() &&
3365 configuration.use_media_transport != configuration_.use_media_transport) {
3366 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3367 "SetLocalDescription.";
3368 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3369 }
3370
3371 if (remote_description() &&
3372 configuration.use_media_transport != configuration_.use_media_transport) {
3373 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3374 "SetRemoteDescription.";
3375 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3376 }
3377
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003378 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003379 configuration.use_media_transport_for_data_channels !=
3380 configuration_.use_media_transport_for_data_channels) {
3381 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3382 "after calling SetLocalDescription.";
3383 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3384 }
3385
3386 if (remote_description() &&
3387 configuration.use_media_transport_for_data_channels !=
3388 configuration_.use_media_transport_for_data_channels) {
3389 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3390 "after calling SetRemoteDescription.";
3391 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3392 }
3393
3394 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003395 configuration.crypto_options != configuration_.crypto_options) {
3396 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3397 "SetLocalDescription.";
3398 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3399 }
3400
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003401 if (configuration.use_media_transport_for_data_channels ||
3402 configuration.use_media_transport) {
3403 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3404 << "Media transport requires MaxBundle policy.";
3405 }
3406
deadbeef293e9262017-01-11 12:28:30 -08003407 // The simplest (and most future-compatible) way to tell if the config was
3408 // modified in an invalid way is to copy each property we do support
3409 // modifying, then use operator==. There are far more properties we don't
3410 // support modifying than those we do, and more could be added.
3411 RTCConfiguration modified_config = configuration_;
3412 modified_config.servers = configuration.servers;
3413 modified_config.type = configuration.type;
3414 modified_config.ice_candidate_pool_size =
3415 configuration.ice_candidate_pool_size;
3416 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003417 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003418 modified_config.ice_check_interval_strong_connectivity =
3419 configuration.ice_check_interval_strong_connectivity;
3420 modified_config.ice_check_interval_weak_connectivity =
3421 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003422 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3423 modified_config.ice_unwritable_min_checks =
3424 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003425 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003426 modified_config.stun_candidate_keepalive_interval =
3427 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003428 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003429 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003430 modified_config.active_reset_srtp_params =
3431 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003432 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003433 modified_config.use_media_transport_for_data_channels =
3434 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003435 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003436 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003437 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3438 }
3439
Steve Anton038834f2017-07-14 15:59:59 -07003440 // Validate the modified configuration.
3441 RTCError validate_error = ValidateConfiguration(modified_config);
3442 if (!validate_error.ok()) {
3443 return SafeSetError(std::move(validate_error), error);
3444 }
3445
deadbeef293e9262017-01-11 12:28:30 -08003446 // Note that this isn't possible through chromium, since it's an unsigned
3447 // short in WebIDL.
3448 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003449 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003450 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3451 }
3452
3453 // Parse ICE servers before hopping to network thread.
3454 cricket::ServerAddresses stun_servers;
3455 std::vector<cricket::RelayServerConfig> turn_servers;
3456 RTCErrorType parse_error =
3457 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3458 if (parse_error != RTCErrorType::NONE) {
3459 return SafeSetError(parse_error, error);
3460 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003461 // Note if STUN or TURN servers were supplied.
3462 if (!stun_servers.empty()) {
3463 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3464 }
3465 if (!turn_servers.empty()) {
3466 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3467 }
deadbeef293e9262017-01-11 12:28:30 -08003468
3469 // In theory this shouldn't fail.
3470 if (!network_thread()->Invoke<bool>(
3471 RTC_FROM_HERE,
3472 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3473 stun_servers, turn_servers, modified_config.type,
3474 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003475 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003476 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003477 modified_config.stun_candidate_keepalive_interval,
3478 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003479 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003480 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3481 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003482
deadbeefd1a38b52016-12-10 13:15:33 -08003483 // As described in JSEP, calling setConfiguration with new ICE servers or
3484 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3485 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003486 if (modified_config.servers != configuration_.servers ||
3487 modified_config.type != configuration_.type ||
3488 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003489 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003490 }
skvladd1f5fda2017-02-03 16:54:05 -08003491
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003492 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003493 transport_controller_->SetMediaTransportSettings(
3494 modified_config.use_media_transport,
3495 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003496
Zhi Huangb57e1692018-06-12 11:41:11 -07003497 if (configuration_.active_reset_srtp_params !=
3498 modified_config.active_reset_srtp_params) {
3499 transport_controller_->SetActiveResetSrtpParams(
3500 modified_config.active_reset_srtp_params);
3501 }
3502
deadbeef293e9262017-01-11 12:28:30 -08003503 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003504 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003505 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003506}
3507
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508bool PeerConnection::AddIceCandidate(
3509 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003510 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003511 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003512 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003513 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003514 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003515 return false;
3516 }
Steve Antond25da372017-11-06 14:50:29 -08003517
3518 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003519 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003520 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003521 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003522 return false;
3523 }
3524
3525 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003526 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003527 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003528 return false;
3529 }
3530
3531 bool valid = false;
3532 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3533 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003534 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003535 return false;
3536 }
3537
3538 // Add this candidate to the remote session description.
3539 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003540 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003541 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003542 return false;
3543 }
3544
3545 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003546 bool result = UseCandidate(ice_candidate);
3547 if (result) {
3548 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3549 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3550 } else {
3551 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3552 }
3553 return result;
Steve Antond25da372017-11-06 14:50:29 -08003554 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003555 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003556 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003557 return true;
3558 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003559}
3560
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003561bool PeerConnection::RemoveIceCandidates(
3562 const std::vector<cricket::Candidate>& candidates) {
3563 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003564 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003565 if (IsClosed()) {
3566 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3567 return false;
3568 }
3569
Steve Antond25da372017-11-06 14:50:29 -08003570 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003571 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3572 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003573 return false;
3574 }
3575
3576 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003577 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003578 return false;
3579 }
3580
3581 size_t number_removed =
3582 mutable_remote_description()->RemoveCandidates(candidates);
3583 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003584 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003585 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003586 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003587 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003588 }
3589
3590 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003591 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3592 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003593 RTC_LOG(LS_ERROR)
3594 << "RemoveIceCandidates: Error when removing remote candidates: "
3595 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003596 }
3597 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003598}
3599
Niels Möller0c4f7be2018-05-07 14:01:37 +02003600RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003601 if (!worker_thread()->IsCurrent()) {
3602 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003603 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003604 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003605 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003606
Niels Möller0c4f7be2018-05-07 14:01:37 +02003607 const bool has_min = bitrate.min_bitrate_bps.has_value();
3608 const bool has_start = bitrate.start_bitrate_bps.has_value();
3609 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003610 if (has_min && *bitrate.min_bitrate_bps < 0) {
3611 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3612 "min_bitrate_bps <= 0");
3613 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003614 if (has_start) {
3615 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003616 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003617 "start_bitrate_bps < min_bitrate_bps");
3618 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003619 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3620 "curent_bitrate_bps < 0");
3621 }
3622 }
3623 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003624 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003625 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003626 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003627 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3628 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3629 "max_bitrate_bps < min_bitrate_bps");
3630 } else if (*bitrate.max_bitrate_bps < 0) {
3631 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3632 "max_bitrate_bps < 0");
3633 }
3634 }
3635
zstein4b979802017-06-02 14:37:37 -07003636 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003637 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003638
3639 return RTCError::OK();
3640}
3641
Alex Narest78609d52017-10-20 10:37:47 +02003642void PeerConnection::SetBitrateAllocationStrategy(
3643 std::unique_ptr<rtc::BitrateAllocationStrategy>
3644 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003645 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003646 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3647 // move-capture values in lambdas.
3648 struct Task {
3649 PeerConnection* const pc;
3650 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3651 void operator()() {
3652 RTC_DCHECK_RUN_ON(pc->worker_thread());
3653 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3654 }
3655 };
3656 worker_thread()->Invoke<void>(
3657 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003658 return;
3659 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003660 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003661 RTC_DCHECK(call_.get());
3662 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3663}
3664
henrika5f6bf242017-11-01 11:06:56 +01003665void PeerConnection::SetAudioPlayout(bool playout) {
3666 if (!worker_thread()->IsCurrent()) {
3667 worker_thread()->Invoke<void>(
3668 RTC_FROM_HERE,
3669 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3670 return;
3671 }
3672 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003673 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003674 audio_state->SetPlayout(playout);
3675}
3676
3677void PeerConnection::SetAudioRecording(bool recording) {
3678 if (!worker_thread()->IsCurrent()) {
3679 worker_thread()->Invoke<void>(
3680 RTC_FROM_HERE,
3681 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3682 return;
3683 }
3684 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003685 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003686 audio_state->SetRecording(recording);
3687}
3688
Steve Anton8c0f7a72017-10-03 10:03:10 -07003689std::unique_ptr<rtc::SSLCertificate>
3690PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003691 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3692 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003693 return nullptr;
3694 }
Steve Antonf25303e2018-10-16 15:23:31 -07003695 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003696}
3697
Zhi Huang70b820f2018-01-27 14:16:15 -08003698std::unique_ptr<rtc::SSLCertChain>
3699PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003700 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003701 auto audio_transceiver = GetFirstAudioTransceiver();
3702 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003703 return nullptr;
3704 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003705 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003706 audio_transceiver->internal()->channel()->transport_name());
3707}
3708
3709rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3710PeerConnection::GetFirstAudioTransceiver() const {
3711 for (auto transceiver : transceivers_) {
3712 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3713 return transceiver;
3714 }
3715 }
3716 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003717}
3718
ivoc14d5dbe2016-07-04 07:06:55 -07003719bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3720 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003721 // TODO(eladalon): It would be better to not allow negative values into PC.
3722 const size_t max_size = (max_size_bytes < 0)
3723 ? RtcEventLog::kUnlimitedOutput
3724 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003725 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3726 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3727 output_period_ms = 5000;
3728 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003729 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003730 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003731 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003732}
3733
Bjorn Tereliusde939432017-11-20 17:38:14 +01003734bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3735 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003736 // TODO(eladalon): In C++14, this can be done with a lambda.
3737 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003738 bool operator()() {
3739 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3740 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003741 PeerConnection* const pc;
3742 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003743 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003744 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003745 return worker_thread()->Invoke<bool>(
3746 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003747}
3748
3749void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003750 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003751 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3752}
3753
Harald Alvestrandad88c882018-11-28 16:47:46 +01003754rtc::scoped_refptr<DtlsTransportInterface>
3755PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003756 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003757 return transport_controller_->LookupDtlsTransportByMid(mid);
3758}
3759
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003760rtc::scoped_refptr<DtlsTransport>
3761PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003762 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003763 return transport_controller_->LookupDtlsTransportByMid(mid);
3764}
3765
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003766rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3767 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003768 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003769 return sctp_transport_;
3770}
3771
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003772const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003773 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003774 return pending_local_description_ ? pending_local_description_.get()
3775 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003776}
3777
3778const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003779 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003780 return pending_remote_description_ ? pending_remote_description_.get()
3781 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003782}
3783
deadbeeffe4a8a42016-12-20 17:56:17 -08003784const SessionDescriptionInterface* PeerConnection::current_local_description()
3785 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003786 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003787 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003788}
3789
3790const SessionDescriptionInterface* PeerConnection::current_remote_description()
3791 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003792 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003793 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003794}
3795
3796const SessionDescriptionInterface* PeerConnection::pending_local_description()
3797 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_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003800}
3801
3802const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3803 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003804 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003805 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003806}
3807
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003808void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003809 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003810 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003811 // Update stats here so that we have the most recent stats for tracks and
3812 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003813 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003814
Steve Anton75737c02017-11-06 10:37:17 -08003815 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003816 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003817
Mirko Bonadei739baf02019-01-27 17:29:42 +01003818 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003819 transceiver->Stop();
3820 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003821
3822 // Ensure that all asynchronous stats requests are completed before destroying
3823 // the transport controller below.
3824 if (stats_collector_) {
3825 stats_collector_->WaitForPendingRequest();
3826 }
3827
3828 // Don't destroy BaseChannels until after stats has been cleaned up so that
3829 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003830 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003831
Qingsi Wang93a84392018-01-30 17:13:09 -08003832 // The event log is used in the transport controller, which must be outlived
3833 // by the former. CreateOffer by the peer connection is implemented
3834 // asynchronously and if the peer connection is closed without resetting the
3835 // WebRTC session description factory, the session description factory would
3836 // call the transport controller.
3837 webrtc_session_desc_factory_.reset();
3838 transport_controller_.reset();
3839
deadbeef42a42632017-03-10 15:18:00 -08003840 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003841 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3842 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003843
Steve Anton978b8762017-09-29 12:15:02 -07003844 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003845 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003846 call_.reset();
3847 // The event log must outlive call (and any other object that uses it).
3848 event_log_.reset();
3849 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003850 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003851 // The .h file says that observer can be discarded after close() returns.
3852 // Make sure this is true.
3853 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003854}
3855
Steve Antonad182762018-09-05 20:22:40 +00003856void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003857 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003858 switch (msg->message_id) {
3859 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3860 SetSessionDescriptionMsg* param =
3861 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3862 param->observer->OnSuccess();
3863 delete param;
3864 break;
3865 }
3866 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3867 SetSessionDescriptionMsg* param =
3868 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3869 param->observer->OnFailure(std::move(param->error));
3870 delete param;
3871 break;
3872 }
3873 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3874 CreateSessionDescriptionMsg* param =
3875 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3876 param->observer->OnFailure(std::move(param->error));
3877 delete param;
3878 break;
3879 }
3880 case MSG_GETSTATS: {
3881 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3882 StatsReports reports;
3883 stats_->GetStats(param->track, &reports);
3884 param->observer->OnComplete(reports);
3885 delete param;
3886 break;
3887 }
3888 case MSG_FREE_DATACHANNELS: {
3889 sctp_data_channels_to_free_.clear();
3890 break;
3891 }
3892 case MSG_REPORT_USAGE_PATTERN: {
3893 ReportUsagePattern();
3894 break;
3895 }
3896 default:
3897 RTC_NOTREACHED() << "Not implemented";
3898 break;
3899 }
3900}
3901
Steve Antonafb0bb72018-02-20 11:35:37 -08003902cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3903 RTC_DCHECK(!IsUnifiedPlan());
3904 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3905 GetAudioTransceiver()->internal()->channel());
3906 if (voice_channel) {
3907 return voice_channel->media_channel();
3908 } else {
3909 return nullptr;
3910 }
3911}
3912
3913cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3914 RTC_DCHECK(!IsUnifiedPlan());
3915 auto* video_channel = static_cast<cricket::VideoChannel*>(
3916 GetVideoTransceiver()->internal()->channel());
3917 if (video_channel) {
3918 return video_channel->media_channel();
3919 } else {
3920 return nullptr;
3921 }
3922}
3923
Steve Anton4171afb2017-11-20 10:20:22 -08003924void PeerConnection::CreateAudioReceiver(
3925 MediaStreamInterface* stream,
3926 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003927 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3928 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003929 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3930 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003931 auto* audio_receiver = new AudioRtpReceiver(
3932 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003933 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003934 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3935 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3936 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003937 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003938 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003939 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003940}
3941
Steve Anton4171afb2017-11-20 10:20:22 -08003942void PeerConnection::CreateVideoReceiver(
3943 MediaStreamInterface* stream,
3944 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003945 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3946 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003947 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3948 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003949 auto* video_receiver = new VideoRtpReceiver(
3950 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003951 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003952 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3953 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3954 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003955 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003956 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003957 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003958}
3959
deadbeef70ab1a12015-09-28 16:53:55 -07003960// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3961// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003962rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003963 const RtpSenderInfo& remote_sender_info) {
3964 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3965 if (!receiver) {
3966 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3967 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003968 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003969 }
Steve Anton4171afb2017-11-20 10:20:22 -08003970 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3971 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3972 } else {
3973 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3974 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003975 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003976}
3977
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003978void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3979 MediaStreamInterface* stream) {
3980 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003981 RTC_DCHECK(track);
3982 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003983 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003984 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003985 // We already have a sender for this track, so just change the stream_id
3986 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003987 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003988 return;
3989 }
3990
3991 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003992 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003993 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003994 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003995 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003996 // If the sender has already been configured in SDP, we call SetSsrc,
3997 // which will connect the sender to the underlying transport. This can
3998 // occur if a local session description that contains the ID of the sender
3999 // is set before AddStream is called. It can also occur if the local
4000 // session description is not changed and RemoveStream is called, and
4001 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004002 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004003 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004004 if (sender_info) {
4005 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004006 }
4007}
4008
4009// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4010// indefinitely, when we have unified plan SDP.
4011void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4012 MediaStreamInterface* stream) {
4013 RTC_DCHECK(!IsClosed());
4014 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004015 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004016 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4017 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004018 return;
4019 }
Steve Anton4171afb2017-11-20 10:20:22 -08004020 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004021}
4022
4023void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4024 MediaStreamInterface* stream) {
4025 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004026 RTC_DCHECK(track);
4027 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004028 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004029 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004030 // We already have a sender for this track, so just change the stream_id
4031 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004032 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004033 return;
4034 }
4035
4036 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004037 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004038 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004039 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004040 GetVideoTransceiver()->internal()->AddSender(new_sender);
4041 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004042 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004043 if (sender_info) {
4044 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004045 }
4046}
4047
4048void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4049 MediaStreamInterface* stream) {
4050 RTC_DCHECK(!IsClosed());
4051 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004052 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004053 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4054 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004055 return;
4056 }
Steve Anton4171afb2017-11-20 10:20:22 -08004057 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004058}
4059
Steve Antonba818672017-11-06 10:21:57 -08004060void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004061 if (ice_connection_state_ == new_state) {
4062 return;
4063 }
4064
deadbeefcbecd352015-09-23 11:50:27 -07004065 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004066 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004067 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004068 return;
4069 }
Steve Antonba818672017-11-06 10:21:57 -08004070
Mirko Bonadei675513b2017-11-09 11:09:25 +01004071 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4072 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004073 RTC_DCHECK(ice_connection_state_ !=
4074 PeerConnectionInterface::kIceConnectionClosed);
4075
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004076 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004077 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004078}
4079
Alex Loiko9289eda2018-11-23 16:18:59 +00004080void PeerConnection::SetStandardizedIceConnectionState(
4081 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004082 if (standardized_ice_connection_state_ == new_state)
4083 return;
4084 if (IsClosed())
4085 return;
4086 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004087 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004088}
4089
Jonas Olsson635474e2018-10-18 15:58:17 +02004090void PeerConnection::SetConnectionState(
4091 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004092 if (connection_state_ == new_state)
4093 return;
4094 if (IsClosed())
4095 return;
4096 connection_state_ = new_state;
4097 Observer()->OnConnectionChange(new_state);
4098}
4099
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004100void PeerConnection::OnIceGatheringChange(
4101 PeerConnectionInterface::IceGatheringState new_state) {
4102 if (IsClosed()) {
4103 return;
4104 }
4105 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004106 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004107}
4108
jbauch81bf7b02017-03-25 08:31:12 -07004109void PeerConnection::OnIceCandidate(
4110 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004111 if (IsClosed()) {
4112 return;
4113 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004114 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004115 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4116 candidate->candidate().address().IsPrivateIP()) {
4117 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4118 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004119 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004120}
4121
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004122void PeerConnection::OnIceCandidatesRemoved(
4123 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004124 if (IsClosed()) {
4125 return;
4126 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004127 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004128}
4129
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004130void PeerConnection::ChangeSignalingState(
4131 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004132 if (signaling_state_ == signaling_state) {
4133 return;
4134 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004135 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4136 << GetSignalingStateString(signaling_state_)
4137 << " New state: "
4138 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004139 signaling_state_ = signaling_state;
4140 if (signaling_state == kClosed) {
4141 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004142 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004143 standardized_ice_connection_state_ =
4144 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004145 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4146 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004147 if (ice_gathering_state_ != kIceGatheringComplete) {
4148 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004149 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004150 }
4151 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004152 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004153}
4154
deadbeefeb459812015-12-15 19:24:43 -08004155void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4156 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004157 if (IsClosed()) {
4158 return;
4159 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004160 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004161 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004162}
4163
deadbeefeb459812015-12-15 19:24:43 -08004164void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4165 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004166 if (IsClosed()) {
4167 return;
4168 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004169 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004170 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004171}
4172
4173void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4174 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004175 if (IsClosed()) {
4176 return;
4177 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004178 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004179 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004180}
4181
4182void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4183 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004184 if (IsClosed()) {
4185 return;
4186 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004187 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004188 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004189}
4190
Henrik Boström31638672017-11-23 17:48:32 +01004191void PeerConnection::PostSetSessionDescriptionSuccess(
4192 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004193 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4194 signaling_thread()->Post(RTC_FROM_HERE, this,
4195 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004196}
4197
deadbeefab9b2d12015-10-14 11:33:11 -07004198void PeerConnection::PostSetSessionDescriptionFailure(
4199 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004200 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004201 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004202 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4203 msg->error = std::move(error);
4204 signaling_thread()->Post(RTC_FROM_HERE, this,
4205 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004206}
4207
4208void PeerConnection::PostCreateSessionDescriptionFailure(
4209 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004210 RTCError error) {
4211 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004212 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4213 msg->error = std::move(error);
4214 signaling_thread()->Post(RTC_FROM_HERE, this,
4215 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004216}
4217
zhihuang1c378ed2017-08-17 14:10:50 -07004218void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004219 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004220 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004221 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004222
Steve Antondcc3c022017-12-22 16:02:54 -08004223 if (IsUnifiedPlan()) {
4224 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4225 } else {
4226 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4227 }
4228
Steve Antonfa2260d2017-12-28 16:38:23 -08004229 // Intentionally unset the data channel type for RTP data channel with the
4230 // second condition. Otherwise the RTP data channels would be successfully
4231 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4232 // when building with chromium. We want to leave RTP data channels broken, so
4233 // people won't try to use them.
4234 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4235 session_options->data_channel_type = data_channel_type();
4236 }
4237
Steve Antondcc3c022017-12-22 16:02:54 -08004238 // Apply ICE restart flag and renomination flag.
4239 for (auto& options : session_options->media_description_options) {
4240 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4241 options.transport_options.enable_ice_renomination =
4242 configuration_.enable_ice_renomination;
4243 }
4244
4245 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004246 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004247 session_options->pooled_ice_credentials =
4248 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4249 RTC_FROM_HERE,
4250 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4251 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004252 session_options->offer_extmap_allow_mixed =
4253 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004254
4255 if (configuration_.enable_dtls_srtp &&
4256 !configuration_.enable_dtls_srtp.value()) {
4257 session_options->media_transport_settings =
4258 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4259 }
Steve Antondcc3c022017-12-22 16:02:54 -08004260}
4261
4262void PeerConnection::GetOptionsForPlanBOffer(
4263 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4264 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004265 // Figure out transceiver directional preferences.
4266 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4267 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4268
4269 // By default, generate sendrecv/recvonly m= sections.
4270 bool recv_audio = true;
4271 bool recv_video = true;
4272
4273 // By default, only offer a new m= section if we have media to send with it.
4274 bool offer_new_audio_description = send_audio;
4275 bool offer_new_video_description = send_video;
4276 bool offer_new_data_description = HasDataChannels();
4277
4278 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004279 if (offer_answer_options.offer_to_receive_audio !=
4280 RTCOfferAnswerOptions::kUndefined) {
4281 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004282 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004283 offer_new_audio_description ||
4284 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004285 }
Steve Antondcc3c022017-12-22 16:02:54 -08004286 if (offer_answer_options.offer_to_receive_video !=
4287 RTCOfferAnswerOptions::kUndefined) {
4288 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004289 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004290 offer_new_video_description ||
4291 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004292 }
4293
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004294 absl::optional<size_t> audio_index;
4295 absl::optional<size_t> video_index;
4296 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004297 // If a current description exists, generate m= sections in the same order,
4298 // using the first audio/video/data section that appears and rejecting
4299 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004300 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004301 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004302 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004303 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4304 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4305 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004306 }
4307
zhihuang1c378ed2017-08-17 14:10:50 -07004308 // Add audio/video/data m= sections to the end if needed.
4309 if (!audio_index && offer_new_audio_description) {
4310 session_options->media_description_options.push_back(
4311 cricket::MediaDescriptionOptions(
4312 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004313 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4314 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004315 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004316 }
zhihuang1c378ed2017-08-17 14:10:50 -07004317 if (!video_index && offer_new_video_description) {
4318 session_options->media_description_options.push_back(
4319 cricket::MediaDescriptionOptions(
4320 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004321 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4322 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004323 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004324 }
zhihuang1c378ed2017-08-17 14:10:50 -07004325 if (!data_index && offer_new_data_description) {
4326 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004327 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004328 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004329 }
4330
4331 cricket::MediaDescriptionOptions* audio_media_description_options =
4332 !audio_index ? nullptr
4333 : &session_options->media_description_options[*audio_index];
4334 cricket::MediaDescriptionOptions* video_media_description_options =
4335 !video_index ? nullptr
4336 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004337
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004338 AddPlanBRtpSenderOptions(GetSendersInternal(),
4339 audio_media_description_options,
4340 video_media_description_options,
4341 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004342}
4343
Steve Antondcc3c022017-12-22 16:02:54 -08004344static cricket::MediaDescriptionOptions
4345GetMediaDescriptionOptionsForTransceiver(
4346 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4347 transceiver,
4348 const std::string& mid) {
4349 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004350 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004351 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004352 // This behavior is specified in JSEP. The gist is that:
4353 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4354 // sendrecv.
4355 // 2. If the MSID is included, then it must be included in any subsequent
4356 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004357 if (transceiver->stopped() ||
4358 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4359 !transceiver->internal()->has_ever_been_used_to_send())) {
4360 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004361 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004362
4363 cricket::SenderOptions sender_options;
4364 sender_options.track_id = transceiver->sender()->id();
4365 sender_options.stream_ids = transceiver->sender()->stream_ids();
4366
4367 // The following sets up RIDs and Simulcast.
4368 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004369 RtpParameters send_parameters =
4370 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004371 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4372 send_parameters.encodings.end(),
4373 [](const RtpEncodingParameters& encoding) {
4374 return !encoding.rid.empty();
4375 });
4376
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004377 std::vector<RidDescription> send_rids;
4378 SimulcastLayerList send_layers;
4379 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4380 if (encoding.rid.empty()) {
4381 continue;
4382 }
4383 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4384 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4385 }
4386
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004387 if (has_rids) {
4388 sender_options.rids = send_rids;
4389 }
4390
4391 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004392 // When RIDs are configured, we must set num_sim_layers to 0 to.
4393 // Otherwise, num_sim_layers must be 1 because either there is no
4394 // simulcast, or simulcast is acheived by munging the SDP.
4395 sender_options.num_sim_layers = has_rids ? 0 : 1;
4396 media_description_options.sender_options.push_back(sender_options);
4397
Steve Antondcc3c022017-12-22 16:02:54 -08004398 return media_description_options;
4399}
4400
Steve Anton5c72e712018-12-10 14:25:30 -08004401// Returns the ContentInfo at mline index |i|, or null if none exists.
4402static const ContentInfo* GetContentByIndex(
4403 const SessionDescriptionInterface* sdesc,
4404 size_t i) {
4405 if (!sdesc) {
4406 return nullptr;
4407 }
4408 const ContentInfos& contents = sdesc->description()->contents();
4409 return (i < contents.size() ? &contents[i] : nullptr);
4410}
4411
Steve Antondcc3c022017-12-22 16:02:54 -08004412void PeerConnection::GetOptionsForUnifiedPlanOffer(
4413 const RTCOfferAnswerOptions& offer_answer_options,
4414 cricket::MediaSessionOptions* session_options) {
4415 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4416 // Offers) and 5.2.2 (Subsequent Offers).
4417 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4418 const ContentInfos& local_contents =
4419 (local_description() ? local_description()->description()->contents()
4420 : ContentInfos());
4421 const ContentInfos& remote_contents =
4422 (remote_description() ? remote_description()->description()->contents()
4423 : ContentInfos());
4424 // The mline indices that can be recycled. New transceivers should reuse these
4425 // slots first.
4426 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004427 // First, go through each media section that exists in either the local or
4428 // remote description and generate a media section in this offer for the
4429 // associated transceiver. If a media section can be recycled, generate a
4430 // default, rejected media section here that can be later overwritten.
4431 for (size_t i = 0;
4432 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4433 // Either |local_content| or |remote_content| is non-null.
4434 const ContentInfo* local_content =
4435 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004436 const ContentInfo* current_local_content =
4437 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004438 const ContentInfo* remote_content =
4439 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004440 const ContentInfo* current_remote_content =
4441 GetContentByIndex(current_remote_description(), i);
4442 bool had_been_rejected =
4443 (current_local_content && current_local_content->rejected) ||
4444 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004445 const std::string& mid =
4446 (local_content ? local_content->name : remote_content->name);
4447 cricket::MediaType media_type =
4448 (local_content ? local_content->media_description()->type()
4449 : remote_content->media_description()->type());
4450 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4451 media_type == cricket::MEDIA_TYPE_VIDEO) {
4452 auto transceiver = GetAssociatedTransceiver(mid);
4453 RTC_CHECK(transceiver);
4454 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004455 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004456 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004457 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004458 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4459 RtpTransceiverDirection::kInactive,
4460 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004461 recycleable_mline_indices.push(i);
4462 } else {
4463 session_options->media_description_options.push_back(
4464 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4465 // CreateOffer shouldn't really cause any state changes in
4466 // PeerConnection, but we need a way to match new transceivers to new
4467 // media sections in SetLocalDescription and JSEP specifies this is done
4468 // by recording the index of the media section generated for the
4469 // transceiver in the offer.
4470 transceiver->internal()->set_mline_index(i);
4471 }
4472 } else {
4473 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004474 RTC_CHECK(GetDataMid());
4475 if (had_been_rejected || mid != *GetDataMid()) {
4476 session_options->media_description_options.push_back(
4477 GetMediaDescriptionOptionsForRejectedData(mid));
4478 } else {
4479 session_options->media_description_options.push_back(
4480 GetMediaDescriptionOptionsForActiveData(mid));
4481 }
Steve Antondcc3c022017-12-22 16:02:54 -08004482 }
4483 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004484
Steve Antondcc3c022017-12-22 16:02:54 -08004485 // Next, look for transceivers that are newly added (that is, are not stopped
4486 // and not associated). Reuse media sections marked as recyclable first,
4487 // otherwise append to the end of the offer. New media sections should be
4488 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004489 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004490 if (transceiver->mid() || transceiver->stopped()) {
4491 continue;
4492 }
4493 size_t mline_index;
4494 if (!recycleable_mline_indices.empty()) {
4495 mline_index = recycleable_mline_indices.front();
4496 recycleable_mline_indices.pop();
4497 session_options->media_description_options[mline_index] =
4498 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004499 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004500 } else {
4501 mline_index = session_options->media_description_options.size();
4502 session_options->media_description_options.push_back(
4503 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004504 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004505 }
4506 // See comment above for why CreateOffer changes the transceiver's state.
4507 transceiver->internal()->set_mline_index(mline_index);
4508 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004509 // Lastly, add a m-section if we have local data channels and an m section
4510 // does not already exist.
4511 if (!GetDataMid() && HasDataChannels()) {
4512 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004513 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004514 }
Steve Antondcc3c022017-12-22 16:02:54 -08004515}
4516
4517void PeerConnection::GetOptionsForAnswer(
4518 const RTCOfferAnswerOptions& offer_answer_options,
4519 cricket::MediaSessionOptions* session_options) {
4520 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4521
4522 if (IsUnifiedPlan()) {
4523 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4524 } else {
4525 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4526 }
4527
Steve Antonfa2260d2017-12-28 16:38:23 -08004528 // Intentionally unset the data channel type for RTP data channel. Otherwise
4529 // the RTP data channels would be successfully negotiated by default and the
4530 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4531 // We want to leave RTP data channels broken, so people won't try to use them.
4532 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4533 session_options->data_channel_type = data_channel_type();
4534 }
4535
Steve Antondcc3c022017-12-22 16:02:54 -08004536 // Apply ICE renomination flag.
4537 for (auto& options : session_options->media_description_options) {
4538 options.transport_options.enable_ice_renomination =
4539 configuration_.enable_ice_renomination;
4540 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004541
4542 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004543 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004544 session_options->pooled_ice_credentials =
4545 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4546 RTC_FROM_HERE,
4547 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4548 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004549}
4550
Steve Antondcc3c022017-12-22 16:02:54 -08004551void PeerConnection::GetOptionsForPlanBAnswer(
4552 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004553 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004554 // Figure out transceiver directional preferences.
4555 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4556 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4557
4558 // By default, generate sendrecv/recvonly m= sections. The direction is also
4559 // restricted by the direction in the offer.
4560 bool recv_audio = true;
4561 bool recv_video = true;
4562
4563 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004564 if (offer_answer_options.offer_to_receive_audio !=
4565 RTCOfferAnswerOptions::kUndefined) {
4566 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004567 }
Steve Antondcc3c022017-12-22 16:02:54 -08004568 if (offer_answer_options.offer_to_receive_video !=
4569 RTCOfferAnswerOptions::kUndefined) {
4570 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004571 }
4572
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004573 absl::optional<size_t> audio_index;
4574 absl::optional<size_t> video_index;
4575 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004576
4577 // Generate m= sections that match those in the offer.
4578 // Note that mediasession.cc will handle intersection our preferred
4579 // direction with the offered direction.
4580 GenerateMediaDescriptionOptions(
4581 remote_description(),
4582 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4583 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4584 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004585
4586 cricket::MediaDescriptionOptions* audio_media_description_options =
4587 !audio_index ? nullptr
4588 : &session_options->media_description_options[*audio_index];
4589 cricket::MediaDescriptionOptions* video_media_description_options =
4590 !video_index ? nullptr
4591 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004592
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004593 AddPlanBRtpSenderOptions(GetSendersInternal(),
4594 audio_media_description_options,
4595 video_media_description_options,
4596 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004597}
zhihuangaf388472016-11-02 16:49:48 -07004598
Steve Antondcc3c022017-12-22 16:02:54 -08004599void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4600 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4601 cricket::MediaSessionOptions* session_options) {
4602 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4603 // Answers) and 5.3.2 (Subsequent Answers).
4604 RTC_DCHECK(remote_description());
4605 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4606 for (const ContentInfo& content :
4607 remote_description()->description()->contents()) {
4608 cricket::MediaType media_type = content.media_description()->type();
4609 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4610 media_type == cricket::MEDIA_TYPE_VIDEO) {
4611 auto transceiver = GetAssociatedTransceiver(content.name);
4612 RTC_CHECK(transceiver);
4613 session_options->media_description_options.push_back(
4614 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4615 } else {
4616 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004617 // Reject all data sections if data channels are disabled.
4618 // Reject a data section if it has already been rejected.
4619 // Reject all data sections except for the first one.
4620 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4621 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004622 session_options->media_description_options.push_back(
4623 GetMediaDescriptionOptionsForRejectedData(content.name));
4624 } else {
4625 session_options->media_description_options.push_back(
4626 GetMediaDescriptionOptionsForActiveData(content.name));
4627 }
Steve Antondcc3c022017-12-22 16:02:54 -08004628 }
4629 }
htaa2a49d92016-03-04 02:51:39 -08004630}
4631
zhihuang1c378ed2017-08-17 14:10:50 -07004632void PeerConnection::GenerateMediaDescriptionOptions(
4633 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004634 RtpTransceiverDirection audio_direction,
4635 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004636 absl::optional<size_t>* audio_index,
4637 absl::optional<size_t>* video_index,
4638 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004639 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004640 for (const cricket::ContentInfo& content :
4641 session_desc->description()->contents()) {
4642 if (IsAudioContent(&content)) {
4643 // If we already have an audio m= section, reject this extra one.
4644 if (*audio_index) {
4645 session_options->media_description_options.push_back(
4646 cricket::MediaDescriptionOptions(
4647 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004648 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004649 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004650 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004651 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004652 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4653 content.name, audio_direction,
4654 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004655 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004656 }
4657 } else if (IsVideoContent(&content)) {
4658 // If we already have an video m= section, reject this extra one.
4659 if (*video_index) {
4660 session_options->media_description_options.push_back(
4661 cricket::MediaDescriptionOptions(
4662 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004663 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004664 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004665 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004666 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004667 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4668 content.name, video_direction,
4669 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004670 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004671 }
4672 } else {
4673 RTC_DCHECK(IsDataContent(&content));
4674 // If we already have an data m= section, reject this extra one.
4675 if (*data_index) {
4676 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004677 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004678 } else {
4679 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004680 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004681 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004682 }
4683 }
htaa2a49d92016-03-04 02:51:39 -08004684 }
deadbeefab9b2d12015-10-14 11:33:11 -07004685}
4686
Steve Antonfa2260d2017-12-28 16:38:23 -08004687cricket::MediaDescriptionOptions
4688PeerConnection::GetMediaDescriptionOptionsForActiveData(
4689 const std::string& mid) const {
4690 // Direction for data sections is meaningless, but legacy endpoints might
4691 // expect sendrecv.
4692 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4693 RtpTransceiverDirection::kSendRecv,
4694 /*stopped=*/false);
4695 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4696 return options;
4697}
4698
4699cricket::MediaDescriptionOptions
4700PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4701 const std::string& mid) const {
4702 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4703 RtpTransceiverDirection::kInactive,
4704 /*stopped=*/true);
4705 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4706 return options;
4707}
4708
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004709absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004710 switch (data_channel_type_) {
4711 case cricket::DCT_RTP:
4712 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004713 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004714 }
4715 return rtp_data_channel_->content_name();
4716 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004717 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004718 case cricket::DCT_MEDIA_TRANSPORT:
4719 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004720 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004721 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004722 }
4723}
4724
Steve Anton4171afb2017-11-20 10:20:22 -08004725void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4726 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4727 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004728 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004729}
4730
Steve Anton4171afb2017-11-20 10:20:22 -08004731void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004732 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004733 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004734 cricket::MediaType media_type,
4735 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004736 RTC_DCHECK(!IsUnifiedPlan());
4737
Steve Anton4171afb2017-11-20 10:20:22 -08004738 std::vector<RtpSenderInfo>* current_senders =
4739 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004740
Steve Anton4171afb2017-11-20 10:20:22 -08004741 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004742 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004743 for (auto sender_it = current_senders->begin();
4744 sender_it != current_senders->end();
4745 /* incremented manually */) {
4746 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004747 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004748 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004749 std::string params_stream_id;
4750 if (params) {
4751 params_stream_id =
4752 (!params->first_stream_id().empty() ? params->first_stream_id()
4753 : kDefaultStreamId);
4754 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004755 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004756 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004757 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004758 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004759 sender_exists) {
4760 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004761 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004762 OnRemoteSenderRemoved(info, media_type);
4763 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004764 }
4765 }
4766
Steve Anton4171afb2017-11-20 10:20:22 -08004767 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004768 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004769 if (!params.has_ssrcs()) {
4770 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4771 // sender, this means it is coming from a Unified Plan endpoint,so we just
4772 // create a default.
4773 default_sender_needed = true;
4774 break;
4775 }
4776
Seth Hampson845e8782018-03-02 11:34:10 -08004777 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004778 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004779 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4780 // not supported in Plan B, we just take the first here and create the
4781 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004782 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004783 (!params.first_stream_id().empty() ? params.first_stream_id()
4784 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004785 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004786 uint32_t ssrc = params.first_ssrc();
4787
4788 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004789 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004790 if (!stream) {
4791 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004792 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004793 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004794 remote_streams_->AddStream(stream);
4795 new_streams->AddStream(stream);
4796 }
4797
Steve Anton4171afb2017-11-20 10:20:22 -08004798 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004799 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004800 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004801 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004802 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004803 }
4804 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004805
Steve Anton4171afb2017-11-20 10:20:22 -08004806 // Add default sender if necessary.
4807 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004808 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004809 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004810 if (!default_stream) {
4811 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004812 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004813 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004814 remote_streams_->AddStream(default_stream);
4815 new_streams->AddStream(default_stream);
4816 }
Steve Anton4171afb2017-11-20 10:20:22 -08004817 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4818 ? kDefaultAudioSenderId
4819 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004820 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004821 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004822 if (!default_sender_info) {
4823 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004824 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004825 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004826 }
4827 }
deadbeefab9b2d12015-10-14 11:33:11 -07004828}
4829
Steve Anton4171afb2017-11-20 10:20:22 -08004830void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4831 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004832 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4833 << " receiver for track_id=" << sender_info.sender_id
4834 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004835
Steve Anton3d954a62018-04-02 11:27:23 -07004836 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004837 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004838 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004839 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004840 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004841 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004842 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004843 }
4844}
4845
Steve Anton4171afb2017-11-20 10:20:22 -08004846void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4847 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004848 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4849 << " receiver for track_id=" << sender_info.sender_id
4850 << " and stream_id=" << sender_info.stream_id;
4851
Seth Hampson845e8782018-03-02 11:34:10 -08004852 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004853
Henrik Boström933d8b02017-10-10 10:05:16 -07004854 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004855 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004856 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4857 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004858 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004859 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004860 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004861 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004862 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004863 }
4864 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004865 // Stopping or destroying a VideoRtpReceiver will end the
4866 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004867 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004868 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004869 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004870 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004871 // There's no guarantee the track is still available, e.g. the track may
4872 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004873 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004874 }
4875 } else {
nisseede5da42017-01-12 05:15:36 -08004876 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004877 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004878 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004879 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004880 }
deadbeefab9b2d12015-10-14 11:33:11 -07004881}
4882
4883void PeerConnection::UpdateEndedRemoteMediaStreams() {
4884 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4885 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4886 MediaStreamInterface* stream = remote_streams_->at(i);
4887 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4888 streams_to_remove.push_back(stream);
4889 }
4890 }
4891
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004892 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004893 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004894 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004895 }
4896}
4897
Steve Anton4171afb2017-11-20 10:20:22 -08004898void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004899 const std::vector<cricket::StreamParams>& streams,
4900 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004901 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004902
Seth Hampson845e8782018-03-02 11:34:10 -08004903 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004904 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004905 for (auto sender_it = current_senders->begin();
4906 sender_it != current_senders->end();
4907 /* incremented manually */) {
4908 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004909 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004910 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4911 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004912 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004913 OnLocalSenderRemoved(info, media_type);
4914 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004915 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004916 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004917 }
4918 }
4919
Steve Anton4171afb2017-11-20 10:20:22 -08004920 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004921 for (const cricket::StreamParams& params : streams) {
4922 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004923 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004924 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004925 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004926 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004927 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004928 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004929 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004930 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004931 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004932 }
4933 }
4934}
4935
Steve Anton4171afb2017-11-20 10:20:22 -08004936void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4937 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004938 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004939 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004940 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004941 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4942 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004943 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004944 return;
4945 }
4946
deadbeeffac06552015-11-25 11:26:01 -08004947 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004948 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004949 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004950 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004951 }
deadbeeffac06552015-11-25 11:26:01 -08004952
Seth Hampson5b4f0752018-04-02 16:31:36 -07004953 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004954 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004955}
4956
Steve Anton4171afb2017-11-20 10:20:22 -08004957void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4958 cricket::MediaType media_type) {
4959 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004960 if (!sender) {
4961 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004962 // SessionDescriptions has been renegotiated.
4963 return;
4964 }
deadbeeffac06552015-11-25 11:26:01 -08004965
4966 // A sender has been removed from the SessionDescription but it's still
4967 // associated with the PeerConnection. This only occurs if the SDP doesn't
4968 // match with the calls to CreateSender, AddStream and RemoveStream.
4969 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004970 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004971 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004972 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004973 }
deadbeeffac06552015-11-25 11:26:01 -08004974
Steve Anton4171afb2017-11-20 10:20:22 -08004975 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004976}
4977
4978void PeerConnection::UpdateLocalRtpDataChannels(
4979 const cricket::StreamParamsVec& streams) {
4980 std::vector<std::string> existing_channels;
4981
4982 // Find new and active data channels.
4983 for (const cricket::StreamParams& params : streams) {
4984 // |it->sync_label| is actually the data channel label. The reason is that
4985 // we use the same naming of data channels as we do for
4986 // MediaStreams and Tracks.
4987 // For MediaStreams, the sync_label is the MediaStream label and the
4988 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004989 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004990 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004991 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004992 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004993 continue;
4994 }
4995 // Set the SSRC the data channel should use for sending.
4996 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4997 existing_channels.push_back(data_channel_it->first);
4998 }
4999
5000 UpdateClosingRtpDataChannels(existing_channels, true);
5001}
5002
5003void PeerConnection::UpdateRemoteRtpDataChannels(
5004 const cricket::StreamParamsVec& streams) {
5005 std::vector<std::string> existing_channels;
5006
5007 // Find new and active data channels.
5008 for (const cricket::StreamParams& params : streams) {
5009 // The data channel label is either the mslabel or the SSRC if the mslabel
5010 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005011 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005012 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005013 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005014 auto data_channel_it = rtp_data_channels_.find(label);
5015 if (data_channel_it == rtp_data_channels_.end()) {
5016 // This is a new data channel.
5017 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5018 } else {
5019 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5020 }
5021 existing_channels.push_back(label);
5022 }
5023
5024 UpdateClosingRtpDataChannels(existing_channels, false);
5025}
5026
5027void PeerConnection::UpdateClosingRtpDataChannels(
5028 const std::vector<std::string>& active_channels,
5029 bool is_local_update) {
5030 auto it = rtp_data_channels_.begin();
5031 while (it != rtp_data_channels_.end()) {
5032 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005033 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005034 ++it;
5035 continue;
5036 }
5037
5038 if (is_local_update) {
5039 data_channel->SetSendSsrc(0);
5040 } else {
5041 data_channel->RemotePeerRequestClose();
5042 }
5043
5044 if (data_channel->state() == DataChannel::kClosed) {
5045 rtp_data_channels_.erase(it);
5046 it = rtp_data_channels_.begin();
5047 } else {
5048 ++it;
5049 }
5050 }
5051}
5052
5053void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5054 uint32_t remote_ssrc) {
5055 rtc::scoped_refptr<DataChannel> channel(
5056 InternalCreateDataChannel(label, nullptr));
5057 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005058 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005059 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005060 return;
5061 }
5062 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005063 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5064 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005065 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005066}
5067
5068rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5069 const std::string& label,
5070 const InternalDataChannelInit* config) {
5071 if (IsClosed()) {
5072 return nullptr;
5073 }
Steve Anton75737c02017-11-06 10:37:17 -08005074 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005075 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005076 << "InternalCreateDataChannel: Data is not supported in this call.";
5077 return nullptr;
5078 }
5079 InternalDataChannelInit new_config =
5080 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005081 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005082 if (new_config.id < 0) {
5083 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005084 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005085 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005086 RTC_LOG(LS_ERROR)
5087 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005088 return nullptr;
5089 }
5090 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005091 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005092 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005093 return nullptr;
5094 }
5095 }
5096
Steve Anton75737c02017-11-06 10:37:17 -08005097 rtc::scoped_refptr<DataChannel> channel(
5098 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005099 if (!channel) {
5100 sid_allocator_.ReleaseSid(new_config.id);
5101 return nullptr;
5102 }
5103
5104 if (channel->data_channel_type() == cricket::DCT_RTP) {
5105 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005106 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5107 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005108 return nullptr;
5109 }
5110 rtp_data_channels_[channel->label()] = channel;
5111 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005112 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005113 sctp_data_channels_.push_back(channel);
5114 channel->SignalClosed.connect(this,
5115 &PeerConnection::OnSctpDataChannelClosed);
5116 }
5117
Steve Anton2d8609c2018-01-23 16:38:46 -08005118 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005119 return channel;
5120}
5121
5122bool PeerConnection::HasDataChannels() const {
5123 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5124}
5125
5126void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005127 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005128 for (const auto& channel : sctp_data_channels_) {
5129 if (channel->id() < 0) {
5130 int sid;
5131 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005132 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5133 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005134 continue;
5135 }
5136 channel->SetSctpSid(sid);
5137 }
5138 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005139 // Since closing modifies the list of channels, we have to do the actual
5140 // closing outside the loop.
5141 for (const auto& channel : channels_to_close) {
5142 channel->CloseAbruptly();
5143 }
deadbeefab9b2d12015-10-14 11:33:11 -07005144}
5145
5146void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005147 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005148 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5149 ++it) {
5150 if (it->get() == channel) {
5151 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005152 // After the closing procedure is done, it's safe to use this ID for
5153 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005154 sid_allocator_.ReleaseSid(channel->id());
5155 }
deadbeefbd292462015-12-14 18:15:29 -08005156 // Since this method is triggered by a signal from the DataChannel,
5157 // we can't free it directly here; we need to free it asynchronously.
5158 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005159 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005160 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5161 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005162 return;
5163 }
5164 }
5165}
5166
deadbeefab9b2d12015-10-14 11:33:11 -07005167void PeerConnection::OnDataChannelDestroyed() {
5168 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5169 // DataChannel may callback to us and try to modify the list.
5170 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5171 temp_rtp_dcs.swap(rtp_data_channels_);
5172 for (const auto& kv : temp_rtp_dcs) {
5173 kv.second->OnTransportChannelDestroyed();
5174 }
5175
5176 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5177 temp_sctp_dcs.swap(sctp_data_channels_);
5178 for (const auto& channel : temp_sctp_dcs) {
5179 channel->OnTransportChannelDestroyed();
5180 }
5181}
5182
5183void PeerConnection::OnDataChannelOpenMessage(
5184 const std::string& label,
5185 const InternalDataChannelInit& config) {
5186 rtc::scoped_refptr<DataChannel> channel(
5187 InternalCreateDataChannel(label, &config));
5188 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005189 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005190 return;
5191 }
5192
deadbeefa601f5c2016-06-06 14:27:39 -07005193 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5194 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005195 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005196 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005197}
5198
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005199bool PeerConnection::HandleOpenMessage_s(
5200 const cricket::ReceiveDataParams& params,
5201 const rtc::CopyOnWriteBuffer& buffer) {
5202 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5203 // Received OPEN message; parse and signal that a new data channel should
5204 // be created.
5205 std::string label;
5206 InternalDataChannelInit config;
5207 config.id = params.ssrc;
5208 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5209 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5210 << params.ssrc;
5211 return true;
5212 }
5213 config.open_handshake_role = InternalDataChannelInit::kAcker;
5214 OnDataChannelOpenMessage(label, config);
5215 return true;
5216 }
5217 return false;
5218}
5219
Steve Anton4171afb2017-11-20 10:20:22 -08005220rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5221PeerConnection::GetAudioTransceiver() const {
5222 // This method only works with Plan B SDP, where there is a single
5223 // audio/video transceiver.
5224 RTC_DCHECK(!IsUnifiedPlan());
5225 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005226 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005227 return transceiver;
5228 }
5229 }
5230 RTC_NOTREACHED();
5231 return nullptr;
5232}
5233
5234rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5235PeerConnection::GetVideoTransceiver() const {
5236 // This method only works with Plan B SDP, where there is a single
5237 // audio/video transceiver.
5238 RTC_DCHECK(!IsUnifiedPlan());
5239 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005240 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005241 return transceiver;
5242 }
5243 }
5244 RTC_NOTREACHED();
5245 return nullptr;
5246}
5247
5248// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5249// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005250bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005251 switch (type) {
5252 case cricket::MEDIA_TYPE_AUDIO:
5253 return !GetAudioTransceiver()->internal()->senders().empty();
5254 case cricket::MEDIA_TYPE_VIDEO:
5255 return !GetVideoTransceiver()->internal()->senders().empty();
5256 case cricket::MEDIA_TYPE_DATA:
5257 return false;
5258 }
5259 RTC_NOTREACHED();
5260 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005261}
5262
Steve Anton4171afb2017-11-20 10:20:22 -08005263rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5264PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005265 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005266 for (auto sender : transceiver->internal()->senders()) {
5267 if (sender->track() == track) {
5268 return sender;
5269 }
5270 }
5271 }
5272 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005273}
5274
Steve Anton4171afb2017-11-20 10:20:22 -08005275rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5276PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005277 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005278 for (auto sender : transceiver->internal()->senders()) {
5279 if (sender->id() == sender_id) {
5280 return sender;
5281 }
5282 }
5283 }
5284 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005285}
5286
Steve Anton4171afb2017-11-20 10:20:22 -08005287rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5288PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005289 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005290 for (auto receiver : transceiver->internal()->receivers()) {
5291 if (receiver->id() == receiver_id) {
5292 return receiver;
5293 }
5294 }
5295 }
5296 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005297}
5298
Steve Anton4171afb2017-11-20 10:20:22 -08005299std::vector<PeerConnection::RtpSenderInfo>*
5300PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5301 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5302 media_type == cricket::MEDIA_TYPE_VIDEO);
5303 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5304 ? &remote_audio_sender_infos_
5305 : &remote_video_sender_infos_;
5306}
5307
5308std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005309 cricket::MediaType media_type) {
5310 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5311 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005312 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5313 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005314}
5315
Steve Anton4171afb2017-11-20 10:20:22 -08005316const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5317 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005318 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005319 const std::string sender_id) const {
5320 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005321 if (sender_info.stream_id == stream_id &&
5322 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005323 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005324 }
5325 }
5326 return nullptr;
5327}
5328
5329DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5330 for (const auto& channel : sctp_data_channels_) {
5331 if (channel->id() == sid) {
5332 return channel;
5333 }
5334 }
5335 return nullptr;
5336}
5337
Karl Wibergfb3be392019-03-22 14:13:22 +01005338PeerConnection::InitializePortAllocatorResult
5339PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005340 const cricket::ServerAddresses& stun_servers,
5341 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005342 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005343 RTC_DCHECK_RUN_ON(network_thread());
5344
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005345 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005346 // To handle both internal and externally created port allocator, we will
5347 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005348 int port_allocator_flags = port_allocator_->flags();
5349 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5350 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5351 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005352 // If the disable-IPv6 flag was specified, we'll not override it
5353 // by experiment.
5354 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005355 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005356 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5357 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005358 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005359 }
5360
zhihuangb09b3f92017-03-07 14:40:51 -08005361 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005362 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005363 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005364 }
5365
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005366 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005367 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005368 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005369 }
5370
honghaiz60347052016-05-31 18:29:12 -07005371 if (configuration.candidate_network_policy ==
5372 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005373 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005374 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005375 }
5376
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005377 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005378 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005379 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5380 }
5381
Karl Wibergfb3be392019-03-22 14:13:22 +01005382 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005383 // No step delay is used while allocating ports.
5384 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5385 port_allocator_->set_candidate_filter(
5386 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005387 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005388
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005389 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005390 for (auto& turn_server : turn_servers_copy) {
5391 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005392 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005393 // Call this last since it may create pooled allocator sessions using the
5394 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005395 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005396 stun_servers, std::move(turn_servers_copy),
5397 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5398 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005399 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005400
5401 InitializePortAllocatorResult res;
5402 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5403 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005404}
5405
deadbeef91dd5672016-05-18 16:55:30 -07005406bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005407 const cricket::ServerAddresses& stun_servers,
5408 const std::vector<cricket::RelayServerConfig>& turn_servers,
5409 IceTransportsType type,
5410 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005411 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005412 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005413 absl::optional<int> stun_candidate_keepalive_interval,
5414 bool have_local_description) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005415 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005416 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005417 // According to JSEP, after setLocalDescription, changing the candidate pool
5418 // size is not allowed, and changing the set of ICE servers will not result
5419 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005420 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005421 port_allocator_->FreezeCandidatePool();
5422 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005423 // Add the custom tls turn servers if they exist.
5424 auto turn_servers_copy = turn_servers;
5425 for (auto& turn_server : turn_servers_copy) {
5426 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5427 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005428 // Call this last since it may create pooled allocator sessions using the
5429 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005430 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005431 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5432 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005433}
5434
Steve Antonba818672017-11-06 10:21:57 -08005435cricket::ChannelManager* PeerConnection::channel_manager() const {
5436 return factory_->channel_manager();
5437}
5438
Elad Alon99c3fe52017-10-13 16:29:40 +02005439bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005440 std::unique_ptr<RtcEventLogOutput> output,
5441 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005442 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005443 if (!event_log_) {
5444 return false;
5445 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005446 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005447}
5448
5449void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005450 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005451 if (event_log_) {
5452 event_log_->StopLogging();
5453 }
ivoc14d5dbe2016-07-04 07:06:55 -07005454}
nisseeaabdf62017-05-05 02:23:02 -07005455
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005456cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005457 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005458 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005459 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005460 if (channel && channel->content_name() == content_name) {
5461 return channel;
5462 }
Steve Anton75737c02017-11-06 10:37:17 -08005463 }
5464 if (rtp_data_channel() &&
5465 rtp_data_channel()->content_name() == content_name) {
5466 return rtp_data_channel();
5467 }
5468 return nullptr;
5469}
5470
5471bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005472 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005473 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005474 RTC_LOG(LS_INFO)
5475 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005476 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005477 return false;
5478 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005479 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005480 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005481 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005482 return false;
5483 }
5484
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005485 absl::optional<rtc::SSLRole> dtls_role;
5486 if (sctp_mid_) {
5487 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5488 } else if (is_caller_) {
5489 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5490 }
Zhi Huange830e682018-03-30 10:48:35 -07005491 if (dtls_role) {
5492 *role = *dtls_role;
5493 return true;
5494 }
5495 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005496}
5497
5498bool PeerConnection::GetSslRole(const std::string& content_name,
5499 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005500 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005501 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005502 RTC_LOG(LS_INFO)
5503 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005504 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005505 return false;
5506 }
5507
Zhi Huange830e682018-03-30 10:48:35 -07005508 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5509 if (dtls_role) {
5510 *role = *dtls_role;
5511 return true;
5512 }
5513 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005514}
5515
Steve Antonf8470812017-12-04 10:46:21 -08005516void PeerConnection::SetSessionError(SessionError error,
5517 const std::string& error_desc) {
5518 RTC_DCHECK_RUN_ON(signaling_thread());
5519 if (error != session_error_) {
5520 session_error_ = error;
5521 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005522 }
5523}
5524
Zhi Huange830e682018-03-30 10:48:35 -07005525RTCError PeerConnection::UpdateSessionState(
5526 SdpType type,
5527 cricket::ContentSource source,
5528 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005529 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005530
5531 // If there's already a pending error then no state transition should happen.
5532 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005533 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005534
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005535 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005536 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005537 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005538 }
5539
5540 // Update the signaling state according to the specified state machine (see
5541 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005542 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005543 ChangeSignalingState(source == cricket::CS_LOCAL
5544 ? PeerConnectionInterface::kHaveLocalOffer
5545 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005546 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005547 ChangeSignalingState(source == cricket::CS_LOCAL
5548 ? PeerConnectionInterface::kHaveLocalPrAnswer
5549 : PeerConnectionInterface::kHaveRemotePrAnswer);
5550 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005551 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005552 ChangeSignalingState(PeerConnectionInterface::kStable);
5553 }
5554
5555 // Update internal objects according to the session description's media
5556 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005557 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005558 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005559 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005560 }
5561
Steve Anton8a006912017-12-04 15:25:56 -08005562 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005563}
5564
Steve Anton8a006912017-12-04 15:25:56 -08005565RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005566 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005567 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005568 const SessionDescriptionInterface* sdesc =
5569 (source == cricket::CS_LOCAL ? local_description()
5570 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005571 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005572
5573 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005574 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005575 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005576 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005577 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005578 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005579 continue;
5580 }
5581 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005582 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005583 if (!content_desc) {
5584 continue;
5585 }
5586 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005587 bool success = (source == cricket::CS_LOCAL)
5588 ? channel->SetLocalContent(content_desc, type, &error)
5589 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005590 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005591 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005592 }
5593 }
5594
5595 // If using the RtpDataChannel, push down the new SDP section for it too.
5596 if (rtp_data_channel_) {
5597 const ContentInfo* data_content =
5598 cricket::GetFirstDataContent(sdesc->description());
5599 if (data_content && !data_content->rejected) {
5600 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005601 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005602 if (data_desc) {
5603 std::string error;
5604 bool success =
5605 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005606 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005607 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005608 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005609 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005610 }
Steve Anton75737c02017-11-06 10:37:17 -08005611 }
5612 }
5613 }
Steve Antoned10bd92017-12-05 10:52:59 -08005614
Steve Anton75737c02017-11-06 10:37:17 -08005615 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5616 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5617 if (sctp_transport_ && local_description() && remote_description() &&
5618 cricket::GetFirstDataContent(local_description()->description()) &&
5619 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005620 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005621 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 11:37:28 +02005622 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5623 GetSctpPort(local_description()->description()),
5624 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 15:25:56 -08005625 if (!success) {
5626 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5627 "Failed to push down SCTP parameters.");
5628 }
Steve Anton75737c02017-11-06 10:37:17 -08005629 }
Steve Antoned10bd92017-12-05 10:52:59 -08005630
Steve Anton8a006912017-12-04 15:25:56 -08005631 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005632}
5633
Karl Wiberg739506e2019-04-03 11:37:28 +02005634bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5635 int local_sctp_port,
5636 int remote_sctp_port) {
5637 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005638 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5639 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 11:37:28 +02005640 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 10:37:17 -08005641}
5642
Steve Anton8a006912017-12-04 15:25:56 -08005643RTCError PeerConnection::PushdownTransportDescription(
5644 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005645 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005646 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005647
Zhi Huange830e682018-03-30 10:48:35 -07005648 if (source == cricket::CS_LOCAL) {
5649 const SessionDescriptionInterface* sdesc = local_description();
5650 RTC_DCHECK(sdesc);
5651 return transport_controller_->SetLocalDescription(type,
5652 sdesc->description());
5653 } else {
5654 const SessionDescriptionInterface* sdesc = remote_description();
5655 RTC_DCHECK(sdesc);
5656 return transport_controller_->SetRemoteDescription(type,
5657 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005658 }
Steve Anton75737c02017-11-06 10:37:17 -08005659}
5660
5661bool PeerConnection::GetTransportDescription(
5662 const SessionDescription* description,
5663 const std::string& content_name,
5664 cricket::TransportDescription* tdesc) {
5665 if (!description || !tdesc) {
5666 return false;
5667 }
5668 const TransportInfo* transport_info =
5669 description->GetTransportInfoByName(content_name);
5670 if (!transport_info) {
5671 return false;
5672 }
5673 *tdesc = transport_info->description;
5674 return true;
5675}
5676
Steve Anton75737c02017-11-06 10:37:17 -08005677cricket::IceConfig PeerConnection::ParseIceConfig(
5678 const PeerConnectionInterface::RTCConfiguration& config) const {
5679 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005680 switch (config.continual_gathering_policy) {
5681 case PeerConnectionInterface::GATHER_ONCE:
5682 gathering_policy = cricket::GATHER_ONCE;
5683 break;
5684 case PeerConnectionInterface::GATHER_CONTINUALLY:
5685 gathering_policy = cricket::GATHER_CONTINUALLY;
5686 break;
5687 default:
5688 RTC_NOTREACHED();
5689 gathering_policy = cricket::GATHER_ONCE;
5690 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005691
Steve Anton75737c02017-11-06 10:37:17 -08005692 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005693 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5694 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005695 ice_config.prioritize_most_likely_candidate_pairs =
5696 config.prioritize_most_likely_ice_candidate_pairs;
5697 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005698 RTCConfigurationToIceConfigOptionalInt(
5699 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005700 ice_config.continual_gathering_policy = gathering_policy;
5701 ice_config.presume_writable_when_fully_relayed =
5702 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005703 ice_config.ice_check_interval_strong_connectivity =
5704 config.ice_check_interval_strong_connectivity;
5705 ice_config.ice_check_interval_weak_connectivity =
5706 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005707 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005708 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5709 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005710 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005711 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005712 ice_config.regather_all_networks_interval_range =
5713 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005714 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005715 return ice_config;
5716}
5717
Steve Anton75737c02017-11-06 10:37:17 -08005718bool PeerConnection::SendData(const cricket::SendDataParams& params,
5719 const rtc::CopyOnWriteBuffer& payload,
5720 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005721 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005722 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5723 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5724 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005725 return false;
5726 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005727 if (media_transport_) {
5728 SendDataParams send_params;
5729 send_params.type = ToWebrtcDataMessageType(params.type);
5730 send_params.ordered = params.ordered;
5731 if (params.max_rtx_count >= 0) {
5732 send_params.max_rtx_count = params.max_rtx_count;
5733 } else if (params.max_rtx_ms >= 0) {
5734 send_params.max_rtx_ms = params.max_rtx_ms;
5735 }
5736 return media_transport_->SendData(params.sid, send_params, payload).ok();
5737 }
Steve Anton75737c02017-11-06 10:37:17 -08005738 return rtp_data_channel_
5739 ? rtp_data_channel_->SendData(params, payload, result)
5740 : network_thread()->Invoke<bool>(
5741 RTC_FROM_HERE,
5742 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005743 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005744}
5745
5746bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005747 RTC_DCHECK_RUN_ON(signaling_thread());
5748 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005749 // Don't log an error here, because DataChannels are expected to call
5750 // ConnectDataChannel in this state. It's the only way to initially tell
5751 // whether or not the underlying transport is ready.
5752 return false;
5753 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005754 if (media_transport_) {
5755 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5756 &DataChannel::OnChannelReady);
5757 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5758 &DataChannel::OnDataReceived);
5759 SignalMediaTransportChannelClosing_s.connect(
5760 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5761 SignalMediaTransportChannelClosed_s.connect(
5762 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5763 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005764 rtp_data_channel_->SignalReadyToSendData.connect(
5765 webrtc_data_channel, &DataChannel::OnChannelReady);
5766 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5767 &DataChannel::OnDataReceived);
5768 } else {
5769 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5770 &DataChannel::OnChannelReady);
5771 SignalSctpDataReceived.connect(webrtc_data_channel,
5772 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005773 SignalSctpClosingProcedureStartedRemotely.connect(
5774 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5775 SignalSctpClosingProcedureComplete.connect(
5776 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005777 }
5778 return true;
5779}
5780
5781void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005782 RTC_DCHECK_RUN_ON(signaling_thread());
5783 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005784 RTC_LOG(LS_ERROR)
5785 << "DisconnectDataChannel called when rtp_data_channel_ and "
5786 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005787 return;
5788 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005789 if (media_transport_) {
5790 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5791 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5792 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5793 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5794 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005795 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5796 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5797 } else {
5798 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5799 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005800 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5801 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
5803}
5804
5805void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005806 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005807 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005808 return;
5809 }
Steve Anton75737c02017-11-06 10:37:17 -08005810 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005811 RTC_LOG(LS_ERROR)
5812 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005813 return;
5814 }
5815 network_thread()->Invoke<void>(
5816 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005817 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005818}
5819
5820void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005821 if (media_transport_) {
5822 media_transport_->CloseChannel(sid);
5823 return;
5824 }
Steve Anton75737c02017-11-06 10:37:17 -08005825 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005826 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005827 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005828 return;
5829 }
5830 network_thread()->Invoke<void>(
5831 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005832 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005833}
5834
5835bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005836 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005837 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005838 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005839 sctp_ready_to_send_data_;
5840}
5841
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005842void PeerConnection::OnDataReceived(int channel_id,
5843 DataMessageType type,
5844 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005845 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005846 cricket::ReceiveDataParams params;
5847 params.sid = channel_id;
5848 params.type = ToCricketDataMessageType(type);
5849 media_transport_invoker_->AsyncInvoke<void>(
5850 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5851 RTC_DCHECK_RUN_ON(signaling_thread());
5852 if (!HandleOpenMessage_s(params, buffer)) {
5853 SignalMediaTransportReceivedData_s(params, buffer);
5854 }
5855 });
5856}
5857
5858void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005859 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005860 media_transport_invoker_->AsyncInvoke<void>(
5861 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5862 RTC_DCHECK_RUN_ON(signaling_thread());
5863 SignalMediaTransportChannelClosing_s(channel_id);
5864 });
5865}
5866
5867void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005868 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005869 media_transport_invoker_->AsyncInvoke<void>(
5870 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5871 RTC_DCHECK_RUN_ON(signaling_thread());
5872 SignalMediaTransportChannelClosed_s(channel_id);
5873 });
5874}
5875
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005876absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005877 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005878 if (sctp_mid_ && transport_controller_) {
5879 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5880 if (dtls_transport) {
5881 return dtls_transport->transport_name();
5882 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005883 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005884 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005885 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005886}
5887
Qingsi Wang72a43a12018-02-20 16:03:18 -08005888cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5889 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005890 network_thread()->Invoke<void>(
5891 RTC_FROM_HERE,
5892 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5893 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005894 return candidate_states_list;
5895}
5896
Steve Anton5dfde182018-02-06 10:34:40 -08005897std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5898 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005899 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005900 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005901 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005902 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005903 if (channel) {
5904 transport_names_by_mid[channel->content_name()] =
5905 channel->transport_name();
5906 }
Steve Anton75737c02017-11-06 10:37:17 -08005907 }
Steve Anton5dfde182018-02-06 10:34:40 -08005908 if (rtp_data_channel_) {
5909 transport_names_by_mid[rtp_data_channel_->content_name()] =
5910 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005911 }
5912 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005913 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005914 RTC_DCHECK(transport_name);
5915 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005916 }
Steve Anton5dfde182018-02-06 10:34:40 -08005917 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005918}
5919
Steve Anton5dfde182018-02-06 10:34:40 -08005920std::map<std::string, cricket::TransportStats>
5921PeerConnection::GetTransportStatsByNames(
5922 const std::set<std::string>& transport_names) {
5923 if (!network_thread()->IsCurrent()) {
5924 return network_thread()
5925 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5926 RTC_FROM_HERE,
5927 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005928 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005929 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005930 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5931 for (const std::string& transport_name : transport_names) {
5932 cricket::TransportStats transport_stats;
5933 bool success =
5934 transport_controller_->GetStats(transport_name, &transport_stats);
5935 if (success) {
5936 transport_stats_by_name[transport_name] = std::move(transport_stats);
5937 } else {
5938 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5939 << transport_name;
5940 }
5941 }
5942 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005943}
5944
5945bool PeerConnection::GetLocalCertificate(
5946 const std::string& transport_name,
5947 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005948 if (!certificate) {
5949 return false;
5950 }
5951 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5952 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005953}
5954
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005955std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005956 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005957 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005958}
5959
5960cricket::DataChannelType PeerConnection::data_channel_type() const {
5961 return data_channel_type_;
5962}
5963
5964bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02005965 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005966 return pending_ice_restarts_.find(content_name) !=
5967 pending_ice_restarts_.end();
5968}
5969
Steve Anton75737c02017-11-06 10:37:17 -08005970bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5971 return transport_controller_->NeedsIceRestart(content_name);
5972}
5973
5974void PeerConnection::OnCertificateReady(
5975 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5976 transport_controller_->SetLocalCertificate(certificate);
5977}
5978
5979void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005980 SetSessionError(SessionError::kTransport,
5981 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005982}
5983
Alex Loiko9289eda2018-11-23 16:18:59 +00005984void PeerConnection::OnTransportControllerConnectionState(
5985 cricket::IceConnectionState state) {
5986 switch (state) {
5987 case cricket::kIceConnectionConnecting:
5988 // If the current state is Connected or Completed, then there were
5989 // writable channels but now there are not, so the next state must
5990 // be Disconnected.
5991 // kIceConnectionConnecting is currently used as the default,
5992 // un-connected state by the TransportController, so its only use is
5993 // detecting disconnections.
5994 if (ice_connection_state_ ==
5995 PeerConnectionInterface::kIceConnectionConnected ||
5996 ice_connection_state_ ==
5997 PeerConnectionInterface::kIceConnectionCompleted) {
5998 SetIceConnectionState(
5999 PeerConnectionInterface::kIceConnectionDisconnected);
6000 }
6001 break;
6002 case cricket::kIceConnectionFailed:
6003 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6004 break;
6005 case cricket::kIceConnectionConnected:
6006 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6007 "all transports are writable.";
6008 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6009 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6010 break;
6011 case cricket::kIceConnectionCompleted:
6012 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6013 "all transports are complete.";
6014 if (ice_connection_state_ !=
6015 PeerConnectionInterface::kIceConnectionConnected) {
6016 // If jumping directly from "checking" to "connected",
6017 // signal "connected" first.
6018 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6019 }
6020 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6021 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6022 ReportTransportStats();
6023 break;
6024 default:
6025 RTC_NOTREACHED();
6026 }
6027}
6028
Steve Anton75737c02017-11-06 10:37:17 -08006029void PeerConnection::OnTransportControllerCandidatesGathered(
6030 const std::string& transport_name,
6031 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006032 int sdp_mline_index;
6033 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006034 RTC_LOG(LS_ERROR)
6035 << "OnTransportControllerCandidatesGathered: content name "
6036 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006037 return;
6038 }
6039
6040 for (cricket::Candidates::const_iterator citer = candidates.begin();
6041 citer != candidates.end(); ++citer) {
6042 // Use transport_name as the candidate media id.
6043 std::unique_ptr<JsepIceCandidate> candidate(
6044 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6045 if (local_description()) {
6046 mutable_local_description()->AddCandidate(candidate.get());
6047 }
6048 OnIceCandidate(std::move(candidate));
6049 }
6050}
6051
6052void PeerConnection::OnTransportControllerCandidatesRemoved(
6053 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006054 // Sanity check.
6055 for (const cricket::Candidate& candidate : candidates) {
6056 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006057 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006058 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006059 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006060 return;
6061 }
6062 }
6063
6064 if (local_description()) {
6065 mutable_local_description()->RemoveCandidates(candidates);
6066 }
6067 OnIceCandidatesRemoved(candidates);
6068}
6069
6070void PeerConnection::OnTransportControllerDtlsHandshakeError(
6071 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006072 RTC_HISTOGRAM_ENUMERATION(
6073 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6074 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006075}
6076
Steve Antoned10bd92017-12-05 10:52:59 -08006077void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006078 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006079 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006080 if (channel && !channel->enabled()) {
6081 channel->Enable(true);
6082 }
Steve Anton75737c02017-11-06 10:37:17 -08006083 }
6084
Steve Anton4171afb2017-11-20 10:20:22 -08006085 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006086 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006087 }
Steve Anton75737c02017-11-06 10:37:17 -08006088}
6089
6090// Returns the media index for a local ice candidate given the content name.
6091bool PeerConnection::GetLocalCandidateMediaIndex(
6092 const std::string& content_name,
6093 int* sdp_mline_index) {
6094 if (!local_description() || !sdp_mline_index) {
6095 return false;
6096 }
6097
6098 bool content_found = false;
6099 const ContentInfos& contents = local_description()->description()->contents();
6100 for (size_t index = 0; index < contents.size(); ++index) {
6101 if (contents[index].name == content_name) {
6102 *sdp_mline_index = static_cast<int>(index);
6103 content_found = true;
6104 break;
6105 }
6106 }
6107 return content_found;
6108}
6109
6110bool PeerConnection::UseCandidatesInSessionDescription(
6111 const SessionDescriptionInterface* remote_desc) {
6112 if (!remote_desc) {
6113 return true;
6114 }
6115 bool ret = true;
6116
6117 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6118 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6119 for (size_t n = 0; n < candidates->count(); ++n) {
6120 const IceCandidateInterface* candidate = candidates->at(n);
6121 bool valid = false;
6122 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6123 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006124 RTC_LOG(LS_INFO)
6125 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006126 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006127 }
6128 continue;
6129 }
6130 ret = UseCandidate(candidate);
6131 if (!ret) {
6132 break;
6133 }
6134 }
6135 }
6136 return ret;
6137}
6138
6139bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6140 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6141 size_t remote_content_size =
6142 remote_description()->description()->contents().size();
6143 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006144 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006145 return false;
6146 }
6147
6148 cricket::ContentInfo content =
6149 remote_description()->description()->contents()[mediacontent_index];
6150 std::vector<cricket::Candidate> candidates;
6151 candidates.push_back(candidate->candidate());
6152 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006153 RTCError error =
6154 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006155 if (error.ok()) {
6156 // Candidates successfully submitted for checking.
6157 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6158 ice_connection_state_ ==
6159 PeerConnectionInterface::kIceConnectionDisconnected) {
6160 // If state is New, then the session has just gotten its first remote ICE
6161 // candidates, so go to Checking.
6162 // If state is Disconnected, the session is re-using old candidates or
6163 // receiving additional ones, so go to Checking.
6164 // If state is Connected, stay Connected.
6165 // TODO(bemasc): If state is Connected, and the new candidates are for a
6166 // newly added transport, then the state actually _should_ move to
6167 // checking. Add a way to distinguish that case.
6168 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6169 }
6170 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006171 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006172 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006173 }
6174 return true;
6175}
6176
6177void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006178 // Destroy video channel first since it may have a pointer to the
6179 // voice channel.
6180 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006181 if (!video_info || video_info->rejected) {
6182 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006183 }
6184
Steve Anton6fec8802017-12-04 10:37:29 -08006185 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6186 if (!audio_info || audio_info->rejected) {
6187 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006188 }
6189
6190 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6191 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006192 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006193 }
6194}
6195
Steve Antondcc3c022017-12-22 16:02:54 -08006196RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6197 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006198 const cricket::ContentGroup* bundle_group = nullptr;
6199 if (configuration_.bundle_policy ==
6200 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006201 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006202 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006203 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6204 "max-bundle configured but session description "
6205 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006206 }
6207 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006208 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006209}
6210
6211RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006212 // Creating the media channels. Transports should already have been created
6213 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006214 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006215 if (voice && !voice->rejected &&
6216 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006217 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006218 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006219 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6220 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006221 }
6222 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6223 }
6224
Steve Antondcc3c022017-12-22 16:02:54 -08006225 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006226 if (video && !video->rejected &&
6227 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006228 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006229 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006230 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6231 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006232 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006233 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006234 }
6235
Steve Antondcc3c022017-12-22 16:02:54 -08006236 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006237 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006238 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006239 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006240 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6241 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006242 }
6243 }
6244
Steve Anton8a006912017-12-04 15:25:56 -08006245 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006246}
6247
Steve Anton4171afb2017-11-20 10:20:22 -08006248// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006249cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006250 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006251 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006252 MediaTransportInterface* media_transport = nullptr;
6253 if (configuration_.use_media_transport) {
6254 media_transport = GetMediaTransport(mid);
6255 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006256
Steve Anton75737c02017-11-06 10:37:17 -08006257 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006258 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006259 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006260 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006261 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006262 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006263 }
Steve Anton75737c02017-11-06 10:37:17 -08006264 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6265 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006266 voice_channel->SignalSentPacket.connect(this,
6267 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006268 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006269
Steve Antoneda6ccd2017-12-04 10:21:55 -08006270 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006271}
6272
Steve Anton4171afb2017-11-20 10:20:22 -08006273// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006274cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006275 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006276 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006277 MediaTransportInterface* media_transport = nullptr;
6278 if (configuration_.use_media_transport) {
6279 media_transport = GetMediaTransport(mid);
6280 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006281
Steve Anton75737c02017-11-06 10:37:17 -08006282 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006283 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006284 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006285 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006286 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006287 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006288 }
Steve Anton75737c02017-11-06 10:37:17 -08006289 video_channel->SignalDtlsSrtpSetupFailure.connect(
6290 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006291 video_channel->SignalSentPacket.connect(this,
6292 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006293 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006294
Steve Antoneda6ccd2017-12-04 10:21:55 -08006295 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006296}
6297
Zhi Huange830e682018-03-30 10:48:35 -07006298bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006299 switch (data_channel_type_) {
6300 case cricket::DCT_MEDIA_TRANSPORT:
6301 if (network_thread()->Invoke<bool>(
6302 RTC_FROM_HERE,
6303 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6304 this, mid))) {
6305 for (const auto& channel : sctp_data_channels_) {
6306 channel->OnTransportChannelCreated();
6307 }
6308 return true;
6309 }
Steve Anton75737c02017-11-06 10:37:17 -08006310 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006311 case cricket::DCT_SCTP:
6312 if (!sctp_factory_) {
6313 RTC_LOG(LS_ERROR)
6314 << "Trying to create SCTP transport, but didn't compile with "
6315 "SCTP support (HAVE_SCTP)";
6316 return false;
6317 }
6318 if (!network_thread()->Invoke<bool>(
6319 RTC_FROM_HERE,
6320 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6321 return false;
6322 }
6323 for (const auto& channel : sctp_data_channels_) {
6324 channel->OnTransportChannelCreated();
6325 }
6326 return true;
6327 case cricket::DCT_RTP:
6328 default:
6329 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6330 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6331 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006332 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006333 if (!rtp_data_channel_) {
6334 return false;
6335 }
6336 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6337 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6338 rtp_data_channel_->SignalSentPacket.connect(
6339 this, &PeerConnection::OnSentPacket_w);
6340 rtp_data_channel_->SetRtpTransport(rtp_transport);
6341 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006342 }
6343
Steve Anton75737c02017-11-06 10:37:17 -08006344 return true;
6345}
6346
6347Call::Stats PeerConnection::GetCallStats() {
6348 if (!worker_thread()->IsCurrent()) {
6349 return worker_thread()->Invoke<Call::Stats>(
6350 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6351 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006352 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006353 if (call_) {
6354 return call_->GetStats();
6355 } else {
6356 return Call::Stats();
6357 }
6358}
6359
Zhi Huange830e682018-03-30 10:48:35 -07006360bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006361 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006362 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006363 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6364 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006365 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006366 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006367 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006368 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6369 sctp_factory_->CreateSctpTransport(dtls_transport);
6370 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006371 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006372 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006373 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006374 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006375 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006376 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6377 // another thread. Would be nice if there was a helper class similar to
6378 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6379 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006380 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006381 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006382 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006383 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006384 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006385 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6386 std::move(cricket_sctp_transport));
6387 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006388 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006389}
6390
6391void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006392 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006393 sctp_transport_->Clear();
6394 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006395 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006396 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006397}
6398
6399void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006400 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006401 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006402 // Note: Cannot use rtc::Bind here because it will grab a reference to
6403 // PeerConnection and potentially cause PeerConnection to live longer than
6404 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6405 // be destroyed before PeerConnection is destroyed, and at that point all
6406 // pending tasks will be cleared.
6407 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6408 OnSctpTransportReadyToSendData_s(true);
6409 });
6410}
6411
6412void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006413 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006414 sctp_ready_to_send_data_ = ready;
6415 SignalSctpReadyToSendData(ready);
6416}
6417
6418void PeerConnection::OnSctpTransportDataReceived_n(
6419 const cricket::ReceiveDataParams& params,
6420 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006421 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006422 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006423 // Note: Cannot use rtc::Bind here because it will grab a reference to
6424 // PeerConnection and potentially cause PeerConnection to live longer than
6425 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6426 // be destroyed before PeerConnection is destroyed, and at that point all
6427 // pending tasks will be cleared.
6428 sctp_invoker_->AsyncInvoke<void>(
6429 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6430 OnSctpTransportDataReceived_s(params, payload);
6431 });
6432}
6433
6434void PeerConnection::OnSctpTransportDataReceived_s(
6435 const cricket::ReceiveDataParams& params,
6436 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006437 RTC_DCHECK_RUN_ON(signaling_thread());
6438 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006439 SignalSctpDataReceived(params, payload);
6440 }
6441}
6442
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006443void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006444 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006445 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006446 sctp_invoker_->AsyncInvoke<void>(
6447 RTC_FROM_HERE, signaling_thread(),
6448 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006449 &SignalSctpClosingProcedureStartedRemotely, sid));
6450}
6451
6452void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006453 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006454 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006455 sctp_invoker_->AsyncInvoke<void>(
6456 RTC_FROM_HERE, signaling_thread(),
6457 rtc::Bind(&sigslot::signal1<int>::operator(),
6458 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006459}
6460
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006461bool PeerConnection::SetupMediaTransportForDataChannels_n(
6462 const std::string& mid) {
6463 media_transport_ = transport_controller_->GetMediaTransport(mid);
6464 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006465 RTC_LOG(LS_ERROR)
6466 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006467 return false;
6468 }
6469
6470 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6471 media_transport_->SetDataSink(this);
6472 media_transport_data_mid_ = mid;
6473 transport_controller_->SignalMediaTransportStateChanged.connect(
6474 this, &PeerConnection::OnMediaTransportStateChanged_n);
6475 // Check the initial state right away, in case transport is already writable.
6476 OnMediaTransportStateChanged_n();
6477 return true;
6478}
6479
6480void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6481 if (!media_transport_) {
6482 return;
6483 }
6484 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6485 media_transport_data_mid_.reset();
6486 media_transport_->SetDataSink(nullptr);
6487 media_transport_invoker_ = nullptr;
6488 media_transport_ = nullptr;
6489}
6490
6491void PeerConnection::OnMediaTransportStateChanged_n() {
6492 if (!media_transport_data_mid_ ||
6493 transport_controller_->GetMediaTransportState(
6494 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6495 return;
6496 }
6497 media_transport_invoker_->AsyncInvoke<void>(
6498 RTC_FROM_HERE, signaling_thread(), [this] {
6499 RTC_DCHECK_RUN_ON(signaling_thread());
6500 media_transport_ready_to_send_data_ = true;
6501 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6502 });
6503}
6504
Steve Anton75737c02017-11-06 10:37:17 -08006505// Returns false if bundle is enabled and rtcp_mux is disabled.
6506bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6507 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6508 if (!bundle_enabled)
6509 return true;
6510
6511 const cricket::ContentGroup* bundle_group =
6512 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6513 RTC_DCHECK(bundle_group != NULL);
6514
6515 const cricket::ContentInfos& contents = desc->contents();
6516 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6517 citer != contents.end(); ++citer) {
6518 const cricket::ContentInfo* content = (&*citer);
6519 RTC_DCHECK(content != NULL);
6520 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006521 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006522 if (!HasRtcpMuxEnabled(content))
6523 return false;
6524 }
6525 }
6526 // RTCP-MUX is enabled in all the contents.
6527 return true;
6528}
6529
6530bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006531 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006532}
6533
Steve Anton06817cd2018-12-18 15:55:30 -08006534static RTCError ValidateMids(const cricket::SessionDescription& description) {
6535 std::set<std::string> mids;
6536 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006537 if (content.name.empty()) {
6538 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6539 "A media section is missing a MID attribute.");
6540 }
Steve Anton06817cd2018-12-18 15:55:30 -08006541 if (!mids.insert(content.name).second) {
6542 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6543 "Duplicate a=mid value '" + content.name + "'.");
6544 }
6545 }
6546 return RTCError::OK();
6547}
6548
Steve Anton8a006912017-12-04 15:25:56 -08006549RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006550 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006551 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006552 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006553 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006554 }
6555
6556 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006558 }
6559
Steve Anton3828c062017-12-06 10:34:51 -08006560 SdpType type = sdesc->GetType();
6561 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6562 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006563 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006564 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006565 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006566 }
6567
Steve Anton06817cd2018-12-18 15:55:30 -08006568 RTCError error = ValidateMids(*sdesc->description());
6569 if (!error.ok()) {
6570 return error;
6571 }
6572
Steve Anton75737c02017-11-06 10:37:17 -08006573 // Verify crypto settings.
6574 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006575 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6576 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006577 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006578 if (!crypto_error.ok()) {
6579 return crypto_error;
6580 }
Steve Anton75737c02017-11-06 10:37:17 -08006581 }
6582
6583 // Verify ice-ufrag and ice-pwd.
6584 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006585 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6586 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006587 }
6588
6589 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006590 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6591 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006592 }
6593
6594 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6595 // m-lines that do not rtcp-mux enabled.
6596
6597 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006598 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006599 // With an answer we want to compare the new answer session description with
6600 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006601 const cricket::SessionDescription* offer_desc =
6602 (source == cricket::CS_LOCAL) ? remote_description()->description()
6603 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006604 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6605 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6606 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006607 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6608 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006609 }
6610 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006611 // The re-offers should respect the order of m= sections in current
6612 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006613 // With a re-offer, either the current local or current remote descriptions
6614 // could be the most up to date, so we would like to check against both of
6615 // them if they exist. It could be the case that one of them has a 0 port
6616 // for a media section, but the other does not. This is important to check
6617 // against in the case that we are recycling an m= section.
6618 const cricket::SessionDescription* current_desc = nullptr;
6619 const cricket::SessionDescription* secondary_current_desc = nullptr;
6620 if (local_description()) {
6621 current_desc = local_description()->description();
6622 if (remote_description()) {
6623 secondary_current_desc = remote_description()->description();
6624 }
6625 } else if (remote_description()) {
6626 current_desc = remote_description()->description();
6627 }
Steve Anton75737c02017-11-06 10:37:17 -08006628 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006629 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6630 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006631 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6632 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006633 }
6634 }
6635
Steve Antonba42e992018-04-09 14:10:01 -07006636 if (IsUnifiedPlan()) {
6637 // Ensure that each audio and video media section has at most one
6638 // "StreamParams". This will return an error if receiving a session
6639 // description from a "Plan B" endpoint which adds multiple tracks of the
6640 // same type. With Unified Plan, there can only be at most one track per
6641 // media section.
6642 for (const ContentInfo& content : sdesc->description()->contents()) {
6643 const MediaContentDescription& desc = *content.description;
6644 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6645 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6646 desc.streams().size() > 1u) {
6647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6648 "Media section has more than one track specified "
6649 "with a=ssrc lines which is not supported with "
6650 "Unified Plan.");
6651 }
6652 }
6653 }
6654
Steve Anton8a006912017-12-04 15:25:56 -08006655 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006656}
6657
Steve Anton3828c062017-12-06 10:34:51 -08006658bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006659 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006660 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006661 return (state == PeerConnectionInterface::kStable) ||
6662 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006663 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006664 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006665 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6666 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6667 }
6668}
6669
Steve Anton3828c062017-12-06 10:34:51 -08006670bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006671 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006672 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006673 return (state == PeerConnectionInterface::kStable) ||
6674 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006675 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006676 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006677 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6678 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6679 }
6680}
6681
Steve Antonf8470812017-12-04 10:46:21 -08006682const char* PeerConnection::SessionErrorToString(SessionError error) const {
6683 switch (error) {
6684 case SessionError::kNone:
6685 return "ERROR_NONE";
6686 case SessionError::kContent:
6687 return "ERROR_CONTENT";
6688 case SessionError::kTransport:
6689 return "ERROR_TRANSPORT";
6690 }
6691 RTC_NOTREACHED();
6692 return "";
6693}
6694
Steve Anton75737c02017-11-06 10:37:17 -08006695std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006696 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006697 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6698 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006699 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006700}
6701
Steve Anton8e20f172018-03-06 10:55:04 -08006702void PeerConnection::ReportSdpFormatReceived(
6703 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006704 int num_audio_mlines = 0;
6705 int num_video_mlines = 0;
6706 int num_audio_tracks = 0;
6707 int num_video_tracks = 0;
6708 for (const ContentInfo& content : remote_offer.description()->contents()) {
6709 cricket::MediaType media_type = content.media_description()->type();
6710 int num_tracks = std::max(
6711 1, static_cast<int>(content.media_description()->streams().size()));
6712 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6713 num_audio_mlines += 1;
6714 num_audio_tracks += num_tracks;
6715 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6716 num_video_mlines += 1;
6717 num_video_tracks += num_tracks;
6718 }
6719 }
6720 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6721 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6722 format = kSdpFormatReceivedComplexUnifiedPlan;
6723 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6724 format = kSdpFormatReceivedComplexPlanB;
6725 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6726 format = kSdpFormatReceivedSimple;
6727 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006728 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6729 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006730}
6731
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006732void PeerConnection::NoteUsageEvent(UsageEvent event) {
6733 RTC_DCHECK_RUN_ON(signaling_thread());
6734 usage_event_accumulator_ |= static_cast<int>(event);
6735}
6736
6737void PeerConnection::ReportUsagePattern() const {
6738 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006739 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6740 usage_event_accumulator_,
6741 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006742 const int bad_bits =
6743 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6744 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6745 const int good_bits =
6746 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6747 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6748 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6749 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6750 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006751 // If called after close(), we can't report, because observer may have
6752 // been deallocated, and therefore pointer is null. Write to log instead.
6753 if (observer_) {
6754 Observer()->OnInterestingUsage(usage_event_accumulator_);
6755 } else {
6756 RTC_LOG(LS_INFO) << "Interesting usage signature "
6757 << usage_event_accumulator_
6758 << " observed after observer shutdown";
6759 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006760 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006761}
6762
Steve Anton0ffaaa22018-02-23 10:31:30 -08006763void PeerConnection::ReportNegotiatedSdpSemantics(
6764 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006765 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006766 switch (answer.description()->msid_signaling()) {
6767 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006768 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006769 break;
6770 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006771 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006772 break;
6773 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006774 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006775 break;
6776 case cricket::kMsidSignalingMediaSection |
6777 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006778 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006779 break;
6780 default:
6781 RTC_NOTREACHED();
6782 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006783 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6784 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006785}
6786
Steve Anton75737c02017-11-06 10:37:17 -08006787// We need to check the local/remote description for the Transport instead of
6788// the session, because a new Transport added during renegotiation may have
6789// them unset while the session has them set from the previous negotiation.
6790// Not doing so may trigger the auto generation of transport description and
6791// mess up DTLS identity information, ICE credential, etc.
6792bool PeerConnection::ReadyToUseRemoteCandidate(
6793 const IceCandidateInterface* candidate,
6794 const SessionDescriptionInterface* remote_desc,
6795 bool* valid) {
6796 *valid = true;
6797
6798 const SessionDescriptionInterface* current_remote_desc =
6799 remote_desc ? remote_desc : remote_description();
6800
6801 if (!current_remote_desc) {
6802 return false;
6803 }
6804
6805 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6806 size_t remote_content_size =
6807 current_remote_desc->description()->contents().size();
6808 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006809 RTC_LOG(LS_ERROR)
6810 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6811 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006812
6813 *valid = false;
6814 return false;
6815 }
6816
6817 cricket::ContentInfo content =
6818 current_remote_desc->description()->contents()[mediacontent_index];
6819
6820 const std::string transport_name = GetTransportName(content.name);
6821 if (transport_name.empty()) {
6822 return false;
6823 }
Zhi Huange830e682018-03-30 10:48:35 -07006824 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006825}
6826
6827bool PeerConnection::SrtpRequired() const {
6828 return dtls_enabled_ ||
6829 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6830}
6831
6832void PeerConnection::OnTransportControllerGatheringState(
6833 cricket::IceGatheringState state) {
6834 RTC_DCHECK(signaling_thread()->IsCurrent());
6835 if (state == cricket::kIceGatheringGathering) {
6836 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6837 } else if (state == cricket::kIceGatheringComplete) {
6838 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6839 }
6840}
6841
6842void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006843 std::map<std::string, std::set<cricket::MediaType>>
6844 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006845 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006846 if (transceiver->internal()->channel()) {
6847 const std::string& transport_name =
6848 transceiver->internal()->channel()->transport_name();
6849 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006850 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006851 }
Steve Anton75737c02017-11-06 10:37:17 -08006852 }
6853 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006854 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6855 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006856 }
Zhi Huange830e682018-03-30 10:48:35 -07006857
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006858 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006859 if (transport_name) {
6860 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006861 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006862 }
Zhi Huange830e682018-03-30 10:48:35 -07006863
Steve Antonc7b964c2018-02-01 14:39:45 -08006864 for (const auto& entry : media_types_by_transport_name) {
6865 const std::string& transport_name = entry.first;
6866 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006867 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006868 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006869 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006870 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006871 }
6872 }
6873}
6874// Walk through the ConnectionInfos to gather best connection usage
6875// for IPv4 and IPv6.
6876void PeerConnection::ReportBestConnectionState(
6877 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006878 for (const cricket::TransportChannelStats& channel_stats :
6879 stats.channel_stats) {
6880 for (const cricket::ConnectionInfo& connection_info :
6881 channel_stats.connection_infos) {
6882 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006883 continue;
6884 }
6885
Steve Antonc7b964c2018-02-01 14:39:45 -08006886 const cricket::Candidate& local = connection_info.local_candidate;
6887 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006888
6889 // Increment the counter for IceCandidatePairType.
6890 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6891 (local.type() == RELAY_PORT_TYPE &&
6892 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006893 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6894 GetIceCandidatePairCounter(local, remote),
6895 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006896 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006897 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6898 GetIceCandidatePairCounter(local, remote),
6899 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006900 } else {
6901 RTC_CHECK(0);
6902 }
Steve Anton75737c02017-11-06 10:37:17 -08006903
6904 // Increment the counter for IP type.
6905 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006906 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6907 kBestConnections_IPv4,
6908 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006909 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006910 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6911 kBestConnections_IPv6,
6912 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006913 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006914 RTC_CHECK(!local.address().hostname().empty() &&
6915 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006916 }
6917
6918 return;
6919 }
6920 }
6921}
6922
6923void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006924 const cricket::TransportStats& stats,
6925 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006926 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6927 return;
6928 }
6929
6930 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6931 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6932 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6933 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6934 return;
6935 }
6936
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006937 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6938 for (cricket::MediaType media_type : media_types) {
6939 switch (media_type) {
6940 case cricket::MEDIA_TYPE_AUDIO:
6941 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6942 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6943 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6944 break;
6945 case cricket::MEDIA_TYPE_VIDEO:
6946 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6947 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6948 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6949 break;
6950 case cricket::MEDIA_TYPE_DATA:
6951 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6952 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6953 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6954 break;
6955 default:
6956 RTC_NOTREACHED();
6957 continue;
6958 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006959 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006960 }
6961
6962 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6963 for (cricket::MediaType media_type : media_types) {
6964 switch (media_type) {
6965 case cricket::MEDIA_TYPE_AUDIO:
6966 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6967 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6968 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6969 break;
6970 case cricket::MEDIA_TYPE_VIDEO:
6971 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6972 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6973 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6974 break;
6975 case cricket::MEDIA_TYPE_DATA:
6976 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6977 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6978 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6979 break;
6980 default:
6981 RTC_NOTREACHED();
6982 continue;
6983 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006984 }
Steve Anton75737c02017-11-06 10:37:17 -08006985 }
6986}
6987
6988void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006989 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006990 RTC_DCHECK(call_);
6991 call_->OnSentPacket(sent_packet);
6992}
6993
6994const std::string PeerConnection::GetTransportName(
6995 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006996 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006997 if (channel) {
6998 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006999 }
Steve Anton6fec8802017-12-04 10:37:29 -08007000 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007001 RTC_DCHECK(sctp_mid_);
7002 if (content_name == *sctp_mid_) {
7003 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007004 }
7005 }
7006 // Return an empty string if failed to retrieve the transport name.
7007 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007008}
7009
Steve Anton6fec8802017-12-04 10:37:29 -08007010void PeerConnection::DestroyTransceiverChannel(
7011 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7012 transceiver) {
7013 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007014
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007015 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007016 if (channel) {
7017 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007018 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007019 }
7020}
7021
7022void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007023 if (rtp_data_channel_) {
7024 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007025 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007026 rtp_data_channel_ = nullptr;
7027 }
7028
7029 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7030 // grab a reference to this PeerConnection. If this is called from the
7031 // PeerConnection destructor, the RefCountedObject vtable will have already
7032 // been destroyed (since it is a subclass of PeerConnection) and using
7033 // rtc::Bind will cause "Pure virtual function called" error to appear.
7034
7035 if (sctp_transport_) {
7036 OnDataChannelDestroyed();
7037 network_thread()->Invoke<void>(RTC_FROM_HERE,
7038 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007039 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007040 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007041
7042 if (media_transport_) {
7043 OnDataChannelDestroyed();
7044 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7045 RTC_DCHECK_RUN_ON(network_thread());
7046 TeardownMediaTransportForDataChannels_n();
7047 });
7048 }
Steve Anton6fec8802017-12-04 10:37:29 -08007049}
7050
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007051void PeerConnection::DestroyChannelInterface(
7052 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007053 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007054 switch (channel->media_type()) {
7055 case cricket::MEDIA_TYPE_AUDIO:
7056 channel_manager()->DestroyVoiceChannel(
7057 static_cast<cricket::VoiceChannel*>(channel));
7058 break;
7059 case cricket::MEDIA_TYPE_VIDEO:
7060 channel_manager()->DestroyVideoChannel(
7061 static_cast<cricket::VideoChannel*>(channel));
7062 break;
7063 case cricket::MEDIA_TYPE_DATA:
7064 channel_manager()->DestroyRtpDataChannel(
7065 static_cast<cricket::RtpDataChannel*>(channel));
7066 break;
7067 default:
7068 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7069 break;
7070 }
Zhi Huange830e682018-03-30 10:48:35 -07007071}
Steve Anton6fec8802017-12-04 10:37:29 -08007072
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007073bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007074 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007075 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007076 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007077 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007078 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007079 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007080 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007081 auto base_channel = GetChannel(mid);
7082 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007083 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007084 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007085 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007086 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007087 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007088
Karl Wiberg5966c502019-02-21 23:55:09 +01007089 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007090 // Only pass media transport to call object if media transport is used
7091 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007092 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007093 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007094
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007095 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007096}
7097
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007098PeerConnectionObserver* PeerConnection::Observer() const {
7099 // In earlier production code, the pointer was not cleared on close,
7100 // which might have led to undefined behavior if the observer was not
7101 // deallocated, or strange crashes if it was.
7102 // We use CHECK in order to catch such behavior if it exists.
7103 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7104 RTC_CHECK(observer_);
7105 return observer_;
7106}
7107
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007108CryptoOptions PeerConnection::GetCryptoOptions() {
7109 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7110 // after it has been removed.
7111 return configuration_.crypto_options.has_value()
7112 ? *configuration_.crypto_options
7113 : factory_->options().crypto_options;
7114}
7115
Harald Alvestrand89061872018-01-02 14:08:34 +01007116void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007117 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007118 if (stats_collector_) {
7119 stats_collector_->ClearCachedStatsReport();
7120 }
7121}
7122
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007123void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007124 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7125 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007126}
7127
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007128} // namespace webrtc