blob: 2de30750612ca591284fa467f8fed566225374d1 [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"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020028#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070029#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "logging/rtc_event_log/ice_logger.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.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;
Steve Anton75737c02017-11-06 10:37:17 -080078using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070079using cricket::RELAY_PORT_TYPE;
80using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080081
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// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
559bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
560 const SessionDescriptionInterface* new_desc,
561 const std::string& content_name) {
562 if (!old_desc) {
563 return false;
564 }
565 const SessionDescription* new_sd = new_desc->description();
566 const SessionDescription* old_sd = old_desc->description();
567 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
568 if (!cinfo || cinfo->rejected) {
569 return false;
570 }
571 // If the content isn't rejected, check if ufrag and password has changed.
572 const cricket::TransportDescription* new_transport_desc =
573 new_sd->GetTransportDescriptionByName(content_name);
574 const cricket::TransportDescription* old_transport_desc =
575 old_sd->GetTransportDescriptionByName(content_name);
576 if (!new_transport_desc || !old_transport_desc) {
577 // No transport description exists. This is not an ICE restart.
578 return false;
579 }
580 if (cricket::IceCredentialsChanged(
581 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
582 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-16 17:08:42 -0800590// Generates a string error message for SetLocalDescription/SetRemoteDescription
591// from an RTCError.
592std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
593 SdpType type,
594 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200595 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800596 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
597 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200598 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800599}
600
Seth Hampson5b4f0752018-04-02 16:31:36 -0700601std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
602 std::string output = "streams=[";
603 const char* separator = "";
604 for (const auto& stream_id : stream_ids) {
605 output.append(separator).append(stream_id);
606 separator = ", ";
607 }
608 output.append("]");
609 return output;
610}
611
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 }
618 return rtc_configuration_parameter;
619}
620
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800621cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
622 switch (type) {
623 case DataMessageType::kText:
624 return cricket::DMT_TEXT;
625 case DataMessageType::kBinary:
626 return cricket::DMT_BINARY;
627 case DataMessageType::kControl:
628 return cricket::DMT_CONTROL;
629 default:
630 return cricket::DMT_NONE;
631 }
632 return cricket::DMT_NONE;
633}
634
635DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
636 switch (type) {
637 case cricket::DMT_TEXT:
638 return DataMessageType::kText;
639 case cricket::DMT_BINARY:
640 return DataMessageType::kBinary;
641 case cricket::DMT_CONTROL:
642 return DataMessageType::kControl;
643 case cricket::DMT_NONE:
644 default:
645 RTC_NOTREACHED();
646 }
647 return DataMessageType::kControl;
648}
649
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800650void ReportSimulcastApiVersion(const char* name,
651 const SessionDescription& session) {
652 bool has_legacy = false;
653 bool has_spec_compliant = false;
654 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200655 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800656 continue;
657 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200658 has_spec_compliant |= content.media_description()->HasSimulcast();
659 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800660 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
661 }
662 }
663
664 if (has_legacy) {
665 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
666 kSimulcastApiVersionMax);
667 }
668 if (has_spec_compliant) {
669 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
670 kSimulcastApiVersionMax);
671 }
672 if (!has_legacy && !has_spec_compliant) {
673 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
674 kSimulcastApiVersionMax);
675 }
676}
677
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200678const ContentInfo* FindTransceiverMSection(
679 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
680 const SessionDescriptionInterface* session_description) {
681 return transceiver->mid()
682 ? session_description->description()->GetContentByName(
683 *transceiver->mid())
684 : nullptr;
685}
686
Steve Anton75737c02017-11-06 10:37:17 -0800687} // namespace
688
Henrik Boström31638672017-11-23 17:48:32 +0100689// Upon completion, posts a task to execute the callback of the
690// SetSessionDescriptionObserver asynchronously on the same thread. At this
691// point, the state of the peer connection might no longer reflect the effects
692// of the SetRemoteDescription operation, as the peer connection could have been
693// modified during the post.
694// TODO(hbos): Remove this class once we remove the version of
695// PeerConnectionInterface::SetRemoteDescription() that takes a
696// SetSessionDescriptionObserver as an argument.
697class PeerConnection::SetRemoteDescriptionObserverAdapter
698 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
699 public:
700 SetRemoteDescriptionObserverAdapter(
701 rtc::scoped_refptr<PeerConnection> pc,
702 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
703 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
704
705 // SetRemoteDescriptionObserverInterface implementation.
706 void OnSetRemoteDescriptionComplete(RTCError error) override {
707 if (error.ok())
708 pc_->PostSetSessionDescriptionSuccess(wrapper_);
709 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100710 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100711 }
712
713 private:
714 rtc::scoped_refptr<PeerConnection> pc_;
715 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
716};
717
deadbeef293e9262017-01-11 12:28:30 -0800718bool PeerConnectionInterface::RTCConfiguration::operator==(
719 const PeerConnectionInterface::RTCConfiguration& o) const {
720 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700721 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800722 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000723 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700724 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800725 BundlePolicy bundle_policy;
726 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700727 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
728 int ice_candidate_pool_size;
729 bool disable_ipv6;
730 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700731 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100732 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200734 absl::optional<int> screencast_min_bitrate;
735 absl::optional<bool> combined_audio_video_bwe;
736 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800737 TcpCandidatePolicy tcp_candidate_policy;
738 CandidateNetworkPolicy candidate_network_policy;
739 int audio_jitter_buffer_max_packets;
740 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100741 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100742 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800743 int ice_connection_receiving_timeout;
744 int ice_backup_candidate_pair_ping_interval;
745 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800746 bool prioritize_most_likely_ice_candidate_pairs;
747 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800748 bool prune_turn_ports;
749 bool presume_writable_when_fully_relayed;
750 bool enable_ice_renomination;
751 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700752 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200753 absl::optional<int> ice_check_interval_strong_connectivity;
754 absl::optional<int> ice_check_interval_weak_connectivity;
755 absl::optional<int> ice_check_min_interval;
756 absl::optional<int> ice_unwritable_timeout;
757 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800758 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200759 absl::optional<int> stun_candidate_keepalive_interval;
760 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200761 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800762 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700764 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700765 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700766 bool use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700767 bool use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700768 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100769 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800770 };
771 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
772 "Did you add something to RTCConfiguration and forget to "
773 "update operator==?");
774 return type == o.type && servers == o.servers &&
775 bundle_policy == o.bundle_policy &&
776 rtcp_mux_policy == o.rtcp_mux_policy &&
777 tcp_candidate_policy == o.tcp_candidate_policy &&
778 candidate_network_policy == o.candidate_network_policy &&
779 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
780 audio_jitter_buffer_fast_accelerate ==
781 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100782 audio_jitter_buffer_min_delay_ms ==
783 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100784 audio_jitter_buffer_enable_rtx_handling ==
785 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800786 ice_connection_receiving_timeout ==
787 o.ice_connection_receiving_timeout &&
788 ice_backup_candidate_pair_ping_interval ==
789 o.ice_backup_candidate_pair_ping_interval &&
790 continual_gathering_policy == o.continual_gathering_policy &&
791 certificates == o.certificates &&
792 prioritize_most_likely_ice_candidate_pairs ==
793 o.prioritize_most_likely_ice_candidate_pairs &&
794 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800795 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700796 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100797 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800798 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800799 screencast_min_bitrate == o.screencast_min_bitrate &&
800 combined_audio_video_bwe == o.combined_audio_video_bwe &&
801 enable_dtls_srtp == o.enable_dtls_srtp &&
802 ice_candidate_pool_size == o.ice_candidate_pool_size &&
803 prune_turn_ports == o.prune_turn_ports &&
804 presume_writable_when_fully_relayed ==
805 o.presume_writable_when_fully_relayed &&
806 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800807 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700808 surface_ice_candidates_on_ice_transport_type_changed ==
809 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800810 ice_check_interval_strong_connectivity ==
811 o.ice_check_interval_strong_connectivity &&
812 ice_check_interval_weak_connectivity ==
813 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700814 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700815 ice_unwritable_timeout == o.ice_unwritable_timeout &&
816 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800817 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800818 stun_candidate_keepalive_interval ==
819 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200820 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800821 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800822 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700823 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700824 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700825 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700826 use_media_transport_for_data_channels ==
827 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700828 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100829 crypto_options == o.crypto_options &&
830 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800831}
832
833bool PeerConnectionInterface::RTCConfiguration::operator!=(
834 const PeerConnectionInterface::RTCConfiguration& o) const {
835 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800836}
837
zhihuang8f65cdf2016-05-06 18:40:30 -0700838// Generate a RTCP CNAME when a PeerConnection is created.
839std::string GenerateRtcpCname() {
840 std::string cname;
841 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100842 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800843 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700844 }
845 return cname;
846}
847
zhihuang1c378ed2017-08-17 14:10:50 -0700848bool ValidateOfferAnswerOptions(
849 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
850 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
851 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700852}
853
zhihuang1c378ed2017-08-17 14:10:50 -0700854// From |rtc_options|, fill parts of |session_options| shared by all generated
855// m= sections (in other words, nothing that involves a map/array).
856void ExtractSharedMediaSessionOptions(
857 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
858 cricket::MediaSessionOptions* session_options) {
859 session_options->vad_enabled = rtc_options.voice_activity_detection;
860 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200861 session_options->raw_packetization_for_video =
862 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700863}
zhihuanga77e6bb2017-08-14 18:17:48 -0700864
zhihuang38ede132017-06-15 12:52:32 -0700865PeerConnection::PeerConnection(PeerConnectionFactory* factory,
866 std::unique_ptr<RtcEventLog> event_log,
867 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700869 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100870 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700871 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700872 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700873 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100874 call_(std::move(call)),
875 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876
877PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100878 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800879 RTC_DCHECK_RUN_ON(signaling_thread());
880
Steve Anton8af21862017-12-15 11:20:13 -0800881 // Need to stop transceivers before destroying the stats collector because
882 // AudioRtpSender has a reference to the StatsCollector it will update when
883 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100884 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800885 transceiver->Stop();
886 }
Steve Anton4171afb2017-11-20 10:20:22 -0800887
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700888 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800889 if (stats_collector_) {
890 stats_collector_->WaitForPendingRequest();
891 stats_collector_ = nullptr;
892 }
Steve Anton75737c02017-11-06 10:37:17 -0800893
Steve Anton8af21862017-12-15 11:20:13 -0800894 // Don't destroy BaseChannels until after stats has been cleaned up so that
895 // the last stats request can still read from the channels.
896 DestroyAllChannels();
897
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800899
900 webrtc_session_desc_factory_.reset();
901 sctp_invoker_.reset();
902 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800903 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800904 transport_controller_.reset();
905
deadbeef91dd5672016-05-18 16:55:30 -0700906 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100907 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
908 RTC_DCHECK_RUN_ON(network_thread());
909 port_allocator_.reset();
910 });
eladalon248fd4f2017-09-06 05:18:15 -0700911 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700912 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100913 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700914 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800915 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700916 event_log_.reset();
917 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918}
919
Steve Anton8af21862017-12-15 11:20:13 -0800920void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800921 // Destroy video channels first since they may have a pointer to a voice
922 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100923 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800924 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800925 DestroyTransceiverChannel(transceiver);
926 }
927 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100928 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800929 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800930 DestroyTransceiverChannel(transceiver);
931 }
932 }
933 DestroyDataChannel();
934}
935
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000937 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700938 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100939 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100940 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100941 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700942
943 RTCError config_error = ValidateConfiguration(configuration);
944 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100945 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700946 return false;
947 }
948
Benjamin Wrightcab58882018-05-02 15:12:47 -0700949 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100950 RTC_LOG(LS_ERROR)
951 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100952 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800953 return false;
954 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200955
Benjamin Wrightcab58882018-05-02 15:12:47 -0700956 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800957 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100958 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100959 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800960 return false;
961 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700962
Benjamin Wrightcab58882018-05-02 15:12:47 -0700963 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700964 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700965 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700966 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800967
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200968 cricket::ServerAddresses stun_servers;
969 std::vector<cricket::RelayServerConfig> turn_servers;
970
971 RTCErrorType parse_error =
972 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
973 if (parse_error != RTCErrorType::NONE) {
974 return false;
975 }
976
deadbeef91dd5672016-05-18 16:55:30 -0700977 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700978 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100979 const auto pa_result =
980 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200981 RTC_FROM_HERE,
982 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100983 stun_servers, turn_servers, configuration));
984
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200985 // If initialization was successful, note if STUN or TURN servers
986 // were supplied.
987 if (!stun_servers.empty()) {
988 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
989 }
990 if (!turn_servers.empty()) {
991 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
992 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700994 // Send information about IPv4/IPv6 status.
995 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +0100996 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700997 address_family = kPeerConnection_IPv6;
998 } else {
999 address_family = kPeerConnection_IPv4;
1000 }
1001 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1002 kPeerConnectionAddressFamilyCounter_Max);
1003
Zhi Huange830e682018-03-30 10:48:35 -07001004 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1005
Steve Anton75737c02017-11-06 10:37:17 -08001006 // RFC 3264: The numeric value of the session id and version in the
1007 // o line MUST be representable with a "64 bit signed integer".
1008 // Due to this constraint session id |session_id_| is max limited to
1009 // LLONG_MAX.
1010 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001011 JsepTransportController::Config config;
1012 config.redetermine_role_on_ice_restart =
1013 configuration.redetermine_role_on_ice_restart;
1014 config.ssl_max_version = factory_->options().ssl_max_version;
1015 config.disable_encryption = options.disable_encryption;
1016 config.bundle_policy = configuration.bundle_policy;
1017 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001018 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1019 // stub.
1020 config.crypto_options = configuration.crypto_options.has_value()
1021 ? *configuration.crypto_options
1022 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001023 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001024 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001025#if defined(ENABLE_EXTERNAL_AUTH)
1026 config.enable_external_auth = true;
1027#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001028 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001029
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001030 if (configuration.use_datagram_transport ||
1031 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001032 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001033 if (!factory_->media_transport_factory()) {
1034 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001035 << "PeerConnecton is initialized with use_media_transport = true or "
1036 << "use_media_transport_for_data_channels = true "
1037 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001038 return false;
1039 }
1040
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001041 if (configuration.use_media_transport ||
1042 configuration.use_media_transport_for_data_channels) {
1043 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1044 // RTP media transport is introduced. But until then, we require SDES to
1045 // be enabled.
1046 if (configuration.enable_dtls_srtp.has_value() &&
1047 configuration.enable_dtls_srtp.value()) {
1048 RTC_LOG(LS_WARNING)
1049 << "When media transport is used, SDES must be enabled. Set "
1050 "configuration.enable_dtls_srtp to false. use_media_transport="
1051 << configuration.use_media_transport
1052 << ", use_media_transport_for_data_channels="
1053 << configuration.use_media_transport_for_data_channels;
1054 return false;
1055 }
1056 }
1057
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001058 config.use_media_transport_for_media = configuration.use_media_transport;
1059 config.use_media_transport_for_data_channels =
1060 configuration.use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001061 config.use_datagram_transport = configuration.use_datagram_transport;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001062 config.media_transport_factory = factory_->media_transport_factory();
1063 }
1064
Zhi Huange830e682018-03-30 10:48:35 -07001065 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001066 signaling_thread(), network_thread(), port_allocator_.get(),
1067 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001068 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001069 this, &PeerConnection::OnTransportControllerConnectionState);
1070 transport_controller_->SignalStandardizedIceConnectionState.connect(
1071 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001072 transport_controller_->SignalConnectionState.connect(
1073 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001074 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001075 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001076 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001077 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001078 transport_controller_->SignalIceCandidateError.connect(
1079 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001080 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001081 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1082 transport_controller_->SignalDtlsHandshakeError.connect(
1083 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1084
1085 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001086
deadbeefab9b2d12015-10-14 11:33:11 -07001087 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001088 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089
Steve Antonba818672017-11-06 10:21:57 -08001090 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001091 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001092
Steve Anton75737c02017-11-06 10:37:17 -08001093 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1094 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1095 if (!configuration.certificates.empty()) {
1096 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1097 // just picking the first one. The decision should be made based on the DTLS
1098 // handshake. The DTLS negotiations need to know about all certificates.
1099 certificate = configuration.certificates[0];
1100 }
1101
Steve Antond25da372017-11-06 14:50:29 -08001102 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001103
1104 if (options.disable_encryption) {
1105 dtls_enabled_ = false;
1106 } else {
1107 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001108 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001109 // |configuration| can override the default |dtls_enabled_| value.
1110 if (configuration.enable_dtls_srtp) {
1111 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1112 }
1113 }
1114
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001115 if (configuration.use_media_transport_for_data_channels) {
1116 if (configuration.enable_rtp_data_channel) {
1117 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1118 "use_media_transport_for_data_channels are "
1119 "incompatible and cannot both be set to true";
1120 return false;
1121 }
1122 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1123 } else if (configuration.enable_rtp_data_channel) {
1124 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1125 // set. It takes precendence over the disable_sctp_data_channels
1126 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001127 data_channel_type_ = cricket::DCT_RTP;
1128 } else {
1129 // DTLS has to be enabled to use SCTP.
1130 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1131 data_channel_type_ = cricket::DCT_SCTP;
1132 }
1133 }
1134
1135 video_options_.screencast_min_bitrate_kbps =
1136 configuration.screencast_min_bitrate;
1137 audio_options_.combined_audio_video_bwe =
1138 configuration.combined_audio_video_bwe;
1139
1140 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001141 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001142
1143 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001144 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001145
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001146 audio_options_.audio_jitter_buffer_min_delay_ms =
1147 configuration.audio_jitter_buffer_min_delay_ms;
1148
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001149 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1150 configuration.audio_jitter_buffer_enable_rtx_handling;
1151
Steve Anton75737c02017-11-06 10:37:17 -08001152 // Whether the certificate generator/certificate is null or not determines
1153 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1154 // the right instructions by clearing the variables if needed.
1155 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001156 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001157 certificate = nullptr;
1158 } else if (certificate) {
1159 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001160 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001161 }
1162
1163 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1164 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001165 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001166 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1167 this, &PeerConnection::OnCertificateReady);
1168
1169 if (options.disable_encryption) {
1170 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1171 }
1172
1173 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001174 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001175 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001176
Steve Anton4171afb2017-11-20 10:20:22 -08001177 // Add default audio/video transceivers for Plan B SDP.
1178 if (!IsUnifiedPlan()) {
1179 transceivers_.push_back(
1180 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1181 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1182 transceivers_.push_back(
1183 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1184 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1185 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001186 int delay_ms =
1187 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001188 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1189 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001190
1191 if (dependencies.video_bitrate_allocator_factory) {
1192 video_bitrate_allocator_factory_ =
1193 std::move(dependencies.video_bitrate_allocator_factory);
1194 } else {
1195 video_bitrate_allocator_factory_ =
1196 CreateBuiltinVideoBitrateAllocatorFactory();
1197 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001198 return true;
1199}
1200
Steve Anton038834f2017-07-14 15:59:59 -07001201RTCError PeerConnection::ValidateConfiguration(
1202 const RTCConfiguration& config) const {
1203 if (config.ice_regather_interval_range &&
1204 config.continual_gathering_policy == GATHER_ONCE) {
1205 return RTCError(RTCErrorType::INVALID_PARAMETER,
1206 "ice_regather_interval_range specified but continual "
1207 "gathering policy is GATHER_ONCE");
1208 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001209 auto result =
1210 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1211 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001212}
1213
Yves Gerey665174f2018-06-19 15:03:05 +02001214rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001215 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001216 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1217 "Plan SdpSemantics. Please use GetSenders "
1218 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001219 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220}
1221
Yves Gerey665174f2018-06-19 15:03:05 +02001222rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001223 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001224 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1225 "Plan SdpSemantics. Please use GetReceivers "
1226 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001227 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228}
1229
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001230bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001231 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001232 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1233 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001234 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 if (IsClosed()) {
1236 return false;
1237 }
deadbeefab9b2d12015-10-14 11:33:11 -07001238 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 return false;
1240 }
deadbeefab9b2d12015-10-14 11:33:11 -07001241
1242 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001243 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1244 observer->SignalAudioTrackAdded.connect(this,
1245 &PeerConnection::OnAudioTrackAdded);
1246 observer->SignalAudioTrackRemoved.connect(
1247 this, &PeerConnection::OnAudioTrackRemoved);
1248 observer->SignalVideoTrackAdded.connect(this,
1249 &PeerConnection::OnVideoTrackAdded);
1250 observer->SignalVideoTrackRemoved.connect(
1251 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001252 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001253
deadbeefab9b2d12015-10-14 11:33:11 -07001254 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001255 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001256 }
1257 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001258 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001259 }
1260
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001261 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001262 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 return true;
1264}
1265
1266void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001267 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001268 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1269 "Plan SdpSemantics. Please use RemoveTrack "
1270 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001271 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001272 if (!IsClosed()) {
1273 for (const auto& track : local_stream->GetAudioTracks()) {
1274 RemoveAudioTrack(track.get(), local_stream);
1275 }
1276 for (const auto& track : local_stream->GetVideoTracks()) {
1277 RemoveVideoTrack(track.get(), local_stream);
1278 }
deadbeefab9b2d12015-10-14 11:33:11 -07001279 }
deadbeefab9b2d12015-10-14 11:33:11 -07001280 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001281 stream_observers_.erase(
1282 std::remove_if(
1283 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001284 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001285 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001286 }),
1287 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 if (IsClosed()) {
1290 return;
1291 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001292 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293}
1294
Steve Anton2d6c76a2018-01-05 17:10:52 -08001295RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001296 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001297 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001298 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001299 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001300 if (!track) {
1301 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1302 }
1303 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1304 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1306 "Track has invalid kind: " + track->kind());
1307 }
Steve Antonf9381f02017-12-14 10:23:57 -08001308 if (IsClosed()) {
1309 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1310 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001311 }
Steve Anton4171afb2017-11-20 10:20:22 -08001312 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001313 LOG_AND_RETURN_ERROR(
1314 RTCErrorType::INVALID_PARAMETER,
1315 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001316 }
Steve Antonf9381f02017-12-14 10:23:57 -08001317 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001318 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1319 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001320 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001321 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001322 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001323 }
1324 return sender_or_error;
1325}
deadbeefe1f9d832016-01-14 15:35:42 -08001326
Steve Antonf9381f02017-12-14 10:23:57 -08001327RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1328PeerConnection::AddTrackPlanB(
1329 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001330 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001331 if (stream_ids.size() > 1u) {
1332 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1333 "AddTrack with more than one stream is not "
1334 "supported with Plan B semantics.");
1335 }
1336 std::vector<std::string> adjusted_stream_ids = stream_ids;
1337 if (adjusted_stream_ids.empty()) {
1338 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1339 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001340 cricket::MediaType media_type =
1341 (track->kind() == MediaStreamTrackInterface::kAudioKind
1342 ? cricket::MEDIA_TYPE_AUDIO
1343 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001344 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001345 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001346 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001347 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001348 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001349 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001350 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001351 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001352 if (sender_info) {
1353 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001354 }
Steve Antonf9381f02017-12-14 10:23:57 -08001355 } else {
1356 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001357 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001358 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001359 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001360 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001361 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001362 if (sender_info) {
1363 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001364 }
deadbeefe1f9d832016-01-14 15:35:42 -08001365 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001366 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001367}
deadbeefe1f9d832016-01-14 15:35:42 -08001368
Steve Antonf9381f02017-12-14 10:23:57 -08001369RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1370PeerConnection::AddTrackUnifiedPlan(
1371 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001372 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001373 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1374 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001375 RTC_LOG(LS_INFO) << "Reusing an existing "
1376 << cricket::MediaTypeToString(transceiver->media_type())
1377 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001378 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001379 transceiver->internal()->set_direction(
1380 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001381 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001382 transceiver->internal()->set_direction(
1383 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001384 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001385 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001386 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001387 } else {
1388 cricket::MediaType media_type =
1389 (track->kind() == MediaStreamTrackInterface::kAudioKind
1390 ? cricket::MEDIA_TYPE_AUDIO
1391 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001392 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1393 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001394 std::string sender_id = track->id();
1395 // Avoid creating a sender with an existing ID by generating a random ID.
1396 // This can happen if this is the second time AddTrack has created a sender
1397 // for this track.
1398 if (FindSenderById(sender_id)) {
1399 sender_id = rtc::CreateRandomUuid();
1400 }
Florent Castelli892acf02018-10-01 22:47:20 +02001401 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001402 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1403 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001404 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001405 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001406 }
Steve Antonf9381f02017-12-14 10:23:57 -08001407 return transceiver->sender();
1408}
1409
1410rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1411PeerConnection::FindFirstTransceiverForAddedTrack(
1412 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1413 RTC_DCHECK(track);
1414 for (auto transceiver : transceivers_) {
1415 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001416 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001417 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001418 !transceiver->internal()->has_ever_been_used_to_send() &&
1419 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001420 return transceiver;
1421 }
1422 }
1423 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001424}
1425
1426bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1427 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001428 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001429}
1430
Steve Anton24db5732018-07-23 10:27:33 -07001431RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001432 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001433 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001434 if (!sender) {
1435 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1436 }
deadbeefe1f9d832016-01-14 15:35:42 -08001437 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001438 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1439 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001440 }
Steve Antonf9381f02017-12-14 10:23:57 -08001441 if (IsUnifiedPlan()) {
1442 auto transceiver = FindTransceiverBySender(sender);
1443 if (!transceiver || !sender->track()) {
1444 return RTCError::OK();
1445 }
1446 sender->SetTrack(nullptr);
1447 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001448 transceiver->internal()->set_direction(
1449 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001450 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001451 transceiver->internal()->set_direction(
1452 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001453 }
Steve Anton4171afb2017-11-20 10:20:22 -08001454 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001455 bool removed;
1456 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1457 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1458 } else {
1459 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1460 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1461 }
1462 if (!removed) {
1463 LOG_AND_RETURN_ERROR(
1464 RTCErrorType::INVALID_PARAMETER,
1465 "Couldn't find sender " + sender->id() + " to remove.");
1466 }
Steve Anton4171afb2017-11-20 10:20:22 -08001467 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001468 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001469 return RTCError::OK();
1470}
1471
1472rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1473PeerConnection::FindTransceiverBySender(
1474 rtc::scoped_refptr<RtpSenderInterface> sender) {
1475 for (auto transceiver : transceivers_) {
1476 if (transceiver->sender() == sender) {
1477 return transceiver;
1478 }
1479 }
1480 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001481}
1482
Steve Anton9158ef62017-11-27 13:01:52 -08001483RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1484PeerConnection::AddTransceiver(
1485 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1486 return AddTransceiver(track, RtpTransceiverInit());
1487}
1488
1489RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1490PeerConnection::AddTransceiver(
1491 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1492 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001493 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001494 RTC_CHECK(IsUnifiedPlan())
1495 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001496 if (!track) {
1497 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1498 }
1499 cricket::MediaType media_type;
1500 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1501 media_type = cricket::MEDIA_TYPE_AUDIO;
1502 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1503 media_type = cricket::MEDIA_TYPE_VIDEO;
1504 } else {
1505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1506 "Track kind is not audio or video");
1507 }
1508 return AddTransceiver(media_type, track, init);
1509}
1510
1511RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1512PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1513 return AddTransceiver(media_type, RtpTransceiverInit());
1514}
1515
1516RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1517PeerConnection::AddTransceiver(cricket::MediaType media_type,
1518 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001519 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001520 RTC_CHECK(IsUnifiedPlan())
1521 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001522 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1523 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1524 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1525 "media type is not audio or video");
1526 }
1527 return AddTransceiver(media_type, nullptr, init);
1528}
1529
1530RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1531PeerConnection::AddTransceiver(
1532 cricket::MediaType media_type,
1533 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001534 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001535 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001536 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1537 media_type == cricket::MEDIA_TYPE_VIDEO));
1538 if (track) {
1539 RTC_DCHECK_EQ(media_type,
1540 (track->kind() == MediaStreamTrackInterface::kAudioKind
1541 ? cricket::MEDIA_TYPE_AUDIO
1542 : cricket::MEDIA_TYPE_VIDEO));
1543 }
1544
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001545 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1546 init.send_encodings.size(), 0, 7, 8);
1547
Amit Hilbuchaa584152019-02-06 17:09:52 -08001548 size_t num_rids = absl::c_count_if(init.send_encodings,
1549 [](const RtpEncodingParameters& encoding) {
1550 return !encoding.rid.empty();
1551 });
1552 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001553 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001554 RTCErrorType::INVALID_PARAMETER,
1555 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001556 }
1557
Amit Hilbuchf4770402019-04-08 14:11:57 -07001558 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1559 [](const RtpEncodingParameters& encoding) {
1560 return !IsLegalRsidName(encoding.rid);
1561 })) {
1562 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1563 "Invalid RID value provided.");
1564 }
1565
Amit Hilbuchaa584152019-02-06 17:09:52 -08001566 if (absl::c_any_of(init.send_encodings,
1567 [](const RtpEncodingParameters& encoding) {
1568 return encoding.ssrc.has_value();
1569 })) {
1570 LOG_AND_RETURN_ERROR(
1571 RTCErrorType::UNSUPPORTED_PARAMETER,
1572 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001573 }
1574
1575 RtpParameters parameters;
1576 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001577
1578 // Encodings are dropped from the tail if too many are provided.
1579 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1580 parameters.encodings.erase(
1581 parameters.encodings.begin() + kMaxSimulcastStreams,
1582 parameters.encodings.end());
1583 }
1584
1585 // Single RID should be removed.
1586 if (parameters.encodings.size() == 1 &&
1587 !parameters.encodings[0].rid.empty()) {
1588 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1589 parameters.encodings[0].rid.clear();
1590 }
1591
1592 // If RIDs were not provided, they are generated for simulcast scenario.
1593 if (parameters.encodings.size() > 1 && num_rids == 0) {
1594 rtc::UniqueStringGenerator rid_generator;
1595 for (RtpEncodingParameters& encoding : parameters.encodings) {
1596 encoding.rid = rid_generator();
1597 }
1598 }
1599
Florent Castelli892acf02018-10-01 22:47:20 +02001600 if (UnimplementedRtpParameterHasValue(parameters)) {
1601 LOG_AND_RETURN_ERROR(
1602 RTCErrorType::UNSUPPORTED_PARAMETER,
1603 "Attempted to set an unimplemented parameter of RtpParameters.");
1604 }
Steve Anton9158ef62017-11-27 13:01:52 -08001605
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001606 auto result = cricket::CheckRtpParametersValues(parameters);
1607 if (!result.ok()) {
1608 LOG_AND_RETURN_ERROR(result.type(), result.message());
1609 }
1610
Steve Anton3d954a62018-04-02 11:27:23 -07001611 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1612 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001613 // Set the sender ID equal to the track ID if the track is specified unless
1614 // that sender ID is already in use.
1615 std::string sender_id =
1616 (track && !FindSenderById(track->id()) ? track->id()
1617 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001618 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001619 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001620 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1621 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1622 transceiver->internal()->set_direction(init.direction);
1623
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001624 if (update_negotiation_needed) {
1625 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001626 }
Steve Antonf9381f02017-12-14 10:23:57 -08001627
1628 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1629}
1630
Steve Anton02ee47c2018-01-10 16:26:06 -08001631rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1632PeerConnection::CreateSender(
1633 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001634 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001635 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001636 const std::vector<std::string>& stream_ids,
1637 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001638 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001639 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001640 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1641 RTC_DCHECK(!track ||
1642 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1643 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1644 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001645 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001646 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001647 } else {
1648 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1649 RTC_DCHECK(!track ||
1650 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1651 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001652 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001653 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001654 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001655 bool set_track_succeeded = sender->SetTrack(track);
1656 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001657 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001658 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001659 return sender;
1660}
1661
1662rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1663PeerConnection::CreateReceiver(cricket::MediaType media_type,
1664 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001665 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1666 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001667 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001668 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001669 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1670 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001671 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001672 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001673 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001674 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001675 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1676 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001677 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001678 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001679 return receiver;
1680}
1681
1682rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1683PeerConnection::CreateAndAddTransceiver(
1684 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1685 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1686 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001687 // Ensure that the new sender does not have an ID that is already in use by
1688 // another sender.
1689 // Allow receiver IDs to conflict since those come from remote SDP (which
1690 // could be invalid, but should not cause a crash).
1691 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001692 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001693 signaling_thread(),
1694 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001695 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001696 transceiver->internal()->SignalNegotiationNeeded.connect(
1697 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001698 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001699}
1700
Steve Anton52d86772018-02-20 15:48:12 -08001701void PeerConnection::OnNegotiationNeeded() {
1702 RTC_DCHECK_RUN_ON(signaling_thread());
1703 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001704 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001705}
1706
deadbeeffac06552015-11-25 11:26:01 -08001707rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001708 const std::string& kind,
1709 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001710 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001711 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1712 "Plan SdpSemantics. Please use AddTransceiver "
1713 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001714 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001715 if (IsClosed()) {
1716 return nullptr;
1717 }
Steve Anton4171afb2017-11-20 10:20:22 -08001718
Seth Hampson5b4f0752018-04-02 16:31:36 -07001719 // Internally we need to have one stream with Plan B semantics, so we
1720 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001721 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001722 if (stream_id.empty()) {
1723 stream_ids.push_back(rtc::CreateRandomUuid());
1724 RTC_LOG(LS_INFO)
1725 << "No stream_id specified for sender. Generated stream ID: "
1726 << stream_ids[0];
1727 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001728 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001729 }
1730
Steve Anton4171afb2017-11-20 10:20:22 -08001731 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001732 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001733 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001734 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001735 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001736 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001737 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001738 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001739 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001740 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001741 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001742 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001743 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001744 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001745 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001746 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001747 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001748 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001749 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001750 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001751 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001752
deadbeefe1f9d832016-01-14 15:35:42 -08001753 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001754}
1755
deadbeef70ab1a12015-09-28 16:53:55 -07001756std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1757 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001758 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001759 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001760 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001761 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001762 }
1763 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001764}
1765
Steve Anton4171afb2017-11-20 10:20:22 -08001766std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1767PeerConnection::GetSendersInternal() const {
1768 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1769 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001770 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001771 auto senders = transceiver->internal()->senders();
1772 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1773 }
1774 return all_senders;
1775}
1776
deadbeef70ab1a12015-09-28 16:53:55 -07001777std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1778PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001779 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001780 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001781 for (const auto& receiver : GetReceiversInternal()) {
1782 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001783 }
1784 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001785}
1786
Steve Anton4171afb2017-11-20 10:20:22 -08001787std::vector<
1788 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1789PeerConnection::GetReceiversInternal() const {
1790 std::vector<
1791 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1792 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001793 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001794 auto receivers = transceiver->internal()->receivers();
1795 all_receivers.insert(all_receivers.end(), receivers.begin(),
1796 receivers.end());
1797 }
1798 return all_receivers;
1799}
1800
Steve Anton9158ef62017-11-27 13:01:52 -08001801std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1802PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001803 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001804 RTC_CHECK(IsUnifiedPlan())
1805 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001806 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001807 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001808 all_transceivers.push_back(transceiver);
1809 }
1810 return all_transceivers;
1811}
1812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001814 MediaStreamTrackInterface* track,
1815 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001816 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001817 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001818 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return false;
1821 }
1822
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001823 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001824 // The StatsCollector is used to tell if a track is valid because it may
1825 // remember tracks that the PeerConnection previously removed.
1826 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1828 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001829 return false;
1830 }
Steve Antonad182762018-09-05 20:22:40 +00001831 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1832 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001833 return true;
1834}
1835
hbos74e1a4f2016-09-15 23:33:01 -07001836void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001837 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001838 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001839 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001840 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001841 stats_collector_->GetStatsReport(callback);
1842}
1843
Henrik Boström1df1bf82018-03-20 13:24:20 +01001844void PeerConnection::GetStats(
1845 rtc::scoped_refptr<RtpSenderInterface> selector,
1846 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1847 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001848 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001849 RTC_DCHECK(callback);
1850 RTC_DCHECK(stats_collector_);
1851 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1852 if (selector) {
1853 for (const auto& proxy_transceiver : transceivers_) {
1854 for (const auto& proxy_sender :
1855 proxy_transceiver->internal()->senders()) {
1856 if (proxy_sender == selector) {
1857 internal_sender = proxy_sender->internal();
1858 break;
1859 }
1860 }
1861 if (internal_sender)
1862 break;
1863 }
1864 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001865 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001866 // belong to the PeerConnection (in Plan B, senders can be removed from the
1867 // PeerConnection). This means that "all the stats objects representing the
1868 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1869 // produces an empty stats report.
1870 stats_collector_->GetStatsReport(internal_sender, callback);
1871}
1872
1873void PeerConnection::GetStats(
1874 rtc::scoped_refptr<RtpReceiverInterface> selector,
1875 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1876 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001877 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001878 RTC_DCHECK(callback);
1879 RTC_DCHECK(stats_collector_);
1880 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1881 if (selector) {
1882 for (const auto& proxy_transceiver : transceivers_) {
1883 for (const auto& proxy_receiver :
1884 proxy_transceiver->internal()->receivers()) {
1885 if (proxy_receiver == selector) {
1886 internal_receiver = proxy_receiver->internal();
1887 break;
1888 }
1889 }
1890 if (internal_receiver)
1891 break;
1892 }
1893 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001894 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001895 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1896 // the PeerConnection). This means that "all the stats objects representing
1897 // the selector" is an empty set. Invoking GetStatsReport() with a null
1898 // selector produces an empty stats report.
1899 stats_collector_->GetStatsReport(internal_receiver, callback);
1900}
1901
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902PeerConnectionInterface::SignalingState PeerConnection::signaling_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 signaling_state_;
1905}
1906
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907PeerConnectionInterface::IceConnectionState
1908PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001909 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 return ice_connection_state_;
1911}
1912
Alex Loiko9289eda2018-11-23 16:18:59 +00001913PeerConnectionInterface::IceConnectionState
1914PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001915 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001916 return standardized_ice_connection_state_;
1917}
1918
Jonas Olsson635474e2018-10-18 15:58:17 +02001919PeerConnectionInterface::PeerConnectionState
1920PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001922 return connection_state_;
1923}
1924
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925PeerConnectionInterface::IceGatheringState
1926PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001927 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 return ice_gathering_state_;
1929}
1930
Yves Gerey665174f2018-06-19 15:03:05 +02001931rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932 const std::string& label,
1933 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001934 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001935 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001936
deadbeefab9b2d12015-10-14 11:33:11 -07001937 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001938
kwibergd1fe2812016-04-27 06:47:29 -07001939 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001940 if (config) {
1941 internal_config.reset(new InternalDataChannelInit(*config));
1942 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001943 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001944 InternalCreateDataChannel(label, internal_config.get()));
1945 if (!channel.get()) {
1946 return nullptr;
1947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001948
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001949 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1950 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001951 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001952 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001953 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001954 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955 return DataChannelProxy::Create(signaling_thread(), channel.get());
1956}
1957
1958void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001959 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001960 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001961 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001962
nisse7ce109a2017-01-31 00:57:56 -08001963 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001964 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001965 return;
1966 }
deadbeefab9b2d12015-10-14 11:33:11 -07001967
Steve Anton8d3444d2017-10-20 15:30:51 -07001968 if (IsClosed()) {
1969 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001970 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001971 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001972 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001973 return;
1974 }
1975
zhihuang1c378ed2017-08-17 14:10:50 -07001976 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001977 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001978 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001979 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001980 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001981 return;
1982 }
1983
Steve Anton22da89f2018-01-25 13:58:07 -08001984 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1985 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1986 if (IsUnifiedPlan()) {
1987 RTCError error = HandleLegacyOfferOptions(options);
1988 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001989 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001990 return;
1991 }
1992 }
1993
zhihuang1c378ed2017-08-17 14:10:50 -07001994 cricket::MediaSessionOptions session_options;
1995 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001996 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997}
1998
Steve Anton22da89f2018-01-25 13:58:07 -08001999RTCError PeerConnection::HandleLegacyOfferOptions(
2000 const RTCOfferAnswerOptions& options) {
2001 RTC_DCHECK(IsUnifiedPlan());
2002
2003 if (options.offer_to_receive_audio == 0) {
2004 RemoveRecvDirectionFromReceivingTransceiversOfType(
2005 cricket::MEDIA_TYPE_AUDIO);
2006 } else if (options.offer_to_receive_audio == 1) {
2007 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2008 } else if (options.offer_to_receive_audio > 1) {
2009 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2010 "offer_to_receive_audio > 1 is not supported.");
2011 }
2012
2013 if (options.offer_to_receive_video == 0) {
2014 RemoveRecvDirectionFromReceivingTransceiversOfType(
2015 cricket::MEDIA_TYPE_VIDEO);
2016 } else if (options.offer_to_receive_video == 1) {
2017 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2018 } else if (options.offer_to_receive_video > 1) {
2019 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2020 "offer_to_receive_video > 1 is not supported.");
2021 }
2022
2023 return RTCError::OK();
2024}
2025
2026void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2027 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002028 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002029 RtpTransceiverDirection new_direction =
2030 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2031 if (new_direction != transceiver->direction()) {
2032 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2033 << " transceiver (MID="
2034 << transceiver->mid().value_or("<not set>") << ") from "
2035 << RtpTransceiverDirectionToString(
2036 transceiver->direction())
2037 << " to "
2038 << RtpTransceiverDirectionToString(new_direction)
2039 << " since CreateOffer specified offer_to_receive=0";
2040 transceiver->internal()->set_direction(new_direction);
2041 }
Steve Anton22da89f2018-01-25 13:58:07 -08002042 }
2043}
2044
2045void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2046 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002047 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002048 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002049 RTC_LOG(LS_INFO)
2050 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2051 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002052 RtpTransceiverInit init;
2053 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002054 AddTransceiver(media_type, nullptr, init,
2055 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002056 }
2057}
2058
2059std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2060PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2061 std::vector<
2062 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2063 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002064 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002065 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002066 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2067 receiving_transceivers.push_back(transceiver);
2068 }
2069 }
2070 return receiving_transceivers;
2071}
2072
htaa2a49d92016-03-04 02:51:39 -08002073void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2074 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002075 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002076 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002077 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002078 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002079 return;
2080 }
2081
Steve Antondffead82018-02-06 10:31:29 -08002082 if (!(signaling_state_ == kHaveRemoteOffer ||
2083 signaling_state_ == kHaveLocalPrAnswer)) {
2084 std::string error =
2085 "PeerConnection cannot create an answer in a state other than "
2086 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002087 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002088 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002089 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002090 return;
2091 }
2092
Steve Antondffead82018-02-06 10:31:29 -08002093 // The remote description should be set if we're in the right state.
2094 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002095
Steve Anton22da89f2018-01-25 13:58:07 -08002096 if (IsUnifiedPlan()) {
2097 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2098 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2099 "supported with Unified Plan semantics. Use the "
2100 "RtpTransceiver API instead.";
2101 }
2102 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2103 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2104 "supported with Unified Plan semantics. Use the "
2105 "RtpTransceiver API instead.";
2106 }
2107 }
2108
htaa2a49d92016-03-04 02:51:39 -08002109 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002110 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002111
Steve Antond25da372017-11-06 14:50:29 -08002112 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002113}
2114
2115void PeerConnection::SetLocalDescription(
2116 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002117 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002118 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002119 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002120
Steve Anton80dd7b52018-02-16 17:08:42 -08002121 // The SetLocalDescription contract is that we take ownership of the session
2122 // description regardless of the outcome, so wrap it in a unique_ptr right
2123 // away. Ideally, SetLocalDescription's signature will be changed to take the
2124 // description as a unique_ptr argument to formalize this agreement.
2125 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2126
nisse7ce109a2017-01-31 00:57:56 -08002127 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002128 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129 return;
2130 }
Steve Anton8a006912017-12-04 15:25:56 -08002131
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002133 PostSetSessionDescriptionFailure(
2134 observer,
2135 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136 return;
2137 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002138
Steve Anton80dd7b52018-02-16 17:08:42 -08002139 // If a session error has occurred the PeerConnection is in a possibly
2140 // inconsistent state so fail right away.
2141 if (session_error() != SessionError::kNone) {
2142 std::string error_message = GetSessionErrorMsg();
2143 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002144 PostSetSessionDescriptionFailure(
2145 observer,
2146 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002147 return;
2148 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002149
Steve Anton80dd7b52018-02-16 17:08:42 -08002150 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2151 if (!error.ok()) {
2152 std::string error_message = GetSetDescriptionErrorMessage(
2153 cricket::CS_LOCAL, desc->GetType(), error);
2154 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002155 PostSetSessionDescriptionFailure(
2156 observer,
2157 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002158 return;
2159 }
2160
2161 // Grab the description type before moving ownership to ApplyLocalDescription,
2162 // which may destroy it before returning.
2163 const SdpType type = desc->GetType();
2164
2165 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002166 // |desc| may be destroyed at this point.
2167
2168 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002169 // If ApplyLocalDescription fails, the PeerConnection could be in an
2170 // inconsistent state, so act conservatively here and set the session error
2171 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2172 SetSessionError(SessionError::kContent, error.message());
2173 std::string error_message =
2174 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2175 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002176 PostSetSessionDescriptionFailure(
2177 observer,
2178 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002179 return;
2180 }
Steve Anton8a006912017-12-04 15:25:56 -08002181 RTC_DCHECK(local_description());
2182
2183 PostSetSessionDescriptionSuccess(observer);
2184
Steve Antonad182762018-09-05 20:22:40 +00002185 // MaybeStartGathering needs to be called after posting
2186 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2187 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002188 transport_controller_->MaybeStartGathering();
2189
Steve Antona3a92c22017-12-07 10:27:41 -08002190 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002191 // TODO(deadbeef): We already had to hop to the network thread for
2192 // MaybeStartGathering...
2193 network_thread()->Invoke<void>(
2194 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2195 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002196 // Make UMA notes about what was agreed to.
2197 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002198 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002199
2200 if (IsUnifiedPlan()) {
2201 bool was_negotiation_needed = is_negotiation_needed_;
2202 UpdateNegotiationNeeded();
2203 if (signaling_state() == kStable && was_negotiation_needed &&
2204 is_negotiation_needed_) {
2205 Observer()->OnRenegotiationNeeded();
2206 }
2207 }
2208
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002209 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002210}
2211
2212RTCError PeerConnection::ApplyLocalDescription(
2213 std::unique_ptr<SessionDescriptionInterface> desc) {
2214 RTC_DCHECK_RUN_ON(signaling_thread());
2215 RTC_DCHECK(desc);
2216
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217 // Update stats here so that we have the most recent stats for tracks and
2218 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002219 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002220
Steve Antondcc3c022017-12-22 16:02:54 -08002221 // Take a reference to the old local description since it's used below to
2222 // compare against the new local description. When setting the new local
2223 // description, grab ownership of the replaced session description in case it
2224 // is the same as |old_local_description|, to keep it alive for the duration
2225 // of the method.
2226 const SessionDescriptionInterface* old_local_description =
2227 local_description();
2228 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002229 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002230 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002231 replaced_local_description = pending_local_description_
2232 ? std::move(pending_local_description_)
2233 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002234 current_local_description_ = std::move(desc);
2235 pending_local_description_ = nullptr;
2236 current_remote_description_ = std::move(pending_remote_description_);
2237 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002238 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002239 pending_local_description_ = std::move(desc);
2240 }
2241 // The session description to apply now must be accessed by
2242 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002243 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002244
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002245 // Report statistics about any use of simulcast.
2246 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2247 *local_description()->description());
2248
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002249 if (!is_caller_) {
2250 if (remote_description()) {
2251 // Remote description was applied first, so this PC is the callee.
2252 is_caller_ = false;
2253 } else {
2254 // Local description is applied first, so this PC is the caller.
2255 is_caller_ = true;
2256 }
2257 }
2258
Zhi Huange830e682018-03-30 10:48:35 -07002259 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2260 if (!error.ok()) {
2261 return error;
2262 }
2263
Steve Antondcc3c022017-12-22 16:02:54 -08002264 if (IsUnifiedPlan()) {
2265 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002266 cricket::CS_LOCAL, *local_description(), old_local_description,
2267 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002268 if (!error.ok()) {
2269 return error;
2270 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002271 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2272 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002273 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002274 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2275 // Note that code paths that don't set MID won't be able to use
2276 // information about DTLS transports.
2277 if (transceiver->mid()) {
2278 auto dtls_transport =
2279 LookupDtlsTransportByMidInternal(*transceiver->mid());
2280 transceiver->internal()->sender_internal()->set_transport(
2281 dtls_transport);
2282 transceiver->internal()->receiver_internal()->set_transport(
2283 dtls_transport);
2284 }
2285
Steve Antondcc3c022017-12-22 16:02:54 -08002286 const ContentInfo* content =
2287 FindMediaSectionForTransceiver(transceiver, local_description());
2288 if (!content) {
2289 continue;
2290 }
2291 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002292 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2293 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002294 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002295 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2296 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2297 // "recvonly", process the removal of a remote track for the media
2298 // description, given transceiver, removeList, and muteTracks.
2299 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2300 (transceiver->internal()->fired_direction() &&
2301 RtpTransceiverDirectionHasRecv(
2302 *transceiver->internal()->fired_direction()))) {
2303 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2304 &removed_streams);
2305 }
2306 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2307 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002308 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002309 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002310 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002311 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002312 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002313 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002314 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002315 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002316 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002317 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002318 }
2319 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002320 // Media channels will be created only when offer is set. These may use new
2321 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002322 if (type == SdpType::kOffer) {
2323 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2324 // description is applied. Restore back to old description.
2325 RTCError error = CreateChannels(*local_description()->description());
2326 if (!error.ok()) {
2327 return error;
2328 }
2329 }
Steve Antondcc3c022017-12-22 16:02:54 -08002330 // Remove unused channels if MediaContentDescription is rejected.
2331 RemoveUnusedChannels(local_description()->description());
2332 }
Steve Anton8a006912017-12-04 15:25:56 -08002333
Zhi Huange830e682018-03-30 10:48:35 -07002334 error = UpdateSessionState(type, cricket::CS_LOCAL,
2335 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002336 if (!error.ok()) {
2337 return error;
2338 }
Steve Antondcc3c022017-12-22 16:02:54 -08002339
Steve Anton8a006912017-12-04 15:25:56 -08002340 if (remote_description()) {
2341 // Now that we have a local description, we can push down remote candidates.
2342 UseCandidatesInSessionDescription(remote_description());
2343 }
2344
2345 pending_ice_restarts_.clear();
2346 if (session_error() != SessionError::kNone) {
2347 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2348 }
2349
deadbeefab9b2d12015-10-14 11:33:11 -07002350 // If setting the description decided our SSL role, allocate any necessary
2351 // SCTP sids.
2352 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002353 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002354 AllocateSctpSids(role);
2355 }
2356
Steve Antond3679212018-01-17 17:41:02 -08002357 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002358 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002359 const ContentInfo* content =
2360 FindMediaSectionForTransceiver(transceiver, local_description());
2361 if (!content) {
2362 continue;
2363 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002364 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2365 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002366 // 0 is a special value meaning "this sender has no associated send
2367 // stream". Need to call this so the sender won't attempt to configure
2368 // a no longer existing stream and run into DCHECKs in the lower
2369 // layers.
2370 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002371 } else {
2372 // Get the StreamParams from the channel which could generate SSRCs.
2373 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002374 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002375 streams[0].stream_ids());
2376 transceiver->internal()->sender_internal()->SetSsrc(
2377 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002378 }
2379 }
2380 } else {
2381 // Plan B semantics.
2382
Steve Antondcc3c022017-12-22 16:02:54 -08002383 // Update state and SSRC of local MediaStreams and DataChannels based on the
2384 // local session description.
2385 const cricket::ContentInfo* audio_content =
2386 GetFirstAudioContent(local_description()->description());
2387 if (audio_content) {
2388 if (audio_content->rejected) {
2389 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2390 } else {
2391 const cricket::AudioContentDescription* audio_desc =
2392 audio_content->media_description()->as_audio();
2393 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2394 }
deadbeeffaac4972015-11-12 15:33:07 -08002395 }
deadbeefab9b2d12015-10-14 11:33:11 -07002396
Steve Antondcc3c022017-12-22 16:02:54 -08002397 const cricket::ContentInfo* video_content =
2398 GetFirstVideoContent(local_description()->description());
2399 if (video_content) {
2400 if (video_content->rejected) {
2401 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2402 } else {
2403 const cricket::VideoContentDescription* video_desc =
2404 video_content->media_description()->as_video();
2405 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2406 }
deadbeeffaac4972015-11-12 15:33:07 -08002407 }
deadbeefab9b2d12015-10-14 11:33:11 -07002408 }
2409
2410 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002411 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002412 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002413 const cricket::RtpDataContentDescription* rtp_data_desc =
2414 data_content->media_description()->as_rtp_data();
2415 // rtp_data_desc will be null if this is an SCTP description.
2416 if (rtp_data_desc) {
2417 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002418 }
2419 }
2420
Steve Anton8a006912017-12-04 15:25:56 -08002421 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002422}
2423
Steve Anton06817cd2018-12-18 15:55:30 -08002424// The SDP parser used to populate these values by default for the 'content
2425// name' if an a=mid line was absent.
2426static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2427 switch (media_type) {
2428 case cricket::MEDIA_TYPE_AUDIO:
2429 return cricket::CN_AUDIO;
2430 case cricket::MEDIA_TYPE_VIDEO:
2431 return cricket::CN_VIDEO;
2432 case cricket::MEDIA_TYPE_DATA:
2433 return cricket::CN_DATA;
2434 }
2435 RTC_NOTREACHED();
2436 return "";
2437}
2438
2439void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002440 cricket::SessionDescription* new_remote_description) {
2441 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002442 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002443 const cricket::ContentInfos& local_contents =
2444 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002445 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002446 const cricket::ContentInfos& remote_contents =
2447 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002448 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002449 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2450 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002451 if (!content.name.empty()) {
2452 continue;
2453 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002454 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002455 absl::string_view source_explanation;
2456 if (IsUnifiedPlan()) {
2457 if (i < local_contents.size()) {
2458 new_mid = local_contents[i].name;
2459 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002460 } else if (i < remote_contents.size()) {
2461 new_mid = remote_contents[i].name;
2462 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002463 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002464 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002465 source_explanation = "generated just now";
2466 }
2467 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002468 new_mid = std::string(
2469 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002470 source_explanation = "to match pre-existing behavior";
2471 }
Steve Antond7180cc2019-02-07 10:44:53 -08002472 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002473 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002474 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002475 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2476 << " is missing an a=mid line. Filling in the value '"
2477 << new_mid << "' " << source_explanation << ".";
2478 }
2479}
2480
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002481void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002482 SetSessionDescriptionObserver* observer,
2483 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002484 SetRemoteDescription(
2485 std::unique_ptr<SessionDescriptionInterface>(desc),
2486 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2487 new SetRemoteDescriptionObserverAdapter(this, observer)));
2488}
2489
2490void PeerConnection::SetRemoteDescription(
2491 std::unique_ptr<SessionDescriptionInterface> desc,
2492 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002493 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002494 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002495
nisse7ce109a2017-01-31 00:57:56 -08002496 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002497 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002498 return;
2499 }
Steve Anton8a006912017-12-04 15:25:56 -08002500
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002502 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002503 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002504 return;
2505 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002506
Steve Anton80dd7b52018-02-16 17:08:42 -08002507 // If a session error has occurred the PeerConnection is in a possibly
2508 // inconsistent state so fail right away.
2509 if (session_error() != SessionError::kNone) {
2510 std::string error_message = GetSessionErrorMsg();
2511 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2512 observer->OnSetRemoteDescriptionComplete(
2513 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2514 return;
2515 }
Steve Anton71439a62018-02-15 11:53:06 -08002516
Steve Antonba42e992018-04-09 14:10:01 -07002517 if (desc->GetType() == SdpType::kOffer) {
2518 // Report to UMA the format of the received offer.
2519 ReportSdpFormatReceived(*desc);
2520 }
2521
Steve Anton06817cd2018-12-18 15:55:30 -08002522 // Handle remote descriptions missing a=mid lines for interop with legacy end
2523 // points.
2524 FillInMissingRemoteMids(desc->description());
2525
Steve Anton80dd7b52018-02-16 17:08:42 -08002526 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002527 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002528 std::string error_message = GetSetDescriptionErrorMessage(
2529 cricket::CS_REMOTE, desc->GetType(), error);
2530 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002531 observer->OnSetRemoteDescriptionComplete(
2532 RTCError(error.type(), std::move(error_message)));
2533 return;
2534 }
Steve Anton71439a62018-02-15 11:53:06 -08002535
Steve Anton80dd7b52018-02-16 17:08:42 -08002536 // Grab the description type before moving ownership to
2537 // ApplyRemoteDescription, which may destroy it before returning.
2538 const SdpType type = desc->GetType();
2539
2540 error = ApplyRemoteDescription(std::move(desc));
2541 // |desc| may be destroyed at this point.
2542
2543 if (!error.ok()) {
2544 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2545 // inconsistent state, so act conservatively here and set the session error
2546 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2547 SetSessionError(SessionError::kContent, error.message());
2548 std::string error_message =
2549 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2550 RTC_LOG(LS_ERROR) << error_message;
2551 observer->OnSetRemoteDescriptionComplete(
2552 RTCError(error.type(), std::move(error_message)));
2553 return;
2554 }
2555 RTC_DCHECK(remote_description());
2556
2557 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002558 // TODO(deadbeef): We already had to hop to the network thread for
2559 // MaybeStartGathering...
2560 network_thread()->Invoke<void>(
2561 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2562 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002563 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002564 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002565 }
2566
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002567 if (IsUnifiedPlan()) {
2568 bool was_negotiation_needed = is_negotiation_needed_;
2569 UpdateNegotiationNeeded();
2570 if (signaling_state() == kStable && was_negotiation_needed &&
2571 is_negotiation_needed_) {
2572 Observer()->OnRenegotiationNeeded();
2573 }
2574 }
2575
Steve Anton8a006912017-12-04 15:25:56 -08002576 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002577 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002578}
2579
2580RTCError PeerConnection::ApplyRemoteDescription(
2581 std::unique_ptr<SessionDescriptionInterface> desc) {
2582 RTC_DCHECK_RUN_ON(signaling_thread());
2583 RTC_DCHECK(desc);
2584
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002585 // Update stats here so that we have the most recent stats for tracks and
2586 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002587 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002588
Steve Antondcc3c022017-12-22 16:02:54 -08002589 // Take a reference to the old remote description since it's used below to
2590 // compare against the new remote description. When setting the new remote
2591 // description, grab ownership of the replaced session description in case it
2592 // is the same as |old_remote_description|, to keep it alive for the duration
2593 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002594 const SessionDescriptionInterface* old_remote_description =
2595 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002596 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002597 SdpType type = desc->GetType();
2598 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002599 replaced_remote_description = pending_remote_description_
2600 ? std::move(pending_remote_description_)
2601 : std::move(current_remote_description_);
2602 current_remote_description_ = std::move(desc);
2603 pending_remote_description_ = nullptr;
2604 current_local_description_ = std::move(pending_local_description_);
2605 } else {
2606 replaced_remote_description = std::move(pending_remote_description_);
2607 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002608 }
Steve Anton8a006912017-12-04 15:25:56 -08002609 // The session description to apply now must be accessed by
2610 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002611 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002612
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002613 // Report statistics about any use of simulcast.
2614 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2615 *remote_description()->description());
2616
Zhi Huange830e682018-03-30 10:48:35 -07002617 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2618 if (!error.ok()) {
2619 return error;
2620 }
Steve Anton8a006912017-12-04 15:25:56 -08002621 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002622 if (IsUnifiedPlan()) {
2623 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002624 cricket::CS_REMOTE, *remote_description(), local_description(),
2625 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002626 if (!error.ok()) {
2627 return error;
2628 }
Steve Antondcc3c022017-12-22 16:02:54 -08002629 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002630 // Media channels will be created only when offer is set. These may use new
2631 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002632 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002633 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002634 // description is applied. Restore back to old description.
2635 RTCError error = CreateChannels(*remote_description()->description());
2636 if (!error.ok()) {
2637 return error;
2638 }
2639 }
Steve Antondcc3c022017-12-22 16:02:54 -08002640 // Remove unused channels if MediaContentDescription is rejected.
2641 RemoveUnusedChannels(remote_description()->description());
2642 }
Steve Anton8a006912017-12-04 15:25:56 -08002643
Zhi Huange830e682018-03-30 10:48:35 -07002644 // NOTE: Candidates allocation will be initiated only when
2645 // SetLocalDescription is called.
2646 error = UpdateSessionState(type, cricket::CS_REMOTE,
2647 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002648 if (!error.ok()) {
2649 return error;
2650 }
2651
2652 if (local_description() &&
2653 !UseCandidatesInSessionDescription(remote_description())) {
2654 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2655 }
2656
2657 if (old_remote_description) {
2658 for (const cricket::ContentInfo& content :
2659 old_remote_description->description()->contents()) {
2660 // Check if this new SessionDescription contains new ICE ufrag and
2661 // password that indicates the remote peer requests an ICE restart.
2662 // TODO(deadbeef): When we start storing both the current and pending
2663 // remote description, this should reset pending_ice_restarts and compare
2664 // against the current description.
2665 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2666 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002667 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002668 pending_ice_restarts_.insert(content.name);
2669 }
2670 } else {
2671 // We retain all received candidates only if ICE is not restarted.
2672 // When ICE is restarted, all previous candidates belong to an old
2673 // generation and should not be kept.
2674 // TODO(deadbeef): This goes against the W3C spec which says the remote
2675 // description should only contain candidates from the last set remote
2676 // description plus any candidates added since then. We should remove
2677 // this once we're sure it won't break anything.
2678 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2679 old_remote_description, content.name, mutable_remote_description());
2680 }
2681 }
2682 }
2683
2684 if (session_error() != SessionError::kNone) {
2685 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2686 }
2687
2688 // Set the the ICE connection state to connecting since the connection may
2689 // become writable with peer reflexive candidates before any remote candidate
2690 // is signaled.
2691 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2692 // is to have a new signal the indicates a change in checking state from the
2693 // transport and expose a new checking() member from transport that can be
2694 // read to determine the current checking state. The existing SignalConnecting
2695 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002696 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002697 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002698 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2699 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2700 }
2701
deadbeefab9b2d12015-10-14 11:33:11 -07002702 // If setting the description decided our SSL role, allocate any necessary
2703 // SCTP sids.
2704 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002705 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002706 AllocateSctpSids(role);
2707 }
2708
Steve Antondcc3c022017-12-22 16:02:54 -08002709 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002710 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002711 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002712 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002713 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002714 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002715 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002716 const ContentInfo* content =
2717 FindMediaSectionForTransceiver(transceiver, remote_description());
2718 if (!content) {
2719 continue;
2720 }
2721 const MediaContentDescription* media_desc = content->media_description();
2722 RtpTransceiverDirection local_direction =
2723 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002724 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2725 // RTCSessionDescription: Set the associated remote streams given
2726 // transceiver.[[Receiver]], msids, addList, and removeList".
2727 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2728 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2729 std::vector<std::string> stream_ids;
2730 if (!media_desc->streams().empty()) {
2731 // The remote description has signaled the stream IDs.
2732 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002733 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002734 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2735 << " (" << GetStreamIdsString(stream_ids) << ").";
2736 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2737 stream_ids, &added_streams,
2738 &removed_streams);
2739 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2740 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2741 // and transceiver's current direction is neither sendrecv nor recvonly,
2742 // process the addition of a remote track for the media description.
2743 if (!transceiver->fired_direction() ||
2744 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2745 RTC_LOG(LS_INFO)
2746 << "Processing the addition of a remote track for MID="
2747 << content->name << ".";
2748 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002749 }
Steve Antondcc3c022017-12-22 16:02:54 -08002750 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002751 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002752 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2753 // removal of a remote track for the media description, given transceiver,
2754 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002755 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002756 (transceiver->fired_direction() &&
2757 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2758 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2759 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002760 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002761 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002762 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002763 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002764 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002765 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002766 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002767 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002768 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002769 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2770 if (transceiver->mid()) {
2771 auto dtls_transport =
2772 LookupDtlsTransportByMidInternal(*transceiver->mid());
2773 transceiver->internal()->sender_internal()->set_transport(
2774 dtls_transport);
2775 transceiver->internal()->receiver_internal()->set_transport(
2776 dtls_transport);
2777 }
Steve Antondcc3c022017-12-22 16:02:54 -08002778 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002779 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002780 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002781 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002782 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2783 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002784 transceiver->Stop();
2785 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002786 if (!content->rejected &&
2787 RtpTransceiverDirectionHasRecv(local_direction)) {
2788 // Set ssrc to 0 in the case of an unsignalled ssrc.
2789 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002790 if (!media_desc->streams().empty() &&
2791 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002792 ssrc = media_desc->streams()[0].first_ssrc();
2793 }
2794 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002795 }
Steve Antondcc3c022017-12-22 16:02:54 -08002796 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002797 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002798 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002799 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002800 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002801 observer->OnTrack(transceiver);
2802 observer->OnAddTrack(transceiver->receiver(),
2803 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002804 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002805 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002806 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002807 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002808 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002809 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002810 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002811 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002812 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002813 }
Steve Antondcc3c022017-12-22 16:02:54 -08002814 }
2815
Henrik Boströmfdb92012017-11-09 19:55:44 +01002816 const cricket::ContentInfo* audio_content =
2817 GetFirstAudioContent(remote_description()->description());
2818 const cricket::ContentInfo* video_content =
2819 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002820 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002821 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002822 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002823 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002824 const cricket::RtpDataContentDescription* rtp_data_desc =
2825 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002826
2827 // Check if the descriptions include streams, just in case the peer supports
2828 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002829 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002830 (audio_desc && !audio_desc->streams().empty()) ||
2831 (video_desc && !video_desc->streams().empty())) {
2832 remote_peer_supports_msid_ = true;
2833 }
deadbeefab9b2d12015-10-14 11:33:11 -07002834
2835 // We wait to signal new streams until we finish processing the description,
2836 // since only at that point will new streams have all their tracks.
2837 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2838
Steve Antondcc3c022017-12-22 16:02:54 -08002839 if (!IsUnifiedPlan()) {
2840 // TODO(steveanton): When removing RTP senders/receivers in response to a
2841 // rejected media section, there is some cleanup logic that expects the
2842 // voice/ video channel to still be set. But in this method the voice/video
2843 // channel would have been destroyed by the SetRemoteDescription caller
2844 // above so the cleanup that relies on them fails to run. The RemoveSenders
2845 // calls should be moved to right before the DestroyChannel calls to fix
2846 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002847
Steve Antondcc3c022017-12-22 16:02:54 -08002848 // Find all audio rtp streams and create corresponding remote AudioTracks
2849 // and MediaStreams.
2850 if (audio_content) {
2851 if (audio_content->rejected) {
2852 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2853 } else {
2854 bool default_audio_track_needed =
2855 !remote_peer_supports_msid_ &&
2856 RtpTransceiverDirectionHasSend(audio_desc->direction());
2857 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2858 default_audio_track_needed, audio_desc->type(),
2859 new_streams);
2860 }
deadbeeffaac4972015-11-12 15:33:07 -08002861 }
deadbeefab9b2d12015-10-14 11:33:11 -07002862
Steve Antondcc3c022017-12-22 16:02:54 -08002863 // Find all video rtp streams and create corresponding remote VideoTracks
2864 // and MediaStreams.
2865 if (video_content) {
2866 if (video_content->rejected) {
2867 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2868 } else {
2869 bool default_video_track_needed =
2870 !remote_peer_supports_msid_ &&
2871 RtpTransceiverDirectionHasSend(video_desc->direction());
2872 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2873 default_video_track_needed, video_desc->type(),
2874 new_streams);
2875 }
deadbeeffaac4972015-11-12 15:33:07 -08002876 }
deadbeefab9b2d12015-10-14 11:33:11 -07002877
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002878 // If this is an RTP data transport, update the DataChannels with the
2879 // information from the remote peer.
2880 if (rtp_data_desc) {
2881 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002882 }
deadbeefab9b2d12015-10-14 11:33:11 -07002883
Steve Antondcc3c022017-12-22 16:02:54 -08002884 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002885 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002886 for (size_t i = 0; i < new_streams->count(); ++i) {
2887 MediaStreamInterface* new_stream = new_streams->at(i);
2888 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002889 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002890 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2891 }
deadbeefab9b2d12015-10-14 11:33:11 -07002892
Steve Antondcc3c022017-12-22 16:02:54 -08002893 UpdateEndedRemoteMediaStreams();
2894 }
deadbeefab9b2d12015-10-14 11:33:11 -07002895
Steve Anton8a006912017-12-04 15:25:56 -08002896 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002897}
2898
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002899void PeerConnection::SetAssociatedRemoteStreams(
2900 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2901 const std::vector<std::string>& stream_ids,
2902 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2903 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2904 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2905 for (const std::string& stream_id : stream_ids) {
2906 rtc::scoped_refptr<MediaStreamInterface> stream =
2907 remote_streams_->find(stream_id);
2908 if (!stream) {
2909 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2910 MediaStream::Create(stream_id));
2911 remote_streams_->AddStream(stream);
2912 added_streams->push_back(stream);
2913 }
2914 media_streams.push_back(stream);
2915 }
2916 // Special case: "a=msid" missing, use random stream ID.
2917 if (media_streams.empty() &&
2918 !(remote_description()->description()->msid_signaling() &
2919 cricket::kMsidSignalingMediaSection)) {
2920 if (!missing_msid_default_stream_) {
2921 missing_msid_default_stream_ = MediaStreamProxy::Create(
2922 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2923 added_streams->push_back(missing_msid_default_stream_);
2924 }
2925 media_streams.push_back(missing_msid_default_stream_);
2926 }
2927 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2928 receiver->streams();
2929 // SetStreams() will add/remove the receiver's track to/from the streams. This
2930 // differs from the spec - the spec uses an "addList" and "removeList" to
2931 // update the stream-track relationships in a later step. We do this earlier,
2932 // changing the order of things, but the end-result is the same.
2933 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2934 // instead. https://crbug.com/webrtc/9480
2935 receiver->SetStreams(media_streams);
2936 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2937}
2938
Steve Anton0f5400a2018-07-17 14:25:36 -07002939void PeerConnection::ProcessRemovalOfRemoteTrack(
2940 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2941 transceiver,
2942 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2943 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2944 RTC_DCHECK(transceiver->mid());
2945 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2946 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002947 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002948 transceiver->internal()->receiver_internal()->streams();
2949 // This will remove the remote track from the streams.
2950 transceiver->internal()->receiver_internal()->set_stream_ids({});
2951 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002952 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2953}
2954
2955void PeerConnection::RemoveRemoteStreamsIfEmpty(
2956 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2957 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2958 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2959 // streams, see if the stream was removed by checking if this was the last
2960 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002961 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002962 if (remote_stream->GetAudioTracks().empty() &&
2963 remote_stream->GetVideoTracks().empty()) {
2964 remote_streams_->RemoveStream(remote_stream);
2965 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002966 }
2967 }
2968}
2969
Steve Antondcc3c022017-12-22 16:02:54 -08002970RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2971 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002972 const SessionDescriptionInterface& new_session,
2973 const SessionDescriptionInterface* old_local_description,
2974 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002975 RTC_DCHECK(IsUnifiedPlan());
2976
Steve Anton7464fca2018-01-19 11:10:37 -08002977 const cricket::ContentGroup* bundle_group = nullptr;
2978 if (new_session.GetType() == SdpType::kOffer) {
2979 auto bundle_group_or_error =
2980 GetEarlyBundleGroup(*new_session.description());
2981 if (!bundle_group_or_error.ok()) {
2982 return bundle_group_or_error.MoveError();
2983 }
2984 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002985 }
Steve Antondcc3c022017-12-22 16:02:54 -08002986
Steve Antondcc3c022017-12-22 16:02:54 -08002987 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002988 for (size_t i = 0; i < new_contents.size(); ++i) {
2989 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002990 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002991 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002992 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2993 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002994 const cricket::ContentInfo* old_local_content = nullptr;
2995 if (old_local_description &&
2996 i < old_local_description->description()->contents().size()) {
2997 old_local_content =
2998 &old_local_description->description()->contents()[i];
2999 }
3000 const cricket::ContentInfo* old_remote_content = nullptr;
3001 if (old_remote_description &&
3002 i < old_remote_description->description()->contents().size()) {
3003 old_remote_content =
3004 &old_remote_description->description()->contents()[i];
3005 }
Steve Antondcc3c022017-12-22 16:02:54 -08003006 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003007 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3008 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003009 if (!transceiver_or_error.ok()) {
3010 return transceiver_or_error.MoveError();
3011 }
3012 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003013 RTCError error =
3014 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3015 if (!error.ok()) {
3016 return error;
3017 }
3018 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003019 if (GetDataMid() && new_content.name != *GetDataMid()) {
3020 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003021 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3022 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003023 continue;
3024 }
3025 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3026 if (!error.ok()) {
3027 return error;
3028 }
Steve Antondcc3c022017-12-22 16:02:54 -08003029 } else {
3030 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3031 "Unknown section type.");
3032 }
3033 }
3034
3035 return RTCError::OK();
3036}
3037
3038RTCError PeerConnection::UpdateTransceiverChannel(
3039 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3040 transceiver,
3041 const cricket::ContentInfo& content,
3042 const cricket::ContentGroup* bundle_group) {
3043 RTC_DCHECK(IsUnifiedPlan());
3044 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003045 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003046 if (content.rejected) {
3047 if (channel) {
3048 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003049 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003050 }
3051 } else {
3052 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003053 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003054 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003055 } else {
Steve Anton69470252018-02-09 11:43:08 -08003056 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003057 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003058 }
3059 if (!channel) {
3060 LOG_AND_RETURN_ERROR(
3061 RTCErrorType::INTERNAL_ERROR,
3062 "Failed to create channel for mid=" + content.name);
3063 }
3064 transceiver->internal()->SetChannel(channel);
3065 }
3066 }
3067 return RTCError::OK();
3068}
3069
Steve Antonfa2260d2017-12-28 16:38:23 -08003070RTCError PeerConnection::UpdateDataChannel(
3071 cricket::ContentSource source,
3072 const cricket::ContentInfo& content,
3073 const cricket::ContentGroup* bundle_group) {
3074 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003075 // If data channels are disabled, ignore this media section. CreateAnswer
3076 // will take care of rejecting it.
3077 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003078 }
3079 if (content.rejected) {
3080 DestroyDataChannel();
3081 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003082 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003083 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003084 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3085 "Failed to create data channel.");
3086 }
3087 }
3088 if (source == cricket::CS_REMOTE) {
3089 const MediaContentDescription* data_desc = content.media_description();
3090 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3091 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3092 }
3093 }
3094 }
3095 return RTCError::OK();
3096}
3097
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003098// This method will extract any send encodings that were sent by the remote
3099// connection. This is currently only relevant for Simulcast scenario (where
3100// the number of layers may be communicated by the server).
3101static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3102 const MediaContentDescription& desc) {
3103 if (!desc.HasSimulcast()) {
3104 return {};
3105 }
3106 std::vector<RtpEncodingParameters> result;
3107 const SimulcastDescription& simulcast = desc.simulcast_description();
3108
3109 // This is a remote description, the parameters we are after should appear
3110 // as receive streams.
3111 for (const auto& alternatives : simulcast.receive_layers()) {
3112 RTC_DCHECK(!alternatives.empty());
3113 // There is currently no way to specify or choose from alternatives.
3114 // We will always use the first alternative, which is the most preferred.
3115 const SimulcastLayer& layer = alternatives[0];
3116 RtpEncodingParameters parameters;
3117 parameters.rid = layer.rid;
3118 parameters.active = !layer.is_paused;
3119 result.push_back(parameters);
3120 }
3121
3122 return result;
3123}
3124
3125static RTCError UpdateSimulcastLayerStatusInSender(
3126 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003127 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003128 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003129 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003130 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003131
3132 // The simulcast envelope cannot be changed, only the status of the streams.
3133 // So we will iterate over the send encodings rather than the layers.
3134 for (RtpEncodingParameters& encoding : parameters.encodings) {
3135 auto iter = std::find_if(layers.begin(), layers.end(),
3136 [&encoding](const SimulcastLayer& layer) {
3137 return layer.rid == encoding.rid;
3138 });
3139 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003140 if (iter == layers.end()) {
3141 disabled_layers.push_back(encoding.rid);
3142 continue;
3143 }
3144
3145 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003146 }
3147
Amit Hilbuch619b2942019-02-26 15:55:19 -08003148 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003149 if (result.ok()) {
3150 result = sender->DisableEncodingLayers(disabled_layers);
3151 }
3152
3153 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003154}
3155
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003156static bool SimulcastIsRejected(
3157 const ContentInfo* local_content,
3158 const MediaContentDescription& answer_media_desc) {
3159 bool simulcast_offered = local_content &&
3160 local_content->media_description() &&
3161 local_content->media_description()->HasSimulcast();
3162 bool simulcast_answered = answer_media_desc.HasSimulcast();
3163 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3164 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3165 return simulcast_offered && (!simulcast_answered || !rids_supported);
3166}
3167
Amit Hilbuch2297d332019-02-19 12:49:22 -08003168static RTCError DisableSimulcastInSender(
3169 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003170 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003171 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003172 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003173 return RTCError::OK();
3174 }
3175
Amit Hilbuch2297d332019-02-19 12:49:22 -08003176 std::vector<std::string> disabled_layers;
3177 std::transform(
3178 parameters.encodings.begin() + 1, parameters.encodings.end(),
3179 std::back_inserter(disabled_layers),
3180 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3181 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003182}
3183
Steve Antondcc3c022017-12-22 16:02:54 -08003184RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3185PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003186 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003187 size_t mline_index,
3188 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003189 const ContentInfo* old_local_content,
3190 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003191 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003192 // If this is an offer then the m= section might be recycled. If the m=
3193 // section is being recycled (defined as: rejected in the current local or
3194 // remote description and not rejected in new description), dissociate the
3195 // currently associated RtpTransceiver by setting its mid property to null,
3196 // and discard the mapping between the transceiver and its m= section index.
3197 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3198 old_remote_content)) {
3199 // We want to dissociate the transceiver that has the rejected mid.
3200 const std::string& old_mid =
3201 (old_local_content && old_local_content->rejected)
3202 ? old_local_content->name
3203 : old_remote_content->name;
3204 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003205 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003206 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3207 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003208 old_transceiver->internal()->set_mid(absl::nullopt);
3209 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003210 }
3211 }
3212 const MediaContentDescription* media_desc = content.media_description();
3213 auto transceiver = GetAssociatedTransceiver(content.name);
3214 if (source == cricket::CS_LOCAL) {
3215 // Find the RtpTransceiver that corresponds to this m= section, using the
3216 // mapping between transceivers and m= section indices established when
3217 // creating the offer.
3218 if (!transceiver) {
3219 transceiver = GetTransceiverByMLineIndex(mline_index);
3220 }
3221 if (!transceiver) {
3222 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3223 "Unknown transceiver");
3224 }
3225 } else {
3226 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3227 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3228 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003229 // When simulcast is requested, a transceiver cannot be associated because
3230 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003231 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003232 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3233 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003234 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3235 }
3236 // If no RtpTransceiver was found in the previous step, create one with a
3237 // recvonly direction.
3238 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003239 RTC_LOG(LS_INFO) << "Adding "
3240 << cricket::MediaTypeToString(media_desc->type())
3241 << " transceiver for MID=" << content.name
3242 << " at i=" << mline_index
3243 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003244 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003245 std::vector<RtpEncodingParameters> send_encodings =
3246 GetSendEncodingsFromRemoteDescription(*media_desc);
3247 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3248 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003249 std::string receiver_id;
3250 if (!media_desc->streams().empty()) {
3251 receiver_id = media_desc->streams()[0].id;
3252 } else {
3253 receiver_id = rtc::CreateRandomUuid();
3254 }
3255 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003256 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003257 transceiver->internal()->set_direction(
3258 RtpTransceiverDirection::kRecvOnly);
3259 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003260
3261 // Check if the offer indicated simulcast but the answer rejected it.
3262 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003263 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003264 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003265 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003266 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003267 if (!error.ok()) {
3268 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3269 return std::move(error);
3270 }
3271 }
Steve Antondcc3c022017-12-22 16:02:54 -08003272 }
3273 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003274 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003275 LOG_AND_RETURN_ERROR(
3276 RTCErrorType::INVALID_PARAMETER,
3277 "Transceiver type does not match media description type.");
3278 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003279 if (media_desc->HasSimulcast()) {
3280 std::vector<SimulcastLayer> layers =
3281 source == cricket::CS_LOCAL
3282 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3283 : media_desc->simulcast_description()
3284 .receive_layers()
3285 .GetAllLayers();
3286 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003287 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003288 if (!error.ok()) {
3289 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3290 return std::move(error);
3291 }
3292 }
Steve Antondcc3c022017-12-22 16:02:54 -08003293 // Associate the found or created RtpTransceiver with the m= section by
3294 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3295 // section, and establish a mapping between the transceiver and the index of
3296 // the m= section.
3297 transceiver->internal()->set_mid(content.name);
3298 transceiver->internal()->set_mline_index(mline_index);
3299 return std::move(transceiver);
3300}
3301
3302rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3303PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3304 RTC_DCHECK(IsUnifiedPlan());
3305 for (auto transceiver : transceivers_) {
3306 if (transceiver->mid() == mid) {
3307 return transceiver;
3308 }
3309 }
3310 return nullptr;
3311}
3312
3313rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3314PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3315 RTC_DCHECK(IsUnifiedPlan());
3316 for (auto transceiver : transceivers_) {
3317 if (transceiver->internal()->mline_index() == mline_index) {
3318 return transceiver;
3319 }
3320 }
3321 return nullptr;
3322}
3323
3324rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3325PeerConnection::FindAvailableTransceiverToReceive(
3326 cricket::MediaType media_type) const {
3327 RTC_DCHECK(IsUnifiedPlan());
3328 // From JSEP section 5.10 (Applying a Remote Description):
3329 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3330 // the same type that were added to the PeerConnection by addTrack and are not
3331 // associated with any m= section and are not stopped, find the first such
3332 // RtpTransceiver.
3333 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003334 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003335 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3336 !transceiver->stopped()) {
3337 return transceiver;
3338 }
3339 }
3340 return nullptr;
3341}
3342
Steve Antoned10bd92017-12-05 10:52:59 -08003343const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3344 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3345 transceiver,
3346 const SessionDescriptionInterface* sdesc) const {
3347 RTC_DCHECK(transceiver);
3348 RTC_DCHECK(sdesc);
3349 if (IsUnifiedPlan()) {
3350 if (!transceiver->internal()->mid()) {
3351 // This transceiver is not associated with a media section yet.
3352 return nullptr;
3353 }
3354 return sdesc->description()->GetContentByName(
3355 *transceiver->internal()->mid());
3356 } else {
3357 // Plan B only allows at most one audio and one video section, so use the
3358 // first media section of that type.
3359 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003360 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003361 }
3362}
3363
deadbeef46c73892016-11-16 19:42:04 -08003364PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003365 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003366 return configuration_;
3367}
3368
deadbeef293e9262017-01-11 12:28:30 -08003369bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3370 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003371 RTC_DCHECK_RUN_ON(signaling_thread());
3372 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003373 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003374 if (IsClosed()) {
3375 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3376 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3377 }
3378
Qingsi Wanga2d60672018-04-11 16:57:45 -07003379 // According to JSEP, after setLocalDescription, changing the candidate pool
3380 // size is not allowed, and changing the set of ICE servers will not result
3381 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003382 if (local_description() && configuration.ice_candidate_pool_size !=
3383 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003384 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3385 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003386 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003387 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003388
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003389 if (local_description() &&
3390 configuration.use_media_transport != configuration_.use_media_transport) {
3391 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3392 "SetLocalDescription.";
3393 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3394 }
3395
3396 if (remote_description() &&
3397 configuration.use_media_transport != configuration_.use_media_transport) {
3398 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3399 "SetRemoteDescription.";
3400 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3401 }
3402
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003403 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003404 configuration.use_media_transport_for_data_channels !=
3405 configuration_.use_media_transport_for_data_channels) {
3406 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3407 "after calling SetLocalDescription.";
3408 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3409 }
3410
3411 if (remote_description() &&
3412 configuration.use_media_transport_for_data_channels !=
3413 configuration_.use_media_transport_for_data_channels) {
3414 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3415 "after calling SetRemoteDescription.";
3416 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3417 }
3418
3419 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003420 configuration.crypto_options != configuration_.crypto_options) {
3421 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3422 "SetLocalDescription.";
3423 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3424 }
3425
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003426 if (local_description() && configuration.use_datagram_transport !=
3427 configuration_.use_datagram_transport) {
3428 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3429 "after calling SetLocalDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
3433 if (remote_description() && configuration.use_datagram_transport !=
3434 configuration_.use_datagram_transport) {
3435 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3436 "after calling SetRemoteDescription.";
3437 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3438 }
3439
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003440 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003441 configuration.use_media_transport ||
3442 configuration.use_datagram_transport) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003443 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3444 << "Media transport requires MaxBundle policy.";
3445 }
3446
deadbeef293e9262017-01-11 12:28:30 -08003447 // The simplest (and most future-compatible) way to tell if the config was
3448 // modified in an invalid way is to copy each property we do support
3449 // modifying, then use operator==. There are far more properties we don't
3450 // support modifying than those we do, and more could be added.
3451 RTCConfiguration modified_config = configuration_;
3452 modified_config.servers = configuration.servers;
3453 modified_config.type = configuration.type;
3454 modified_config.ice_candidate_pool_size =
3455 configuration.ice_candidate_pool_size;
3456 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003457 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003458 modified_config.ice_check_interval_strong_connectivity =
3459 configuration.ice_check_interval_strong_connectivity;
3460 modified_config.ice_check_interval_weak_connectivity =
3461 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003462 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3463 modified_config.ice_unwritable_min_checks =
3464 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003465 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003466 modified_config.stun_candidate_keepalive_interval =
3467 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003468 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003469 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003470 modified_config.active_reset_srtp_params =
3471 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003472 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003473 modified_config.use_media_transport_for_data_channels =
3474 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003475 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003476 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003477 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3478 }
3479
Steve Anton038834f2017-07-14 15:59:59 -07003480 // Validate the modified configuration.
3481 RTCError validate_error = ValidateConfiguration(modified_config);
3482 if (!validate_error.ok()) {
3483 return SafeSetError(std::move(validate_error), error);
3484 }
3485
deadbeef293e9262017-01-11 12:28:30 -08003486 // Note that this isn't possible through chromium, since it's an unsigned
3487 // short in WebIDL.
3488 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003489 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003490 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3491 }
3492
3493 // Parse ICE servers before hopping to network thread.
3494 cricket::ServerAddresses stun_servers;
3495 std::vector<cricket::RelayServerConfig> turn_servers;
3496 RTCErrorType parse_error =
3497 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3498 if (parse_error != RTCErrorType::NONE) {
3499 return SafeSetError(parse_error, error);
3500 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003501 // Note if STUN or TURN servers were supplied.
3502 if (!stun_servers.empty()) {
3503 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3504 }
3505 if (!turn_servers.empty()) {
3506 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3507 }
deadbeef293e9262017-01-11 12:28:30 -08003508
3509 // In theory this shouldn't fail.
3510 if (!network_thread()->Invoke<bool>(
3511 RTC_FROM_HERE,
3512 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3513 stun_servers, turn_servers, modified_config.type,
3514 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003515 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003516 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003517 modified_config.stun_candidate_keepalive_interval,
3518 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003519 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003520 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3521 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003522
deadbeefd1a38b52016-12-10 13:15:33 -08003523 // As described in JSEP, calling setConfiguration with new ICE servers or
3524 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3525 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003526 if (modified_config.servers != configuration_.servers ||
3527 modified_config.type != configuration_.type ||
3528 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003529 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003530 }
skvladd1f5fda2017-02-03 16:54:05 -08003531
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003532 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003533 transport_controller_->SetMediaTransportSettings(
3534 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003535 modified_config.use_media_transport_for_data_channels,
3536 modified_config.use_datagram_transport);
skvladd1f5fda2017-02-03 16:54:05 -08003537
Zhi Huangb57e1692018-06-12 11:41:11 -07003538 if (configuration_.active_reset_srtp_params !=
3539 modified_config.active_reset_srtp_params) {
3540 transport_controller_->SetActiveResetSrtpParams(
3541 modified_config.active_reset_srtp_params);
3542 }
3543
deadbeef293e9262017-01-11 12:28:30 -08003544 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003545 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003546 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003547}
3548
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003549bool PeerConnection::AddIceCandidate(
3550 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003551 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003552 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003553 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003554 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003555 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003556 return false;
3557 }
Steve Antond25da372017-11-06 14:50:29 -08003558
3559 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003560 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003561 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003562 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003563 return false;
3564 }
3565
3566 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003567 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003568 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003569 return false;
3570 }
3571
3572 bool valid = false;
3573 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3574 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003575 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003576 return false;
3577 }
3578
3579 // Add this candidate to the remote session description.
3580 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003581 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003582 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003583 return false;
3584 }
3585
3586 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003587 bool result = UseCandidate(ice_candidate);
3588 if (result) {
3589 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003590 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3591 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3592 }
3593 if (ice_candidate->candidate().address().IsPrivateIP()) {
3594 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3595 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003596 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3597 } else {
3598 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3599 }
3600 return result;
Steve Antond25da372017-11-06 14:50:29 -08003601 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003602 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003603 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003604 return true;
3605 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003606}
3607
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003608bool PeerConnection::RemoveIceCandidates(
3609 const std::vector<cricket::Candidate>& candidates) {
3610 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003611 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003612 if (IsClosed()) {
3613 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3614 return false;
3615 }
3616
Steve Antond25da372017-11-06 14:50:29 -08003617 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003618 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3619 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003620 return false;
3621 }
3622
3623 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003624 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003625 return false;
3626 }
3627
3628 size_t number_removed =
3629 mutable_remote_description()->RemoveCandidates(candidates);
3630 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003631 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003632 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003633 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003634 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003635 }
3636
3637 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003638 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3639 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003640 RTC_LOG(LS_ERROR)
3641 << "RemoveIceCandidates: Error when removing remote candidates: "
3642 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003643 }
3644 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003645}
3646
Niels Möller0c4f7be2018-05-07 14:01:37 +02003647RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003648 if (!worker_thread()->IsCurrent()) {
3649 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003650 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003651 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003652 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003653
Niels Möller0c4f7be2018-05-07 14:01:37 +02003654 const bool has_min = bitrate.min_bitrate_bps.has_value();
3655 const bool has_start = bitrate.start_bitrate_bps.has_value();
3656 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003657 if (has_min && *bitrate.min_bitrate_bps < 0) {
3658 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3659 "min_bitrate_bps <= 0");
3660 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003661 if (has_start) {
3662 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003663 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003664 "start_bitrate_bps < min_bitrate_bps");
3665 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3667 "curent_bitrate_bps < 0");
3668 }
3669 }
3670 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003671 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003672 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003673 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003674 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3676 "max_bitrate_bps < min_bitrate_bps");
3677 } else if (*bitrate.max_bitrate_bps < 0) {
3678 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3679 "max_bitrate_bps < 0");
3680 }
3681 }
3682
zstein4b979802017-06-02 14:37:37 -07003683 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003684 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003685
3686 return RTCError::OK();
3687}
3688
Alex Narest78609d52017-10-20 10:37:47 +02003689void PeerConnection::SetBitrateAllocationStrategy(
3690 std::unique_ptr<rtc::BitrateAllocationStrategy>
3691 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003692 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003693 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3694 // move-capture values in lambdas.
3695 struct Task {
3696 PeerConnection* const pc;
3697 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3698 void operator()() {
3699 RTC_DCHECK_RUN_ON(pc->worker_thread());
3700 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3701 }
3702 };
3703 worker_thread()->Invoke<void>(
3704 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003705 return;
3706 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003707 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003708 RTC_DCHECK(call_.get());
3709 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3710}
3711
henrika5f6bf242017-11-01 11:06:56 +01003712void PeerConnection::SetAudioPlayout(bool playout) {
3713 if (!worker_thread()->IsCurrent()) {
3714 worker_thread()->Invoke<void>(
3715 RTC_FROM_HERE,
3716 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3717 return;
3718 }
3719 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003720 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003721 audio_state->SetPlayout(playout);
3722}
3723
3724void PeerConnection::SetAudioRecording(bool recording) {
3725 if (!worker_thread()->IsCurrent()) {
3726 worker_thread()->Invoke<void>(
3727 RTC_FROM_HERE,
3728 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3729 return;
3730 }
3731 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003732 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003733 audio_state->SetRecording(recording);
3734}
3735
Steve Anton8c0f7a72017-10-03 10:03:10 -07003736std::unique_ptr<rtc::SSLCertificate>
3737PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003738 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3739 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003740 return nullptr;
3741 }
Steve Antonf25303e2018-10-16 15:23:31 -07003742 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003743}
3744
Zhi Huang70b820f2018-01-27 14:16:15 -08003745std::unique_ptr<rtc::SSLCertChain>
3746PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003747 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003748 auto audio_transceiver = GetFirstAudioTransceiver();
3749 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003750 return nullptr;
3751 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003752 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003753 audio_transceiver->internal()->channel()->transport_name());
3754}
3755
3756rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3757PeerConnection::GetFirstAudioTransceiver() const {
3758 for (auto transceiver : transceivers_) {
3759 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3760 return transceiver;
3761 }
3762 }
3763 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003764}
3765
Bjorn Tereliusde939432017-11-20 17:38:14 +01003766bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3767 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003768 // TODO(eladalon): In C++14, this can be done with a lambda.
3769 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003770 bool operator()() {
3771 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3772 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003773 PeerConnection* const pc;
3774 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003775 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003776 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003777 return worker_thread()->Invoke<bool>(
3778 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003779}
3780
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003781bool PeerConnection::StartRtcEventLog(
3782 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003783 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3784 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3785 output_period_ms = 5000;
3786 }
3787 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003788}
3789
ivoc14d5dbe2016-07-04 07:06:55 -07003790void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003791 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003792 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3793}
3794
Harald Alvestrandad88c882018-11-28 16:47:46 +01003795rtc::scoped_refptr<DtlsTransportInterface>
3796PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003797 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003798 return transport_controller_->LookupDtlsTransportByMid(mid);
3799}
3800
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003801rtc::scoped_refptr<DtlsTransport>
3802PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003803 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003804 return transport_controller_->LookupDtlsTransportByMid(mid);
3805}
3806
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003807rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3808 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003809 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003810 return sctp_transport_;
3811}
3812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003813const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003814 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003815 return pending_local_description_ ? pending_local_description_.get()
3816 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003817}
3818
3819const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003820 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003821 return pending_remote_description_ ? pending_remote_description_.get()
3822 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003823}
3824
deadbeeffe4a8a42016-12-20 17:56:17 -08003825const SessionDescriptionInterface* PeerConnection::current_local_description()
3826 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003827 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003828 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003829}
3830
3831const SessionDescriptionInterface* PeerConnection::current_remote_description()
3832 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003833 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003834 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003835}
3836
3837const SessionDescriptionInterface* PeerConnection::pending_local_description()
3838 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003839 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003840 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003841}
3842
3843const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3844 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003845 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003846 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003847}
3848
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003849void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003850 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003851 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003852 // Update stats here so that we have the most recent stats for tracks and
3853 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003854 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003855
Steve Anton75737c02017-11-06 10:37:17 -08003856 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003857 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003858
Mirko Bonadei739baf02019-01-27 17:29:42 +01003859 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003860 transceiver->Stop();
3861 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003862
3863 // Ensure that all asynchronous stats requests are completed before destroying
3864 // the transport controller below.
3865 if (stats_collector_) {
3866 stats_collector_->WaitForPendingRequest();
3867 }
3868
3869 // Don't destroy BaseChannels until after stats has been cleaned up so that
3870 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003871 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003872
Qingsi Wang93a84392018-01-30 17:13:09 -08003873 // The event log is used in the transport controller, which must be outlived
3874 // by the former. CreateOffer by the peer connection is implemented
3875 // asynchronously and if the peer connection is closed without resetting the
3876 // WebRTC session description factory, the session description factory would
3877 // call the transport controller.
3878 webrtc_session_desc_factory_.reset();
3879 transport_controller_.reset();
3880
deadbeef42a42632017-03-10 15:18:00 -08003881 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003882 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3883 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003884
Steve Anton978b8762017-09-29 12:15:02 -07003885 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003886 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003887 call_.reset();
3888 // The event log must outlive call (and any other object that uses it).
3889 event_log_.reset();
3890 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003891 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003892 // The .h file says that observer can be discarded after close() returns.
3893 // Make sure this is true.
3894 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003895}
3896
Steve Antonad182762018-09-05 20:22:40 +00003897void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003898 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003899 switch (msg->message_id) {
3900 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3901 SetSessionDescriptionMsg* param =
3902 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3903 param->observer->OnSuccess();
3904 delete param;
3905 break;
3906 }
3907 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3908 SetSessionDescriptionMsg* param =
3909 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3910 param->observer->OnFailure(std::move(param->error));
3911 delete param;
3912 break;
3913 }
3914 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3915 CreateSessionDescriptionMsg* param =
3916 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3917 param->observer->OnFailure(std::move(param->error));
3918 delete param;
3919 break;
3920 }
3921 case MSG_GETSTATS: {
3922 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3923 StatsReports reports;
3924 stats_->GetStats(param->track, &reports);
3925 param->observer->OnComplete(reports);
3926 delete param;
3927 break;
3928 }
3929 case MSG_FREE_DATACHANNELS: {
3930 sctp_data_channels_to_free_.clear();
3931 break;
3932 }
3933 case MSG_REPORT_USAGE_PATTERN: {
3934 ReportUsagePattern();
3935 break;
3936 }
3937 default:
3938 RTC_NOTREACHED() << "Not implemented";
3939 break;
3940 }
3941}
3942
Steve Antonafb0bb72018-02-20 11:35:37 -08003943cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3944 RTC_DCHECK(!IsUnifiedPlan());
3945 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3946 GetAudioTransceiver()->internal()->channel());
3947 if (voice_channel) {
3948 return voice_channel->media_channel();
3949 } else {
3950 return nullptr;
3951 }
3952}
3953
3954cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3955 RTC_DCHECK(!IsUnifiedPlan());
3956 auto* video_channel = static_cast<cricket::VideoChannel*>(
3957 GetVideoTransceiver()->internal()->channel());
3958 if (video_channel) {
3959 return video_channel->media_channel();
3960 } else {
3961 return nullptr;
3962 }
3963}
3964
Steve Anton4171afb2017-11-20 10:20:22 -08003965void PeerConnection::CreateAudioReceiver(
3966 MediaStreamInterface* stream,
3967 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003968 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3969 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003970 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3971 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003972 auto* audio_receiver = new AudioRtpReceiver(
3973 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003974 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003975 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3976 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3977 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003978 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003979 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003980 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003981}
3982
Steve Anton4171afb2017-11-20 10:20:22 -08003983void PeerConnection::CreateVideoReceiver(
3984 MediaStreamInterface* stream,
3985 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003986 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3987 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003988 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3989 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003990 auto* video_receiver = new VideoRtpReceiver(
3991 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003992 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003993 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3994 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3995 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003996 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003997 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003998 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003999}
4000
deadbeef70ab1a12015-09-28 16:53:55 -07004001// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4002// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004003rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004004 const RtpSenderInfo& remote_sender_info) {
4005 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4006 if (!receiver) {
4007 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4008 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004009 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004010 }
Steve Anton4171afb2017-11-20 10:20:22 -08004011 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4012 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4013 } else {
4014 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4015 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004016 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004017}
4018
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004019void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4020 MediaStreamInterface* stream) {
4021 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004022 RTC_DCHECK(track);
4023 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004024 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004025 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004026 // We already have a sender for this track, so just change the stream_id
4027 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004028 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004029 return;
4030 }
4031
4032 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004033 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004034 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004035 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004036 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004037 // If the sender has already been configured in SDP, we call SetSsrc,
4038 // which will connect the sender to the underlying transport. This can
4039 // occur if a local session description that contains the ID of the sender
4040 // is set before AddStream is called. It can also occur if the local
4041 // session description is not changed and RemoveStream is called, and
4042 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004043 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004044 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004045 if (sender_info) {
4046 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004047 }
4048}
4049
4050// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4051// indefinitely, when we have unified plan SDP.
4052void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4053 MediaStreamInterface* stream) {
4054 RTC_DCHECK(!IsClosed());
4055 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004056 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004057 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4058 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004059 return;
4060 }
Steve Anton4171afb2017-11-20 10:20:22 -08004061 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004062}
4063
4064void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4065 MediaStreamInterface* stream) {
4066 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004067 RTC_DCHECK(track);
4068 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004069 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004070 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004071 // We already have a sender for this track, so just change the stream_id
4072 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004073 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004074 return;
4075 }
4076
4077 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004078 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004079 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004080 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004081 GetVideoTransceiver()->internal()->AddSender(new_sender);
4082 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004083 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004084 if (sender_info) {
4085 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004086 }
4087}
4088
4089void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4090 MediaStreamInterface* stream) {
4091 RTC_DCHECK(!IsClosed());
4092 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004093 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004094 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4095 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004096 return;
4097 }
Steve Anton4171afb2017-11-20 10:20:22 -08004098 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004099}
4100
Steve Antonba818672017-11-06 10:21:57 -08004101void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004102 if (ice_connection_state_ == new_state) {
4103 return;
4104 }
4105
deadbeefcbecd352015-09-23 11:50:27 -07004106 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004107 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004108 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004109 return;
4110 }
Steve Antonba818672017-11-06 10:21:57 -08004111
Mirko Bonadei675513b2017-11-09 11:09:25 +01004112 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4113 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004114 RTC_DCHECK(ice_connection_state_ !=
4115 PeerConnectionInterface::kIceConnectionClosed);
4116
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004117 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004118 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004119}
4120
Alex Loiko9289eda2018-11-23 16:18:59 +00004121void PeerConnection::SetStandardizedIceConnectionState(
4122 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004123 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004124 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004125 }
4126
4127 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004128 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004129 }
4130
4131 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4132 << standardized_ice_connection_state_ << " => " << new_state;
4133
Alex Loiko9289eda2018-11-23 16:18:59 +00004134 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004135 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004136}
4137
Jonas Olsson635474e2018-10-18 15:58:17 +02004138void PeerConnection::SetConnectionState(
4139 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004140 if (connection_state_ == new_state)
4141 return;
4142 if (IsClosed())
4143 return;
4144 connection_state_ = new_state;
4145 Observer()->OnConnectionChange(new_state);
4146}
4147
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004148void PeerConnection::OnIceGatheringChange(
4149 PeerConnectionInterface::IceGatheringState new_state) {
4150 if (IsClosed()) {
4151 return;
4152 }
4153 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004154 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004155}
4156
jbauch81bf7b02017-03-25 08:31:12 -07004157void PeerConnection::OnIceCandidate(
4158 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004159 if (IsClosed()) {
4160 return;
4161 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004162 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004163 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4164 candidate->candidate().address().IsPrivateIP()) {
4165 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4166 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004167 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4168 candidate->candidate().address().IsUnresolvedIP()) {
4169 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4170 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004171 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004172}
4173
Eldar Relloda13ea22019-06-01 12:23:43 +03004174void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4175 const std::string& url,
4176 int error_code,
4177 const std::string& error_text) {
4178 if (IsClosed()) {
4179 return;
4180 }
4181 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4182}
4183
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004184void PeerConnection::OnIceCandidatesRemoved(
4185 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004186 if (IsClosed()) {
4187 return;
4188 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004189 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004190}
4191
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004192void PeerConnection::ChangeSignalingState(
4193 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004194 if (signaling_state_ == signaling_state) {
4195 return;
4196 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004197 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4198 << GetSignalingStateString(signaling_state_)
4199 << " New state: "
4200 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004201 signaling_state_ = signaling_state;
4202 if (signaling_state == kClosed) {
4203 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004204 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004205 standardized_ice_connection_state_ =
4206 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004207 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4208 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004209 if (ice_gathering_state_ != kIceGatheringComplete) {
4210 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004211 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004212 }
4213 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004214 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004215}
4216
deadbeefeb459812015-12-15 19:24:43 -08004217void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4218 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004219 if (IsClosed()) {
4220 return;
4221 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004222 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004223 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004224}
4225
deadbeefeb459812015-12-15 19:24:43 -08004226void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4227 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004228 if (IsClosed()) {
4229 return;
4230 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004231 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004232 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004233}
4234
4235void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4236 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004237 if (IsClosed()) {
4238 return;
4239 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004240 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004241 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004242}
4243
4244void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4245 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004246 if (IsClosed()) {
4247 return;
4248 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004249 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004250 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004251}
4252
Henrik Boström31638672017-11-23 17:48:32 +01004253void PeerConnection::PostSetSessionDescriptionSuccess(
4254 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004255 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4256 signaling_thread()->Post(RTC_FROM_HERE, this,
4257 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004258}
4259
deadbeefab9b2d12015-10-14 11:33:11 -07004260void PeerConnection::PostSetSessionDescriptionFailure(
4261 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004262 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004263 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004264 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4265 msg->error = std::move(error);
4266 signaling_thread()->Post(RTC_FROM_HERE, this,
4267 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004268}
4269
4270void PeerConnection::PostCreateSessionDescriptionFailure(
4271 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004272 RTCError error) {
4273 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004274 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4275 msg->error = std::move(error);
4276 signaling_thread()->Post(RTC_FROM_HERE, this,
4277 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004278}
4279
zhihuang1c378ed2017-08-17 14:10:50 -07004280void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004281 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004282 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004283 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004284
Steve Antondcc3c022017-12-22 16:02:54 -08004285 if (IsUnifiedPlan()) {
4286 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4287 } else {
4288 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4289 }
4290
Steve Antonfa2260d2017-12-28 16:38:23 -08004291 // Intentionally unset the data channel type for RTP data channel with the
4292 // second condition. Otherwise the RTP data channels would be successfully
4293 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4294 // when building with chromium. We want to leave RTP data channels broken, so
4295 // people won't try to use them.
4296 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4297 session_options->data_channel_type = data_channel_type();
4298 }
4299
Steve Antondcc3c022017-12-22 16:02:54 -08004300 // Apply ICE restart flag and renomination flag.
4301 for (auto& options : session_options->media_description_options) {
4302 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4303 options.transport_options.enable_ice_renomination =
4304 configuration_.enable_ice_renomination;
4305 }
4306
4307 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004308 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004309 session_options->pooled_ice_credentials =
4310 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4311 RTC_FROM_HERE,
4312 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4313 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004314 session_options->offer_extmap_allow_mixed =
4315 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004316
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004317 if (configuration_.use_media_transport ||
4318 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004319 session_options->media_transport_settings =
4320 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4321 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004322
4323 // If datagram transport is in use, add opaque transport parameters.
4324 if (configuration_.use_datagram_transport) {
4325 for (auto& options : session_options->media_description_options) {
4326 options.transport_options.opaque_parameters =
4327 transport_controller_->GetTransportParameters(options.mid);
4328 }
4329 }
4330
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004331 // Allow fallback for using obsolete SCTP syntax.
4332 // Note that the default in |session_options| is true, while
4333 // the default in |options| is false.
4334 session_options->use_obsolete_sctp_sdp =
4335 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004336}
4337
4338void PeerConnection::GetOptionsForPlanBOffer(
4339 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4340 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004341 // Figure out transceiver directional preferences.
4342 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4343 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4344
4345 // By default, generate sendrecv/recvonly m= sections.
4346 bool recv_audio = true;
4347 bool recv_video = true;
4348
4349 // By default, only offer a new m= section if we have media to send with it.
4350 bool offer_new_audio_description = send_audio;
4351 bool offer_new_video_description = send_video;
4352 bool offer_new_data_description = HasDataChannels();
4353
4354 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004355 if (offer_answer_options.offer_to_receive_audio !=
4356 RTCOfferAnswerOptions::kUndefined) {
4357 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004358 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004359 offer_new_audio_description ||
4360 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004361 }
Steve Antondcc3c022017-12-22 16:02:54 -08004362 if (offer_answer_options.offer_to_receive_video !=
4363 RTCOfferAnswerOptions::kUndefined) {
4364 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004365 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004366 offer_new_video_description ||
4367 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004368 }
4369
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004370 absl::optional<size_t> audio_index;
4371 absl::optional<size_t> video_index;
4372 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004373 // If a current description exists, generate m= sections in the same order,
4374 // using the first audio/video/data section that appears and rejecting
4375 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004376 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004377 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004378 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004379 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4380 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4381 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004382 }
4383
zhihuang1c378ed2017-08-17 14:10:50 -07004384 // Add audio/video/data m= sections to the end if needed.
4385 if (!audio_index && offer_new_audio_description) {
4386 session_options->media_description_options.push_back(
4387 cricket::MediaDescriptionOptions(
4388 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004389 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4390 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004391 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004392 }
zhihuang1c378ed2017-08-17 14:10:50 -07004393 if (!video_index && offer_new_video_description) {
4394 session_options->media_description_options.push_back(
4395 cricket::MediaDescriptionOptions(
4396 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004397 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4398 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004399 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004400 }
zhihuang1c378ed2017-08-17 14:10:50 -07004401 if (!data_index && offer_new_data_description) {
4402 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004403 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004404 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004405 }
4406
4407 cricket::MediaDescriptionOptions* audio_media_description_options =
4408 !audio_index ? nullptr
4409 : &session_options->media_description_options[*audio_index];
4410 cricket::MediaDescriptionOptions* video_media_description_options =
4411 !video_index ? nullptr
4412 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004413
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004414 AddPlanBRtpSenderOptions(GetSendersInternal(),
4415 audio_media_description_options,
4416 video_media_description_options,
4417 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004418}
4419
Steve Antondcc3c022017-12-22 16:02:54 -08004420static cricket::MediaDescriptionOptions
4421GetMediaDescriptionOptionsForTransceiver(
4422 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4423 transceiver,
4424 const std::string& mid) {
4425 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004426 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004427 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004428 media_description_options.codec_preferences =
4429 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004430 // This behavior is specified in JSEP. The gist is that:
4431 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4432 // sendrecv.
4433 // 2. If the MSID is included, then it must be included in any subsequent
4434 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004435 if (transceiver->stopped() ||
4436 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4437 !transceiver->internal()->has_ever_been_used_to_send())) {
4438 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004439 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004440
4441 cricket::SenderOptions sender_options;
4442 sender_options.track_id = transceiver->sender()->id();
4443 sender_options.stream_ids = transceiver->sender()->stream_ids();
4444
4445 // The following sets up RIDs and Simulcast.
4446 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004447 RtpParameters send_parameters =
4448 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004449 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4450 send_parameters.encodings.end(),
4451 [](const RtpEncodingParameters& encoding) {
4452 return !encoding.rid.empty();
4453 });
4454
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004455 std::vector<RidDescription> send_rids;
4456 SimulcastLayerList send_layers;
4457 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4458 if (encoding.rid.empty()) {
4459 continue;
4460 }
4461 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4462 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4463 }
4464
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004465 if (has_rids) {
4466 sender_options.rids = send_rids;
4467 }
4468
4469 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004470 // When RIDs are configured, we must set num_sim_layers to 0 to.
4471 // Otherwise, num_sim_layers must be 1 because either there is no
4472 // simulcast, or simulcast is acheived by munging the SDP.
4473 sender_options.num_sim_layers = has_rids ? 0 : 1;
4474 media_description_options.sender_options.push_back(sender_options);
4475
Steve Antondcc3c022017-12-22 16:02:54 -08004476 return media_description_options;
4477}
4478
Steve Anton5c72e712018-12-10 14:25:30 -08004479// Returns the ContentInfo at mline index |i|, or null if none exists.
4480static const ContentInfo* GetContentByIndex(
4481 const SessionDescriptionInterface* sdesc,
4482 size_t i) {
4483 if (!sdesc) {
4484 return nullptr;
4485 }
4486 const ContentInfos& contents = sdesc->description()->contents();
4487 return (i < contents.size() ? &contents[i] : nullptr);
4488}
4489
Steve Antondcc3c022017-12-22 16:02:54 -08004490void PeerConnection::GetOptionsForUnifiedPlanOffer(
4491 const RTCOfferAnswerOptions& offer_answer_options,
4492 cricket::MediaSessionOptions* session_options) {
4493 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4494 // Offers) and 5.2.2 (Subsequent Offers).
4495 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004496 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004497 const ContentInfos& local_contents =
4498 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004499 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004500 const ContentInfos& remote_contents =
4501 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004502 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004503 // The mline indices that can be recycled. New transceivers should reuse these
4504 // slots first.
4505 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004506 // First, go through each media section that exists in either the local or
4507 // remote description and generate a media section in this offer for the
4508 // associated transceiver. If a media section can be recycled, generate a
4509 // default, rejected media section here that can be later overwritten.
4510 for (size_t i = 0;
4511 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4512 // Either |local_content| or |remote_content| is non-null.
4513 const ContentInfo* local_content =
4514 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004515 const ContentInfo* current_local_content =
4516 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004517 const ContentInfo* remote_content =
4518 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004519 const ContentInfo* current_remote_content =
4520 GetContentByIndex(current_remote_description(), i);
4521 bool had_been_rejected =
4522 (current_local_content && current_local_content->rejected) ||
4523 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004524 const std::string& mid =
4525 (local_content ? local_content->name : remote_content->name);
4526 cricket::MediaType media_type =
4527 (local_content ? local_content->media_description()->type()
4528 : remote_content->media_description()->type());
4529 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4530 media_type == cricket::MEDIA_TYPE_VIDEO) {
4531 auto transceiver = GetAssociatedTransceiver(mid);
4532 RTC_CHECK(transceiver);
4533 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004534 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004535 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004536 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004537 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4538 RtpTransceiverDirection::kInactive,
4539 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004540 recycleable_mline_indices.push(i);
4541 } else {
4542 session_options->media_description_options.push_back(
4543 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4544 // CreateOffer shouldn't really cause any state changes in
4545 // PeerConnection, but we need a way to match new transceivers to new
4546 // media sections in SetLocalDescription and JSEP specifies this is done
4547 // by recording the index of the media section generated for the
4548 // transceiver in the offer.
4549 transceiver->internal()->set_mline_index(i);
4550 }
4551 } else {
4552 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004553 RTC_CHECK(GetDataMid());
4554 if (had_been_rejected || mid != *GetDataMid()) {
4555 session_options->media_description_options.push_back(
4556 GetMediaDescriptionOptionsForRejectedData(mid));
4557 } else {
4558 session_options->media_description_options.push_back(
4559 GetMediaDescriptionOptionsForActiveData(mid));
4560 }
Steve Antondcc3c022017-12-22 16:02:54 -08004561 }
4562 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004563
Steve Antondcc3c022017-12-22 16:02:54 -08004564 // Next, look for transceivers that are newly added (that is, are not stopped
4565 // and not associated). Reuse media sections marked as recyclable first,
4566 // otherwise append to the end of the offer. New media sections should be
4567 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004568 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004569 if (transceiver->mid() || transceiver->stopped()) {
4570 continue;
4571 }
4572 size_t mline_index;
4573 if (!recycleable_mline_indices.empty()) {
4574 mline_index = recycleable_mline_indices.front();
4575 recycleable_mline_indices.pop();
4576 session_options->media_description_options[mline_index] =
4577 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004578 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004579 } else {
4580 mline_index = session_options->media_description_options.size();
4581 session_options->media_description_options.push_back(
4582 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004583 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004584 }
4585 // See comment above for why CreateOffer changes the transceiver's state.
4586 transceiver->internal()->set_mline_index(mline_index);
4587 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004588 // Lastly, add a m-section if we have local data channels and an m section
4589 // does not already exist.
4590 if (!GetDataMid() && HasDataChannels()) {
4591 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004592 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004593 }
Steve Antondcc3c022017-12-22 16:02:54 -08004594}
4595
4596void PeerConnection::GetOptionsForAnswer(
4597 const RTCOfferAnswerOptions& offer_answer_options,
4598 cricket::MediaSessionOptions* session_options) {
4599 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4600
4601 if (IsUnifiedPlan()) {
4602 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4603 } else {
4604 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4605 }
4606
Steve Antonfa2260d2017-12-28 16:38:23 -08004607 // Intentionally unset the data channel type for RTP data channel. Otherwise
4608 // the RTP data channels would be successfully negotiated by default and the
4609 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4610 // We want to leave RTP data channels broken, so people won't try to use them.
4611 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4612 session_options->data_channel_type = data_channel_type();
4613 }
4614
Steve Antondcc3c022017-12-22 16:02:54 -08004615 // Apply ICE renomination flag.
4616 for (auto& options : session_options->media_description_options) {
4617 options.transport_options.enable_ice_renomination =
4618 configuration_.enable_ice_renomination;
4619 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004620
4621 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004622 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004623 session_options->pooled_ice_credentials =
4624 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4625 RTC_FROM_HERE,
4626 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4627 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004628
4629 // If datagram transport is in use, add opaque transport parameters.
4630 if (configuration_.use_datagram_transport) {
4631 for (auto& options : session_options->media_description_options) {
4632 options.transport_options.opaque_parameters =
4633 transport_controller_->GetTransportParameters(options.mid);
4634 }
4635 }
deadbeefab9b2d12015-10-14 11:33:11 -07004636}
4637
Steve Antondcc3c022017-12-22 16:02:54 -08004638void PeerConnection::GetOptionsForPlanBAnswer(
4639 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004640 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004641 // Figure out transceiver directional preferences.
4642 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4643 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4644
4645 // By default, generate sendrecv/recvonly m= sections. The direction is also
4646 // restricted by the direction in the offer.
4647 bool recv_audio = true;
4648 bool recv_video = true;
4649
4650 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004651 if (offer_answer_options.offer_to_receive_audio !=
4652 RTCOfferAnswerOptions::kUndefined) {
4653 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004654 }
Steve Antondcc3c022017-12-22 16:02:54 -08004655 if (offer_answer_options.offer_to_receive_video !=
4656 RTCOfferAnswerOptions::kUndefined) {
4657 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004658 }
4659
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004660 absl::optional<size_t> audio_index;
4661 absl::optional<size_t> video_index;
4662 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004663
4664 // Generate m= sections that match those in the offer.
4665 // Note that mediasession.cc will handle intersection our preferred
4666 // direction with the offered direction.
4667 GenerateMediaDescriptionOptions(
4668 remote_description(),
4669 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4670 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4671 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004672
4673 cricket::MediaDescriptionOptions* audio_media_description_options =
4674 !audio_index ? nullptr
4675 : &session_options->media_description_options[*audio_index];
4676 cricket::MediaDescriptionOptions* video_media_description_options =
4677 !video_index ? nullptr
4678 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004679
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004680 AddPlanBRtpSenderOptions(GetSendersInternal(),
4681 audio_media_description_options,
4682 video_media_description_options,
4683 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004684}
zhihuangaf388472016-11-02 16:49:48 -07004685
Steve Antondcc3c022017-12-22 16:02:54 -08004686void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4687 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4688 cricket::MediaSessionOptions* session_options) {
4689 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4690 // Answers) and 5.3.2 (Subsequent Answers).
4691 RTC_DCHECK(remote_description());
4692 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4693 for (const ContentInfo& content :
4694 remote_description()->description()->contents()) {
4695 cricket::MediaType media_type = content.media_description()->type();
4696 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4697 media_type == cricket::MEDIA_TYPE_VIDEO) {
4698 auto transceiver = GetAssociatedTransceiver(content.name);
4699 RTC_CHECK(transceiver);
4700 session_options->media_description_options.push_back(
4701 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4702 } else {
4703 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004704 // Reject all data sections if data channels are disabled.
4705 // Reject a data section if it has already been rejected.
4706 // Reject all data sections except for the first one.
4707 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4708 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004709 session_options->media_description_options.push_back(
4710 GetMediaDescriptionOptionsForRejectedData(content.name));
4711 } else {
4712 session_options->media_description_options.push_back(
4713 GetMediaDescriptionOptionsForActiveData(content.name));
4714 }
Steve Antondcc3c022017-12-22 16:02:54 -08004715 }
4716 }
htaa2a49d92016-03-04 02:51:39 -08004717}
4718
zhihuang1c378ed2017-08-17 14:10:50 -07004719void PeerConnection::GenerateMediaDescriptionOptions(
4720 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004721 RtpTransceiverDirection audio_direction,
4722 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004723 absl::optional<size_t>* audio_index,
4724 absl::optional<size_t>* video_index,
4725 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004726 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004727 for (const cricket::ContentInfo& content :
4728 session_desc->description()->contents()) {
4729 if (IsAudioContent(&content)) {
4730 // If we already have an audio m= section, reject this extra one.
4731 if (*audio_index) {
4732 session_options->media_description_options.push_back(
4733 cricket::MediaDescriptionOptions(
4734 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004735 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004736 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004737 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004738 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004739 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4740 content.name, audio_direction,
4741 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004742 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004743 }
4744 } else if (IsVideoContent(&content)) {
4745 // If we already have an video m= section, reject this extra one.
4746 if (*video_index) {
4747 session_options->media_description_options.push_back(
4748 cricket::MediaDescriptionOptions(
4749 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004750 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004751 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004752 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004753 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004754 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4755 content.name, video_direction,
4756 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004757 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004758 }
4759 } else {
4760 RTC_DCHECK(IsDataContent(&content));
4761 // If we already have an data m= section, reject this extra one.
4762 if (*data_index) {
4763 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004764 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004765 } else {
4766 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004767 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004768 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004769 }
4770 }
htaa2a49d92016-03-04 02:51:39 -08004771 }
deadbeefab9b2d12015-10-14 11:33:11 -07004772}
4773
Steve Antonfa2260d2017-12-28 16:38:23 -08004774cricket::MediaDescriptionOptions
4775PeerConnection::GetMediaDescriptionOptionsForActiveData(
4776 const std::string& mid) const {
4777 // Direction for data sections is meaningless, but legacy endpoints might
4778 // expect sendrecv.
4779 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4780 RtpTransceiverDirection::kSendRecv,
4781 /*stopped=*/false);
4782 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4783 return options;
4784}
4785
4786cricket::MediaDescriptionOptions
4787PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4788 const std::string& mid) const {
4789 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4790 RtpTransceiverDirection::kInactive,
4791 /*stopped=*/true);
4792 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4793 return options;
4794}
4795
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004796absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004797 switch (data_channel_type_) {
4798 case cricket::DCT_RTP:
4799 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004800 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004801 }
4802 return rtp_data_channel_->content_name();
4803 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004804 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004805 case cricket::DCT_MEDIA_TRANSPORT:
4806 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004807 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004808 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004809 }
4810}
4811
Steve Anton4171afb2017-11-20 10:20:22 -08004812void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4813 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4814 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004815 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004816}
4817
Steve Anton4171afb2017-11-20 10:20:22 -08004818void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004819 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004820 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004821 cricket::MediaType media_type,
4822 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004823 RTC_DCHECK(!IsUnifiedPlan());
4824
Steve Anton4171afb2017-11-20 10:20:22 -08004825 std::vector<RtpSenderInfo>* current_senders =
4826 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004827
Steve Anton4171afb2017-11-20 10:20:22 -08004828 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004829 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004830 for (auto sender_it = current_senders->begin();
4831 sender_it != current_senders->end();
4832 /* incremented manually */) {
4833 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004834 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004835 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004836 std::string params_stream_id;
4837 if (params) {
4838 params_stream_id =
4839 (!params->first_stream_id().empty() ? params->first_stream_id()
4840 : kDefaultStreamId);
4841 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004842 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004843 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004844 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004845 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004846 sender_exists) {
4847 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004848 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004849 OnRemoteSenderRemoved(info, media_type);
4850 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004851 }
4852 }
4853
Steve Anton4171afb2017-11-20 10:20:22 -08004854 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004855 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004856 if (!params.has_ssrcs()) {
4857 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4858 // sender, this means it is coming from a Unified Plan endpoint,so we just
4859 // create a default.
4860 default_sender_needed = true;
4861 break;
4862 }
4863
Seth Hampson845e8782018-03-02 11:34:10 -08004864 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004865 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004866 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4867 // not supported in Plan B, we just take the first here and create the
4868 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004869 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004870 (!params.first_stream_id().empty() ? params.first_stream_id()
4871 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004872 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004873 uint32_t ssrc = params.first_ssrc();
4874
4875 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004876 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004877 if (!stream) {
4878 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004879 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004880 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004881 remote_streams_->AddStream(stream);
4882 new_streams->AddStream(stream);
4883 }
4884
Steve Anton4171afb2017-11-20 10:20:22 -08004885 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004886 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004887 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004888 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004889 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004890 }
4891 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004892
Steve Anton4171afb2017-11-20 10:20:22 -08004893 // Add default sender if necessary.
4894 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004895 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004896 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004897 if (!default_stream) {
4898 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004899 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004900 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004901 remote_streams_->AddStream(default_stream);
4902 new_streams->AddStream(default_stream);
4903 }
Steve Anton4171afb2017-11-20 10:20:22 -08004904 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4905 ? kDefaultAudioSenderId
4906 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004907 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004908 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004909 if (!default_sender_info) {
4910 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004911 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004912 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004913 }
4914 }
deadbeefab9b2d12015-10-14 11:33:11 -07004915}
4916
Steve Anton4171afb2017-11-20 10:20:22 -08004917void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4918 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004919 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4920 << " receiver for track_id=" << sender_info.sender_id
4921 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004922
Steve Anton3d954a62018-04-02 11:27:23 -07004923 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004924 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004925 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004926 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004927 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004928 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004929 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004930 }
4931}
4932
Steve Anton4171afb2017-11-20 10:20:22 -08004933void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4934 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004935 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4936 << " receiver for track_id=" << sender_info.sender_id
4937 << " and stream_id=" << sender_info.stream_id;
4938
Seth Hampson845e8782018-03-02 11:34:10 -08004939 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004940
Henrik Boström933d8b02017-10-10 10:05:16 -07004941 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004942 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004943 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4944 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004945 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004946 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004947 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004948 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004949 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004950 }
4951 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004952 // Stopping or destroying a VideoRtpReceiver will end the
4953 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004954 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004955 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004956 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004957 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004958 // There's no guarantee the track is still available, e.g. the track may
4959 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004960 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004961 }
4962 } else {
nisseede5da42017-01-12 05:15:36 -08004963 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004964 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004965 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004966 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004967 }
deadbeefab9b2d12015-10-14 11:33:11 -07004968}
4969
4970void PeerConnection::UpdateEndedRemoteMediaStreams() {
4971 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4972 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4973 MediaStreamInterface* stream = remote_streams_->at(i);
4974 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4975 streams_to_remove.push_back(stream);
4976 }
4977 }
4978
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004979 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004980 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004981 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004982 }
4983}
4984
Steve Anton4171afb2017-11-20 10:20:22 -08004985void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004986 const std::vector<cricket::StreamParams>& streams,
4987 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004988 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004989
Seth Hampson845e8782018-03-02 11:34:10 -08004990 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004991 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004992 for (auto sender_it = current_senders->begin();
4993 sender_it != current_senders->end();
4994 /* incremented manually */) {
4995 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004996 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004997 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4998 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004999 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005000 OnLocalSenderRemoved(info, media_type);
5001 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005002 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005003 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005004 }
5005 }
5006
Steve Anton4171afb2017-11-20 10:20:22 -08005007 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005008 for (const cricket::StreamParams& params : streams) {
5009 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005010 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005011 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005012 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005013 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005014 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005015 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005016 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005017 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005018 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005019 }
5020 }
5021}
5022
Steve Anton4171afb2017-11-20 10:20:22 -08005023void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5024 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005025 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005026 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005027 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005028 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5029 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005030 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005031 return;
5032 }
5033
deadbeeffac06552015-11-25 11:26:01 -08005034 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005035 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005036 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005037 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005038 }
deadbeeffac06552015-11-25 11:26:01 -08005039
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005040 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005041 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005042}
5043
Steve Anton4171afb2017-11-20 10:20:22 -08005044void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5045 cricket::MediaType media_type) {
5046 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005047 if (!sender) {
5048 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005049 // SessionDescriptions has been renegotiated.
5050 return;
5051 }
deadbeeffac06552015-11-25 11:26:01 -08005052
5053 // A sender has been removed from the SessionDescription but it's still
5054 // associated with the PeerConnection. This only occurs if the SDP doesn't
5055 // match with the calls to CreateSender, AddStream and RemoveStream.
5056 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005057 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005058 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005059 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005060 }
deadbeeffac06552015-11-25 11:26:01 -08005061
Steve Anton4171afb2017-11-20 10:20:22 -08005062 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005063}
5064
5065void PeerConnection::UpdateLocalRtpDataChannels(
5066 const cricket::StreamParamsVec& streams) {
5067 std::vector<std::string> existing_channels;
5068
5069 // Find new and active data channels.
5070 for (const cricket::StreamParams& params : streams) {
5071 // |it->sync_label| is actually the data channel label. The reason is that
5072 // we use the same naming of data channels as we do for
5073 // MediaStreams and Tracks.
5074 // For MediaStreams, the sync_label is the MediaStream label and the
5075 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005076 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005077 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005078 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005079 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005080 continue;
5081 }
5082 // Set the SSRC the data channel should use for sending.
5083 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5084 existing_channels.push_back(data_channel_it->first);
5085 }
5086
5087 UpdateClosingRtpDataChannels(existing_channels, true);
5088}
5089
5090void PeerConnection::UpdateRemoteRtpDataChannels(
5091 const cricket::StreamParamsVec& streams) {
5092 std::vector<std::string> existing_channels;
5093
5094 // Find new and active data channels.
5095 for (const cricket::StreamParams& params : streams) {
5096 // The data channel label is either the mslabel or the SSRC if the mslabel
5097 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005098 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005099 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005100 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005101 auto data_channel_it = rtp_data_channels_.find(label);
5102 if (data_channel_it == rtp_data_channels_.end()) {
5103 // This is a new data channel.
5104 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5105 } else {
5106 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5107 }
5108 existing_channels.push_back(label);
5109 }
5110
5111 UpdateClosingRtpDataChannels(existing_channels, false);
5112}
5113
5114void PeerConnection::UpdateClosingRtpDataChannels(
5115 const std::vector<std::string>& active_channels,
5116 bool is_local_update) {
5117 auto it = rtp_data_channels_.begin();
5118 while (it != rtp_data_channels_.end()) {
5119 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005120 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005121 ++it;
5122 continue;
5123 }
5124
5125 if (is_local_update) {
5126 data_channel->SetSendSsrc(0);
5127 } else {
5128 data_channel->RemotePeerRequestClose();
5129 }
5130
5131 if (data_channel->state() == DataChannel::kClosed) {
5132 rtp_data_channels_.erase(it);
5133 it = rtp_data_channels_.begin();
5134 } else {
5135 ++it;
5136 }
5137 }
5138}
5139
5140void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5141 uint32_t remote_ssrc) {
5142 rtc::scoped_refptr<DataChannel> channel(
5143 InternalCreateDataChannel(label, nullptr));
5144 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005145 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005146 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005147 return;
5148 }
5149 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005150 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5151 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005152 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005153}
5154
5155rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5156 const std::string& label,
5157 const InternalDataChannelInit* config) {
5158 if (IsClosed()) {
5159 return nullptr;
5160 }
Steve Anton75737c02017-11-06 10:37:17 -08005161 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005162 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005163 << "InternalCreateDataChannel: Data is not supported in this call.";
5164 return nullptr;
5165 }
5166 InternalDataChannelInit new_config =
5167 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005168 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005169 if (new_config.id < 0) {
5170 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005171 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005172 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005173 RTC_LOG(LS_ERROR)
5174 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005175 return nullptr;
5176 }
5177 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005178 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005179 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005180 return nullptr;
5181 }
5182 }
5183
Steve Anton75737c02017-11-06 10:37:17 -08005184 rtc::scoped_refptr<DataChannel> channel(
5185 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005186 if (!channel) {
5187 sid_allocator_.ReleaseSid(new_config.id);
5188 return nullptr;
5189 }
5190
5191 if (channel->data_channel_type() == cricket::DCT_RTP) {
5192 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005193 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5194 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005195 return nullptr;
5196 }
5197 rtp_data_channels_[channel->label()] = channel;
5198 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005199 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005200 sctp_data_channels_.push_back(channel);
5201 channel->SignalClosed.connect(this,
5202 &PeerConnection::OnSctpDataChannelClosed);
5203 }
5204
Steve Anton2d8609c2018-01-23 16:38:46 -08005205 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005206 return channel;
5207}
5208
5209bool PeerConnection::HasDataChannels() const {
5210 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5211}
5212
5213void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005214 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005215 for (const auto& channel : sctp_data_channels_) {
5216 if (channel->id() < 0) {
5217 int sid;
5218 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005219 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5220 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005221 continue;
5222 }
5223 channel->SetSctpSid(sid);
5224 }
5225 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005226 // Since closing modifies the list of channels, we have to do the actual
5227 // closing outside the loop.
5228 for (const auto& channel : channels_to_close) {
5229 channel->CloseAbruptly();
5230 }
deadbeefab9b2d12015-10-14 11:33:11 -07005231}
5232
5233void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005234 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005235 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5236 ++it) {
5237 if (it->get() == channel) {
5238 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005239 // After the closing procedure is done, it's safe to use this ID for
5240 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005241 sid_allocator_.ReleaseSid(channel->id());
5242 }
deadbeefbd292462015-12-14 18:15:29 -08005243 // Since this method is triggered by a signal from the DataChannel,
5244 // we can't free it directly here; we need to free it asynchronously.
5245 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005246 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005247 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5248 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005249 return;
5250 }
5251 }
5252}
5253
deadbeefab9b2d12015-10-14 11:33:11 -07005254void PeerConnection::OnDataChannelDestroyed() {
5255 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5256 // DataChannel may callback to us and try to modify the list.
5257 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5258 temp_rtp_dcs.swap(rtp_data_channels_);
5259 for (const auto& kv : temp_rtp_dcs) {
5260 kv.second->OnTransportChannelDestroyed();
5261 }
5262
5263 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5264 temp_sctp_dcs.swap(sctp_data_channels_);
5265 for (const auto& channel : temp_sctp_dcs) {
5266 channel->OnTransportChannelDestroyed();
5267 }
5268}
5269
5270void PeerConnection::OnDataChannelOpenMessage(
5271 const std::string& label,
5272 const InternalDataChannelInit& config) {
5273 rtc::scoped_refptr<DataChannel> channel(
5274 InternalCreateDataChannel(label, &config));
5275 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005276 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005277 return;
5278 }
5279
deadbeefa601f5c2016-06-06 14:27:39 -07005280 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5281 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005282 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005283 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005284}
5285
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005286bool PeerConnection::HandleOpenMessage_s(
5287 const cricket::ReceiveDataParams& params,
5288 const rtc::CopyOnWriteBuffer& buffer) {
5289 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5290 // Received OPEN message; parse and signal that a new data channel should
5291 // be created.
5292 std::string label;
5293 InternalDataChannelInit config;
5294 config.id = params.ssrc;
5295 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5296 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5297 << params.ssrc;
5298 return true;
5299 }
5300 config.open_handshake_role = InternalDataChannelInit::kAcker;
5301 OnDataChannelOpenMessage(label, config);
5302 return true;
5303 }
5304 return false;
5305}
5306
Steve Anton4171afb2017-11-20 10:20:22 -08005307rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5308PeerConnection::GetAudioTransceiver() const {
5309 // This method only works with Plan B SDP, where there is a single
5310 // audio/video transceiver.
5311 RTC_DCHECK(!IsUnifiedPlan());
5312 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005313 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005314 return transceiver;
5315 }
5316 }
5317 RTC_NOTREACHED();
5318 return nullptr;
5319}
5320
5321rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5322PeerConnection::GetVideoTransceiver() const {
5323 // This method only works with Plan B SDP, where there is a single
5324 // audio/video transceiver.
5325 RTC_DCHECK(!IsUnifiedPlan());
5326 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005327 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005328 return transceiver;
5329 }
5330 }
5331 RTC_NOTREACHED();
5332 return nullptr;
5333}
5334
5335// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5336// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005337bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005338 switch (type) {
5339 case cricket::MEDIA_TYPE_AUDIO:
5340 return !GetAudioTransceiver()->internal()->senders().empty();
5341 case cricket::MEDIA_TYPE_VIDEO:
5342 return !GetVideoTransceiver()->internal()->senders().empty();
5343 case cricket::MEDIA_TYPE_DATA:
5344 return false;
5345 }
5346 RTC_NOTREACHED();
5347 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005348}
5349
Steve Anton4171afb2017-11-20 10:20:22 -08005350rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5351PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005352 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005353 for (auto sender : transceiver->internal()->senders()) {
5354 if (sender->track() == track) {
5355 return sender;
5356 }
5357 }
5358 }
5359 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005360}
5361
Steve Anton4171afb2017-11-20 10:20:22 -08005362rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5363PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005364 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005365 for (auto sender : transceiver->internal()->senders()) {
5366 if (sender->id() == sender_id) {
5367 return sender;
5368 }
5369 }
5370 }
5371 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005372}
5373
Steve Anton4171afb2017-11-20 10:20:22 -08005374rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5375PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005376 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005377 for (auto receiver : transceiver->internal()->receivers()) {
5378 if (receiver->id() == receiver_id) {
5379 return receiver;
5380 }
5381 }
5382 }
5383 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005384}
5385
Steve Anton4171afb2017-11-20 10:20:22 -08005386std::vector<PeerConnection::RtpSenderInfo>*
5387PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5388 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5389 media_type == cricket::MEDIA_TYPE_VIDEO);
5390 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5391 ? &remote_audio_sender_infos_
5392 : &remote_video_sender_infos_;
5393}
5394
5395std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005396 cricket::MediaType media_type) {
5397 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5398 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005399 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5400 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005401}
5402
Steve Anton4171afb2017-11-20 10:20:22 -08005403const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5404 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005405 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005406 const std::string sender_id) const {
5407 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005408 if (sender_info.stream_id == stream_id &&
5409 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005410 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005411 }
5412 }
5413 return nullptr;
5414}
5415
5416DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5417 for (const auto& channel : sctp_data_channels_) {
5418 if (channel->id() == sid) {
5419 return channel;
5420 }
5421 }
5422 return nullptr;
5423}
5424
Karl Wibergfb3be392019-03-22 14:13:22 +01005425PeerConnection::InitializePortAllocatorResult
5426PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005427 const cricket::ServerAddresses& stun_servers,
5428 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005429 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005430 RTC_DCHECK_RUN_ON(network_thread());
5431
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005432 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005433 // To handle both internal and externally created port allocator, we will
5434 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005435 int port_allocator_flags = port_allocator_->flags();
5436 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5437 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5438 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005439 // If the disable-IPv6 flag was specified, we'll not override it
5440 // by experiment.
5441 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005442 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005443 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5444 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005445 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005446 }
5447
zhihuangb09b3f92017-03-07 14:40:51 -08005448 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005449 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005450 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005451 }
5452
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005453 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005454 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005455 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005456 }
5457
honghaiz60347052016-05-31 18:29:12 -07005458 if (configuration.candidate_network_policy ==
5459 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005460 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005461 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005462 }
5463
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005464 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005465 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005466 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5467 }
5468
Karl Wibergfb3be392019-03-22 14:13:22 +01005469 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005470 // No step delay is used while allocating ports.
5471 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005472 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005473 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005474 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005475
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005476 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005477 for (auto& turn_server : turn_servers_copy) {
5478 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005479 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005480 // Call this last since it may create pooled allocator sessions using the
5481 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005482 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005483 stun_servers, std::move(turn_servers_copy),
5484 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5485 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005486 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005487
5488 InitializePortAllocatorResult res;
5489 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5490 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005491}
5492
deadbeef91dd5672016-05-18 16:55:30 -07005493bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005494 const cricket::ServerAddresses& stun_servers,
5495 const std::vector<cricket::RelayServerConfig>& turn_servers,
5496 IceTransportsType type,
5497 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005498 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005499 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005500 absl::optional<int> stun_candidate_keepalive_interval,
5501 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005502 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005503 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005504 // According to JSEP, after setLocalDescription, changing the candidate pool
5505 // size is not allowed, and changing the set of ICE servers will not result
5506 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005507 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005508 port_allocator_->FreezeCandidatePool();
5509 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005510 // Add the custom tls turn servers if they exist.
5511 auto turn_servers_copy = turn_servers;
5512 for (auto& turn_server : turn_servers_copy) {
5513 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5514 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005515 // Call this last since it may create pooled allocator sessions using the
5516 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005517 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005518 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5519 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005520}
5521
Steve Antonba818672017-11-06 10:21:57 -08005522cricket::ChannelManager* PeerConnection::channel_manager() const {
5523 return factory_->channel_manager();
5524}
5525
Elad Alon99c3fe52017-10-13 16:29:40 +02005526bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005527 std::unique_ptr<RtcEventLogOutput> output,
5528 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005529 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005530 if (!event_log_) {
5531 return false;
5532 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005533 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005534}
5535
5536void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005537 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005538 if (event_log_) {
5539 event_log_->StopLogging();
5540 }
ivoc14d5dbe2016-07-04 07:06:55 -07005541}
nisseeaabdf62017-05-05 02:23:02 -07005542
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005543cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005544 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005545 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005546 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005547 if (channel && channel->content_name() == content_name) {
5548 return channel;
5549 }
Steve Anton75737c02017-11-06 10:37:17 -08005550 }
5551 if (rtp_data_channel() &&
5552 rtp_data_channel()->content_name() == content_name) {
5553 return rtp_data_channel();
5554 }
5555 return nullptr;
5556}
5557
5558bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005559 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005560 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005561 RTC_LOG(LS_INFO)
5562 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005563 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005564 return false;
5565 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005566 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005567 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005568 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005569 return false;
5570 }
5571
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005572 absl::optional<rtc::SSLRole> dtls_role;
5573 if (sctp_mid_) {
5574 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5575 } else if (is_caller_) {
5576 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5577 }
Zhi Huange830e682018-03-30 10:48:35 -07005578 if (dtls_role) {
5579 *role = *dtls_role;
5580 return true;
5581 }
5582 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005583}
5584
5585bool PeerConnection::GetSslRole(const std::string& content_name,
5586 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005587 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005588 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005589 RTC_LOG(LS_INFO)
5590 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005591 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005592 return false;
5593 }
5594
Zhi Huange830e682018-03-30 10:48:35 -07005595 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5596 if (dtls_role) {
5597 *role = *dtls_role;
5598 return true;
5599 }
5600 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005601}
5602
Steve Antonf8470812017-12-04 10:46:21 -08005603void PeerConnection::SetSessionError(SessionError error,
5604 const std::string& error_desc) {
5605 RTC_DCHECK_RUN_ON(signaling_thread());
5606 if (error != session_error_) {
5607 session_error_ = error;
5608 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005609 }
5610}
5611
Zhi Huange830e682018-03-30 10:48:35 -07005612RTCError PeerConnection::UpdateSessionState(
5613 SdpType type,
5614 cricket::ContentSource source,
5615 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005616 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005617
5618 // If there's already a pending error then no state transition should happen.
5619 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005620 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005621
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005622 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005623 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005624 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005625 }
5626
5627 // Update the signaling state according to the specified state machine (see
5628 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005629 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005630 ChangeSignalingState(source == cricket::CS_LOCAL
5631 ? PeerConnectionInterface::kHaveLocalOffer
5632 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005633 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005634 ChangeSignalingState(source == cricket::CS_LOCAL
5635 ? PeerConnectionInterface::kHaveLocalPrAnswer
5636 : PeerConnectionInterface::kHaveRemotePrAnswer);
5637 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005638 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005639 ChangeSignalingState(PeerConnectionInterface::kStable);
5640 }
5641
5642 // Update internal objects according to the session description's media
5643 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005644 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005645 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005646 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005647 }
5648
Steve Anton8a006912017-12-04 15:25:56 -08005649 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005650}
5651
Steve Anton8a006912017-12-04 15:25:56 -08005652RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005653 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005654 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005655 const SessionDescriptionInterface* sdesc =
5656 (source == cricket::CS_LOCAL ? local_description()
5657 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005658 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005659
5660 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005661 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005662 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005663 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005664 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005665 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005666 continue;
5667 }
5668 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005669 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005670 if (!content_desc) {
5671 continue;
5672 }
5673 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005674 bool success = (source == cricket::CS_LOCAL)
5675 ? channel->SetLocalContent(content_desc, type, &error)
5676 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005677 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005678 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005679 }
5680 }
5681
5682 // If using the RtpDataChannel, push down the new SDP section for it too.
5683 if (rtp_data_channel_) {
5684 const ContentInfo* data_content =
5685 cricket::GetFirstDataContent(sdesc->description());
5686 if (data_content && !data_content->rejected) {
5687 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005688 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005689 if (data_desc) {
5690 std::string error;
5691 bool success =
5692 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005693 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005694 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005695 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005697 }
Steve Anton75737c02017-11-06 10:37:17 -08005698 }
5699 }
5700 }
Steve Antoned10bd92017-12-05 10:52:59 -08005701
Steve Anton75737c02017-11-06 10:37:17 -08005702 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5703 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005704 if (sctp_transport_ && local_description() && remote_description()) {
5705 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5706 local_description()->description());
5707 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5708 remote_description()->description());
5709 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005710 int max_message_size;
5711 // A remote max message size of zero means "any size supported".
5712 // We configure the connection with our own max message size.
5713 if (remote_sctp_description->max_message_size() == 0) {
5714 max_message_size = local_sctp_description->max_message_size();
5715 } else {
5716 max_message_size =
5717 std::min(local_sctp_description->max_message_size(),
5718 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005719 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005720 sctp_transport_->Start(local_sctp_description->port(),
5721 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005722 }
Steve Anton75737c02017-11-06 10:37:17 -08005723 }
Steve Antoned10bd92017-12-05 10:52:59 -08005724
Steve Anton8a006912017-12-04 15:25:56 -08005725 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005726}
5727
Steve Anton8a006912017-12-04 15:25:56 -08005728RTCError PeerConnection::PushdownTransportDescription(
5729 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005730 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005731 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005732
Zhi Huange830e682018-03-30 10:48:35 -07005733 if (source == cricket::CS_LOCAL) {
5734 const SessionDescriptionInterface* sdesc = local_description();
5735 RTC_DCHECK(sdesc);
5736 return transport_controller_->SetLocalDescription(type,
5737 sdesc->description());
5738 } else {
5739 const SessionDescriptionInterface* sdesc = remote_description();
5740 RTC_DCHECK(sdesc);
5741 return transport_controller_->SetRemoteDescription(type,
5742 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005743 }
Steve Anton75737c02017-11-06 10:37:17 -08005744}
5745
5746bool PeerConnection::GetTransportDescription(
5747 const SessionDescription* description,
5748 const std::string& content_name,
5749 cricket::TransportDescription* tdesc) {
5750 if (!description || !tdesc) {
5751 return false;
5752 }
5753 const TransportInfo* transport_info =
5754 description->GetTransportInfoByName(content_name);
5755 if (!transport_info) {
5756 return false;
5757 }
5758 *tdesc = transport_info->description;
5759 return true;
5760}
5761
Steve Anton75737c02017-11-06 10:37:17 -08005762cricket::IceConfig PeerConnection::ParseIceConfig(
5763 const PeerConnectionInterface::RTCConfiguration& config) const {
5764 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005765 switch (config.continual_gathering_policy) {
5766 case PeerConnectionInterface::GATHER_ONCE:
5767 gathering_policy = cricket::GATHER_ONCE;
5768 break;
5769 case PeerConnectionInterface::GATHER_CONTINUALLY:
5770 gathering_policy = cricket::GATHER_CONTINUALLY;
5771 break;
5772 default:
5773 RTC_NOTREACHED();
5774 gathering_policy = cricket::GATHER_ONCE;
5775 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005776
Steve Anton75737c02017-11-06 10:37:17 -08005777 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005778 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5779 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005780 ice_config.prioritize_most_likely_candidate_pairs =
5781 config.prioritize_most_likely_ice_candidate_pairs;
5782 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005783 RTCConfigurationToIceConfigOptionalInt(
5784 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005785 ice_config.continual_gathering_policy = gathering_policy;
5786 ice_config.presume_writable_when_fully_relayed =
5787 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005788 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5789 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005790 ice_config.ice_check_interval_strong_connectivity =
5791 config.ice_check_interval_strong_connectivity;
5792 ice_config.ice_check_interval_weak_connectivity =
5793 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005794 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005795 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5796 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005797 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005798 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005799 ice_config.regather_all_networks_interval_range =
5800 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005801 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005802 return ice_config;
5803}
5804
Steve Anton75737c02017-11-06 10:37:17 -08005805bool PeerConnection::SendData(const cricket::SendDataParams& params,
5806 const rtc::CopyOnWriteBuffer& payload,
5807 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005808 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005809 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5810 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5811 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005812 return false;
5813 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005814 if (media_transport_) {
5815 SendDataParams send_params;
5816 send_params.type = ToWebrtcDataMessageType(params.type);
5817 send_params.ordered = params.ordered;
5818 if (params.max_rtx_count >= 0) {
5819 send_params.max_rtx_count = params.max_rtx_count;
5820 } else if (params.max_rtx_ms >= 0) {
5821 send_params.max_rtx_ms = params.max_rtx_ms;
5822 }
5823 return media_transport_->SendData(params.sid, send_params, payload).ok();
5824 }
Steve Anton75737c02017-11-06 10:37:17 -08005825 return rtp_data_channel_
5826 ? rtp_data_channel_->SendData(params, payload, result)
5827 : network_thread()->Invoke<bool>(
5828 RTC_FROM_HERE,
5829 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005830 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005831}
5832
5833bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005834 RTC_DCHECK_RUN_ON(signaling_thread());
5835 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005836 // Don't log an error here, because DataChannels are expected to call
5837 // ConnectDataChannel in this state. It's the only way to initially tell
5838 // whether or not the underlying transport is ready.
5839 return false;
5840 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005841 if (media_transport_) {
5842 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5843 &DataChannel::OnChannelReady);
5844 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5845 &DataChannel::OnDataReceived);
5846 SignalMediaTransportChannelClosing_s.connect(
5847 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5848 SignalMediaTransportChannelClosed_s.connect(
5849 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5850 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 rtp_data_channel_->SignalReadyToSendData.connect(
5852 webrtc_data_channel, &DataChannel::OnChannelReady);
5853 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5854 &DataChannel::OnDataReceived);
5855 } else {
5856 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5857 &DataChannel::OnChannelReady);
5858 SignalSctpDataReceived.connect(webrtc_data_channel,
5859 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005860 SignalSctpClosingProcedureStartedRemotely.connect(
5861 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5862 SignalSctpClosingProcedureComplete.connect(
5863 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005864 }
5865 return true;
5866}
5867
5868void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005869 RTC_DCHECK_RUN_ON(signaling_thread());
5870 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005871 RTC_LOG(LS_ERROR)
5872 << "DisconnectDataChannel called when rtp_data_channel_ and "
5873 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005874 return;
5875 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005876 if (media_transport_) {
5877 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5878 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5879 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5880 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5881 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005882 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5883 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5884 } else {
5885 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5886 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005887 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5888 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005889 }
5890}
5891
5892void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005893 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005894 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005895 return;
5896 }
Steve Anton75737c02017-11-06 10:37:17 -08005897 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005898 RTC_LOG(LS_ERROR)
5899 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005900 return;
5901 }
5902 network_thread()->Invoke<void>(
5903 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005904 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005905}
5906
5907void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005908 if (media_transport_) {
5909 media_transport_->CloseChannel(sid);
5910 return;
5911 }
Steve Anton75737c02017-11-06 10:37:17 -08005912 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005913 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005914 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005915 return;
5916 }
5917 network_thread()->Invoke<void>(
5918 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005919 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005920}
5921
5922bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005923 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005924 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005925 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005926 sctp_ready_to_send_data_;
5927}
5928
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005929void PeerConnection::OnDataReceived(int channel_id,
5930 DataMessageType type,
5931 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005932 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005933 cricket::ReceiveDataParams params;
5934 params.sid = channel_id;
5935 params.type = ToCricketDataMessageType(type);
5936 media_transport_invoker_->AsyncInvoke<void>(
5937 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5938 RTC_DCHECK_RUN_ON(signaling_thread());
5939 if (!HandleOpenMessage_s(params, buffer)) {
5940 SignalMediaTransportReceivedData_s(params, buffer);
5941 }
5942 });
5943}
5944
5945void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005946 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005947 media_transport_invoker_->AsyncInvoke<void>(
5948 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5949 RTC_DCHECK_RUN_ON(signaling_thread());
5950 SignalMediaTransportChannelClosing_s(channel_id);
5951 });
5952}
5953
5954void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005955 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005956 media_transport_invoker_->AsyncInvoke<void>(
5957 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5958 RTC_DCHECK_RUN_ON(signaling_thread());
5959 SignalMediaTransportChannelClosed_s(channel_id);
5960 });
5961}
5962
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005963absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005964 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005965 if (sctp_mid_ && transport_controller_) {
5966 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5967 if (dtls_transport) {
5968 return dtls_transport->transport_name();
5969 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005970 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005971 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005972 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005973}
5974
Qingsi Wang72a43a12018-02-20 16:03:18 -08005975cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5976 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005977 network_thread()->Invoke<void>(
5978 RTC_FROM_HERE,
5979 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5980 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005981 return candidate_states_list;
5982}
5983
Steve Anton5dfde182018-02-06 10:34:40 -08005984std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5985 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005986 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005987 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005988 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005989 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005990 if (channel) {
5991 transport_names_by_mid[channel->content_name()] =
5992 channel->transport_name();
5993 }
Steve Anton75737c02017-11-06 10:37:17 -08005994 }
Steve Anton5dfde182018-02-06 10:34:40 -08005995 if (rtp_data_channel_) {
5996 transport_names_by_mid[rtp_data_channel_->content_name()] =
5997 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005998 }
5999 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006000 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006001 RTC_DCHECK(transport_name);
6002 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006003 }
Steve Anton5dfde182018-02-06 10:34:40 -08006004 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006005}
6006
Steve Anton5dfde182018-02-06 10:34:40 -08006007std::map<std::string, cricket::TransportStats>
6008PeerConnection::GetTransportStatsByNames(
6009 const std::set<std::string>& transport_names) {
6010 if (!network_thread()->IsCurrent()) {
6011 return network_thread()
6012 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6013 RTC_FROM_HERE,
6014 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006015 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006016 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006017 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6018 for (const std::string& transport_name : transport_names) {
6019 cricket::TransportStats transport_stats;
6020 bool success =
6021 transport_controller_->GetStats(transport_name, &transport_stats);
6022 if (success) {
6023 transport_stats_by_name[transport_name] = std::move(transport_stats);
6024 } else {
6025 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6026 << transport_name;
6027 }
6028 }
6029 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006030}
6031
6032bool PeerConnection::GetLocalCertificate(
6033 const std::string& transport_name,
6034 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006035 if (!certificate) {
6036 return false;
6037 }
6038 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6039 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006040}
6041
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006042std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006043 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006044 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006045}
6046
6047cricket::DataChannelType PeerConnection::data_channel_type() const {
6048 return data_channel_type_;
6049}
6050
6051bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006052 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006053 return pending_ice_restarts_.find(content_name) !=
6054 pending_ice_restarts_.end();
6055}
6056
Steve Anton75737c02017-11-06 10:37:17 -08006057bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6058 return transport_controller_->NeedsIceRestart(content_name);
6059}
6060
6061void PeerConnection::OnCertificateReady(
6062 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6063 transport_controller_->SetLocalCertificate(certificate);
6064}
6065
6066void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006067 SetSessionError(SessionError::kTransport,
6068 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006069}
6070
Alex Loiko9289eda2018-11-23 16:18:59 +00006071void PeerConnection::OnTransportControllerConnectionState(
6072 cricket::IceConnectionState state) {
6073 switch (state) {
6074 case cricket::kIceConnectionConnecting:
6075 // If the current state is Connected or Completed, then there were
6076 // writable channels but now there are not, so the next state must
6077 // be Disconnected.
6078 // kIceConnectionConnecting is currently used as the default,
6079 // un-connected state by the TransportController, so its only use is
6080 // detecting disconnections.
6081 if (ice_connection_state_ ==
6082 PeerConnectionInterface::kIceConnectionConnected ||
6083 ice_connection_state_ ==
6084 PeerConnectionInterface::kIceConnectionCompleted) {
6085 SetIceConnectionState(
6086 PeerConnectionInterface::kIceConnectionDisconnected);
6087 }
6088 break;
6089 case cricket::kIceConnectionFailed:
6090 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6091 break;
6092 case cricket::kIceConnectionConnected:
6093 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6094 "all transports are writable.";
6095 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6096 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6097 break;
6098 case cricket::kIceConnectionCompleted:
6099 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6100 "all transports are complete.";
6101 if (ice_connection_state_ !=
6102 PeerConnectionInterface::kIceConnectionConnected) {
6103 // If jumping directly from "checking" to "connected",
6104 // signal "connected" first.
6105 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6106 }
6107 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6108 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6109 ReportTransportStats();
6110 break;
6111 default:
6112 RTC_NOTREACHED();
6113 }
6114}
6115
Steve Anton75737c02017-11-06 10:37:17 -08006116void PeerConnection::OnTransportControllerCandidatesGathered(
6117 const std::string& transport_name,
6118 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006119 int sdp_mline_index;
6120 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006121 RTC_LOG(LS_ERROR)
6122 << "OnTransportControllerCandidatesGathered: content name "
6123 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006124 return;
6125 }
6126
6127 for (cricket::Candidates::const_iterator citer = candidates.begin();
6128 citer != candidates.end(); ++citer) {
6129 // Use transport_name as the candidate media id.
6130 std::unique_ptr<JsepIceCandidate> candidate(
6131 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6132 if (local_description()) {
6133 mutable_local_description()->AddCandidate(candidate.get());
6134 }
6135 OnIceCandidate(std::move(candidate));
6136 }
6137}
6138
Eldar Relloda13ea22019-06-01 12:23:43 +03006139void PeerConnection::OnTransportControllerCandidateError(
6140 const cricket::IceCandidateErrorEvent& event) {
6141 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6142 event.error_text);
6143}
6144
Steve Anton75737c02017-11-06 10:37:17 -08006145void PeerConnection::OnTransportControllerCandidatesRemoved(
6146 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006147 // Sanity check.
6148 for (const cricket::Candidate& candidate : candidates) {
6149 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006150 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006151 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006152 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006153 return;
6154 }
6155 }
6156
6157 if (local_description()) {
6158 mutable_local_description()->RemoveCandidates(candidates);
6159 }
6160 OnIceCandidatesRemoved(candidates);
6161}
6162
6163void PeerConnection::OnTransportControllerDtlsHandshakeError(
6164 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006165 RTC_HISTOGRAM_ENUMERATION(
6166 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6167 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006168}
6169
Steve Antoned10bd92017-12-05 10:52:59 -08006170void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006171 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006172 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006173 if (channel && !channel->enabled()) {
6174 channel->Enable(true);
6175 }
Steve Anton75737c02017-11-06 10:37:17 -08006176 }
6177
Steve Anton4171afb2017-11-20 10:20:22 -08006178 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006179 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006180 }
Steve Anton75737c02017-11-06 10:37:17 -08006181}
6182
6183// Returns the media index for a local ice candidate given the content name.
6184bool PeerConnection::GetLocalCandidateMediaIndex(
6185 const std::string& content_name,
6186 int* sdp_mline_index) {
6187 if (!local_description() || !sdp_mline_index) {
6188 return false;
6189 }
6190
6191 bool content_found = false;
6192 const ContentInfos& contents = local_description()->description()->contents();
6193 for (size_t index = 0; index < contents.size(); ++index) {
6194 if (contents[index].name == content_name) {
6195 *sdp_mline_index = static_cast<int>(index);
6196 content_found = true;
6197 break;
6198 }
6199 }
6200 return content_found;
6201}
6202
6203bool PeerConnection::UseCandidatesInSessionDescription(
6204 const SessionDescriptionInterface* remote_desc) {
6205 if (!remote_desc) {
6206 return true;
6207 }
6208 bool ret = true;
6209
6210 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6211 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6212 for (size_t n = 0; n < candidates->count(); ++n) {
6213 const IceCandidateInterface* candidate = candidates->at(n);
6214 bool valid = false;
6215 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6216 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006217 RTC_LOG(LS_INFO)
6218 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006219 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006220 }
6221 continue;
6222 }
6223 ret = UseCandidate(candidate);
6224 if (!ret) {
6225 break;
6226 }
6227 }
6228 }
6229 return ret;
6230}
6231
6232bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006233 RTCErrorOr<const cricket::ContentInfo*> result =
6234 FindContentInfo(remote_description(), candidate);
6235 if (!result.ok()) {
6236 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6237 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006238 return false;
6239 }
Steve Anton75737c02017-11-06 10:37:17 -08006240 std::vector<cricket::Candidate> candidates;
6241 candidates.push_back(candidate->candidate());
6242 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006243 RTCError error = transport_controller_->AddRemoteCandidates(
6244 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006245 if (error.ok()) {
6246 // Candidates successfully submitted for checking.
6247 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6248 ice_connection_state_ ==
6249 PeerConnectionInterface::kIceConnectionDisconnected) {
6250 // If state is New, then the session has just gotten its first remote ICE
6251 // candidates, so go to Checking.
6252 // If state is Disconnected, the session is re-using old candidates or
6253 // receiving additional ones, so go to Checking.
6254 // If state is Connected, stay Connected.
6255 // TODO(bemasc): If state is Connected, and the new candidates are for a
6256 // newly added transport, then the state actually _should_ move to
6257 // checking. Add a way to distinguish that case.
6258 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6259 }
6260 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006261 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006262 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006263 }
6264 return true;
6265}
6266
Guido Urdaneta41633172019-05-23 20:12:29 +02006267RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6268 const SessionDescriptionInterface* description,
6269 const IceCandidateInterface* candidate) {
6270 if (candidate->sdp_mline_index() >= 0) {
6271 size_t mediacontent_index =
6272 static_cast<size_t>(candidate->sdp_mline_index());
6273 size_t content_size = description->description()->contents().size();
6274 if (mediacontent_index < content_size) {
6275 return &description->description()->contents()[mediacontent_index];
6276 } else {
6277 return RTCError(RTCErrorType::INVALID_RANGE,
6278 "Media line index (" +
6279 rtc::ToString(candidate->sdp_mline_index()) +
6280 ") out of range (number of mlines: " +
6281 rtc::ToString(content_size) + ").");
6282 }
6283 } else if (!candidate->sdp_mid().empty()) {
6284 auto& contents = description->description()->contents();
6285 auto it = absl::c_find_if(
6286 contents, [candidate](const cricket::ContentInfo& content_info) {
6287 return content_info.mid() == candidate->sdp_mid();
6288 });
6289 if (it == contents.end()) {
6290 return RTCError(
6291 RTCErrorType::INVALID_PARAMETER,
6292 "Mid " + candidate->sdp_mid() +
6293 " specified but no media section with that mid found.");
6294 } else {
6295 return &*it;
6296 }
6297 }
6298
6299 return RTCError(RTCErrorType::INVALID_PARAMETER,
6300 "Neither sdp_mline_index nor sdp_mid specified.");
6301}
6302
Steve Anton75737c02017-11-06 10:37:17 -08006303void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006304 // Destroy video channel first since it may have a pointer to the
6305 // voice channel.
6306 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006307 if (!video_info || video_info->rejected) {
6308 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006309 }
6310
Steve Anton6fec8802017-12-04 10:37:29 -08006311 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6312 if (!audio_info || audio_info->rejected) {
6313 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006314 }
6315
6316 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6317 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006318 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006319 }
6320}
6321
Steve Antondcc3c022017-12-22 16:02:54 -08006322RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6323 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006324 const cricket::ContentGroup* bundle_group = nullptr;
6325 if (configuration_.bundle_policy ==
6326 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006327 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006328 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006329 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6330 "max-bundle configured but session description "
6331 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006332 }
6333 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006334 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006335}
6336
6337RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006338 // Creating the media channels. Transports should already have been created
6339 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006340 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006341 if (voice && !voice->rejected &&
6342 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006343 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006344 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006345 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6346 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006347 }
6348 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6349 }
6350
Steve Antondcc3c022017-12-22 16:02:54 -08006351 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006352 if (video && !video->rejected &&
6353 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006354 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006355 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006356 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6357 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006358 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006359 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006360 }
6361
Steve Antondcc3c022017-12-22 16:02:54 -08006362 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006363 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006364 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006365 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006366 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6367 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006368 }
6369 }
6370
Steve Anton8a006912017-12-04 15:25:56 -08006371 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006372}
6373
Steve Anton4171afb2017-11-20 10:20:22 -08006374// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006375cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006376 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006377 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006378 MediaTransportConfig media_transport_config =
6379 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006380
Steve Anton75737c02017-11-06 10:37:17 -08006381 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006382 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006383 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6384 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006385 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006386 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006387 }
Steve Anton75737c02017-11-06 10:37:17 -08006388 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6389 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006390 voice_channel->SignalSentPacket.connect(this,
6391 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006392 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006393
Steve Antoneda6ccd2017-12-04 10:21:55 -08006394 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006395}
6396
Steve Anton4171afb2017-11-20 10:20:22 -08006397// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006398cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006399 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006400 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006401 MediaTransportConfig media_transport_config =
6402 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006403
Steve Anton75737c02017-11-06 10:37:17 -08006404 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006405 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006406 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6407 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006408 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006409 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006410 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006411 }
Steve Anton75737c02017-11-06 10:37:17 -08006412 video_channel->SignalDtlsSrtpSetupFailure.connect(
6413 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006414 video_channel->SignalSentPacket.connect(this,
6415 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006416 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006417
Steve Antoneda6ccd2017-12-04 10:21:55 -08006418 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006419}
6420
Zhi Huange830e682018-03-30 10:48:35 -07006421bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006422 switch (data_channel_type_) {
6423 case cricket::DCT_MEDIA_TRANSPORT:
6424 if (network_thread()->Invoke<bool>(
6425 RTC_FROM_HERE,
6426 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6427 this, mid))) {
6428 for (const auto& channel : sctp_data_channels_) {
6429 channel->OnTransportChannelCreated();
6430 }
6431 return true;
6432 }
Steve Anton75737c02017-11-06 10:37:17 -08006433 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006434 case cricket::DCT_SCTP:
6435 if (!sctp_factory_) {
6436 RTC_LOG(LS_ERROR)
6437 << "Trying to create SCTP transport, but didn't compile with "
6438 "SCTP support (HAVE_SCTP)";
6439 return false;
6440 }
6441 if (!network_thread()->Invoke<bool>(
6442 RTC_FROM_HERE,
6443 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6444 return false;
6445 }
6446 for (const auto& channel : sctp_data_channels_) {
6447 channel->OnTransportChannelCreated();
6448 }
6449 return true;
6450 case cricket::DCT_RTP:
6451 default:
6452 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6453 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6454 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006455 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006456 if (!rtp_data_channel_) {
6457 return false;
6458 }
6459 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6460 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6461 rtp_data_channel_->SignalSentPacket.connect(
6462 this, &PeerConnection::OnSentPacket_w);
6463 rtp_data_channel_->SetRtpTransport(rtp_transport);
6464 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006465 }
6466
Steve Anton75737c02017-11-06 10:37:17 -08006467 return true;
6468}
6469
6470Call::Stats PeerConnection::GetCallStats() {
6471 if (!worker_thread()->IsCurrent()) {
6472 return worker_thread()->Invoke<Call::Stats>(
6473 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6474 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006475 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006476 if (call_) {
6477 return call_->GetStats();
6478 } else {
6479 return Call::Stats();
6480 }
6481}
6482
Zhi Huange830e682018-03-30 10:48:35 -07006483bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006484 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006485 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006486 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6487 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006488 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006489 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006490 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006491 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6492 sctp_factory_->CreateSctpTransport(dtls_transport);
6493 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006494 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006495 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006496 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006497 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006498 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006499 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6500 // another thread. Would be nice if there was a helper class similar to
6501 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6502 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006503 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006504 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006505 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006506 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006507 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006508 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6509 std::move(cricket_sctp_transport));
6510 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006511 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006512}
6513
6514void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006515 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006516 sctp_transport_->Clear();
6517 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006518 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006519 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006520}
6521
6522void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006523 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006524 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006525 // Note: Cannot use rtc::Bind here because it will grab a reference to
6526 // PeerConnection and potentially cause PeerConnection to live longer than
6527 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6528 // be destroyed before PeerConnection is destroyed, and at that point all
6529 // pending tasks will be cleared.
6530 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6531 OnSctpTransportReadyToSendData_s(true);
6532 });
6533}
6534
6535void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006536 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006537 sctp_ready_to_send_data_ = ready;
6538 SignalSctpReadyToSendData(ready);
6539}
6540
6541void PeerConnection::OnSctpTransportDataReceived_n(
6542 const cricket::ReceiveDataParams& params,
6543 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006544 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006545 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006546 // Note: Cannot use rtc::Bind here because it will grab a reference to
6547 // PeerConnection and potentially cause PeerConnection to live longer than
6548 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6549 // be destroyed before PeerConnection is destroyed, and at that point all
6550 // pending tasks will be cleared.
6551 sctp_invoker_->AsyncInvoke<void>(
6552 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6553 OnSctpTransportDataReceived_s(params, payload);
6554 });
6555}
6556
6557void PeerConnection::OnSctpTransportDataReceived_s(
6558 const cricket::ReceiveDataParams& params,
6559 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006560 RTC_DCHECK_RUN_ON(signaling_thread());
6561 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006562 SignalSctpDataReceived(params, payload);
6563 }
6564}
6565
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006566void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006567 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006568 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006569 sctp_invoker_->AsyncInvoke<void>(
6570 RTC_FROM_HERE, signaling_thread(),
6571 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006572 &SignalSctpClosingProcedureStartedRemotely, sid));
6573}
6574
6575void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006576 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006577 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006578 sctp_invoker_->AsyncInvoke<void>(
6579 RTC_FROM_HERE, signaling_thread(),
6580 rtc::Bind(&sigslot::signal1<int>::operator(),
6581 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006582}
6583
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006584bool PeerConnection::SetupMediaTransportForDataChannels_n(
6585 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006586 media_transport_ =
6587 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006588 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006589 RTC_LOG(LS_ERROR)
6590 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006591 return false;
6592 }
6593
6594 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6595 media_transport_->SetDataSink(this);
6596 media_transport_data_mid_ = mid;
6597 transport_controller_->SignalMediaTransportStateChanged.connect(
6598 this, &PeerConnection::OnMediaTransportStateChanged_n);
6599 // Check the initial state right away, in case transport is already writable.
6600 OnMediaTransportStateChanged_n();
6601 return true;
6602}
6603
6604void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6605 if (!media_transport_) {
6606 return;
6607 }
6608 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6609 media_transport_data_mid_.reset();
6610 media_transport_->SetDataSink(nullptr);
6611 media_transport_invoker_ = nullptr;
6612 media_transport_ = nullptr;
6613}
6614
6615void PeerConnection::OnMediaTransportStateChanged_n() {
6616 if (!media_transport_data_mid_ ||
6617 transport_controller_->GetMediaTransportState(
6618 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6619 return;
6620 }
6621 media_transport_invoker_->AsyncInvoke<void>(
6622 RTC_FROM_HERE, signaling_thread(), [this] {
6623 RTC_DCHECK_RUN_ON(signaling_thread());
6624 media_transport_ready_to_send_data_ = true;
6625 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6626 });
6627}
6628
Steve Anton75737c02017-11-06 10:37:17 -08006629// Returns false if bundle is enabled and rtcp_mux is disabled.
6630bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6631 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6632 if (!bundle_enabled)
6633 return true;
6634
6635 const cricket::ContentGroup* bundle_group =
6636 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6637 RTC_DCHECK(bundle_group != NULL);
6638
6639 const cricket::ContentInfos& contents = desc->contents();
6640 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6641 citer != contents.end(); ++citer) {
6642 const cricket::ContentInfo* content = (&*citer);
6643 RTC_DCHECK(content != NULL);
6644 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006645 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006646 if (!HasRtcpMuxEnabled(content))
6647 return false;
6648 }
6649 }
6650 // RTCP-MUX is enabled in all the contents.
6651 return true;
6652}
6653
6654bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006655 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006656}
6657
Steve Anton06817cd2018-12-18 15:55:30 -08006658static RTCError ValidateMids(const cricket::SessionDescription& description) {
6659 std::set<std::string> mids;
6660 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006661 if (content.name.empty()) {
6662 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6663 "A media section is missing a MID attribute.");
6664 }
Steve Anton06817cd2018-12-18 15:55:30 -08006665 if (!mids.insert(content.name).second) {
6666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6667 "Duplicate a=mid value '" + content.name + "'.");
6668 }
6669 }
6670 return RTCError::OK();
6671}
6672
Steve Anton8a006912017-12-04 15:25:56 -08006673RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006674 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006675 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006676 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006677 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006678 }
6679
6680 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006681 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006682 }
6683
Steve Anton3828c062017-12-06 10:34:51 -08006684 SdpType type = sdesc->GetType();
6685 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6686 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006687 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006688 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006689 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006690 }
6691
Steve Anton06817cd2018-12-18 15:55:30 -08006692 RTCError error = ValidateMids(*sdesc->description());
6693 if (!error.ok()) {
6694 return error;
6695 }
6696
Steve Anton75737c02017-11-06 10:37:17 -08006697 // Verify crypto settings.
6698 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006699 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6700 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006701 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006702 if (!crypto_error.ok()) {
6703 return crypto_error;
6704 }
Steve Anton75737c02017-11-06 10:37:17 -08006705 }
6706
6707 // Verify ice-ufrag and ice-pwd.
6708 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006709 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6710 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006711 }
6712
6713 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006714 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6715 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006716 }
6717
6718 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6719 // m-lines that do not rtcp-mux enabled.
6720
6721 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006722 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006723 // With an answer we want to compare the new answer session description with
6724 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006725 const cricket::SessionDescription* offer_desc =
6726 (source == cricket::CS_LOCAL) ? remote_description()->description()
6727 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006728 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6729 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6730 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006731 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6732 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006733 }
6734 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006735 // The re-offers should respect the order of m= sections in current
6736 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006737 // With a re-offer, either the current local or current remote descriptions
6738 // could be the most up to date, so we would like to check against both of
6739 // them if they exist. It could be the case that one of them has a 0 port
6740 // for a media section, but the other does not. This is important to check
6741 // against in the case that we are recycling an m= section.
6742 const cricket::SessionDescription* current_desc = nullptr;
6743 const cricket::SessionDescription* secondary_current_desc = nullptr;
6744 if (local_description()) {
6745 current_desc = local_description()->description();
6746 if (remote_description()) {
6747 secondary_current_desc = remote_description()->description();
6748 }
6749 } else if (remote_description()) {
6750 current_desc = remote_description()->description();
6751 }
Steve Anton75737c02017-11-06 10:37:17 -08006752 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006753 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6754 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006755 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6756 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006757 }
6758 }
6759
Steve Antonba42e992018-04-09 14:10:01 -07006760 if (IsUnifiedPlan()) {
6761 // Ensure that each audio and video media section has at most one
6762 // "StreamParams". This will return an error if receiving a session
6763 // description from a "Plan B" endpoint which adds multiple tracks of the
6764 // same type. With Unified Plan, there can only be at most one track per
6765 // media section.
6766 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006767 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006768 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6769 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6770 desc.streams().size() > 1u) {
6771 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6772 "Media section has more than one track specified "
6773 "with a=ssrc lines which is not supported with "
6774 "Unified Plan.");
6775 }
6776 }
6777 }
6778
Steve Anton8a006912017-12-04 15:25:56 -08006779 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006780}
6781
Steve Anton3828c062017-12-06 10:34:51 -08006782bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006783 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006784 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006785 return (state == PeerConnectionInterface::kStable) ||
6786 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006787 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006788 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006789 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6790 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6791 }
6792}
6793
Steve Anton3828c062017-12-06 10:34:51 -08006794bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006795 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006796 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006797 return (state == PeerConnectionInterface::kStable) ||
6798 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006799 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006800 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006801 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6802 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6803 }
6804}
6805
Steve Antonf8470812017-12-04 10:46:21 -08006806const char* PeerConnection::SessionErrorToString(SessionError error) const {
6807 switch (error) {
6808 case SessionError::kNone:
6809 return "ERROR_NONE";
6810 case SessionError::kContent:
6811 return "ERROR_CONTENT";
6812 case SessionError::kTransport:
6813 return "ERROR_TRANSPORT";
6814 }
6815 RTC_NOTREACHED();
6816 return "";
6817}
6818
Steve Anton75737c02017-11-06 10:37:17 -08006819std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006820 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006821 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6822 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006823 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006824}
6825
Steve Anton8e20f172018-03-06 10:55:04 -08006826void PeerConnection::ReportSdpFormatReceived(
6827 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006828 int num_audio_mlines = 0;
6829 int num_video_mlines = 0;
6830 int num_audio_tracks = 0;
6831 int num_video_tracks = 0;
6832 for (const ContentInfo& content : remote_offer.description()->contents()) {
6833 cricket::MediaType media_type = content.media_description()->type();
6834 int num_tracks = std::max(
6835 1, static_cast<int>(content.media_description()->streams().size()));
6836 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6837 num_audio_mlines += 1;
6838 num_audio_tracks += num_tracks;
6839 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6840 num_video_mlines += 1;
6841 num_video_tracks += num_tracks;
6842 }
6843 }
6844 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6845 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6846 format = kSdpFormatReceivedComplexUnifiedPlan;
6847 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6848 format = kSdpFormatReceivedComplexPlanB;
6849 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6850 format = kSdpFormatReceivedSimple;
6851 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006852 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6853 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006854}
6855
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006856void PeerConnection::NoteUsageEvent(UsageEvent event) {
6857 RTC_DCHECK_RUN_ON(signaling_thread());
6858 usage_event_accumulator_ |= static_cast<int>(event);
6859}
6860
6861void PeerConnection::ReportUsagePattern() const {
6862 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006863 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6864 usage_event_accumulator_,
6865 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006866 const int bad_bits =
6867 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6868 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6869 const int good_bits =
6870 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6871 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6872 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6873 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6874 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006875 // If called after close(), we can't report, because observer may have
6876 // been deallocated, and therefore pointer is null. Write to log instead.
6877 if (observer_) {
6878 Observer()->OnInterestingUsage(usage_event_accumulator_);
6879 } else {
6880 RTC_LOG(LS_INFO) << "Interesting usage signature "
6881 << usage_event_accumulator_
6882 << " observed after observer shutdown";
6883 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006884 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006885}
6886
Steve Anton0ffaaa22018-02-23 10:31:30 -08006887void PeerConnection::ReportNegotiatedSdpSemantics(
6888 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006889 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006890 switch (answer.description()->msid_signaling()) {
6891 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006892 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006893 break;
6894 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006895 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006896 break;
6897 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006898 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006899 break;
6900 case cricket::kMsidSignalingMediaSection |
6901 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006902 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006903 break;
6904 default:
6905 RTC_NOTREACHED();
6906 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006907 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6908 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006909}
6910
Steve Anton75737c02017-11-06 10:37:17 -08006911// We need to check the local/remote description for the Transport instead of
6912// the session, because a new Transport added during renegotiation may have
6913// them unset while the session has them set from the previous negotiation.
6914// Not doing so may trigger the auto generation of transport description and
6915// mess up DTLS identity information, ICE credential, etc.
6916bool PeerConnection::ReadyToUseRemoteCandidate(
6917 const IceCandidateInterface* candidate,
6918 const SessionDescriptionInterface* remote_desc,
6919 bool* valid) {
6920 *valid = true;
6921
6922 const SessionDescriptionInterface* current_remote_desc =
6923 remote_desc ? remote_desc : remote_description();
6924
6925 if (!current_remote_desc) {
6926 return false;
6927 }
6928
Guido Urdaneta41633172019-05-23 20:12:29 +02006929 RTCErrorOr<const cricket::ContentInfo*> result =
6930 FindContentInfo(current_remote_desc, candidate);
6931 if (!result.ok()) {
6932 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6933 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006934
6935 *valid = false;
6936 return false;
6937 }
6938
Guido Urdaneta41633172019-05-23 20:12:29 +02006939 std::string transport_name = GetTransportName(result.value()->name);
6940 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006941}
6942
6943bool PeerConnection::SrtpRequired() const {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006944 return !configuration_.use_datagram_transport &&
6945 (dtls_enabled_ ||
6946 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006947}
6948
6949void PeerConnection::OnTransportControllerGatheringState(
6950 cricket::IceGatheringState state) {
6951 RTC_DCHECK(signaling_thread()->IsCurrent());
6952 if (state == cricket::kIceGatheringGathering) {
6953 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6954 } else if (state == cricket::kIceGatheringComplete) {
6955 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6956 }
6957}
6958
6959void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006960 std::map<std::string, std::set<cricket::MediaType>>
6961 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006962 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006963 if (transceiver->internal()->channel()) {
6964 const std::string& transport_name =
6965 transceiver->internal()->channel()->transport_name();
6966 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006967 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006968 }
Steve Anton75737c02017-11-06 10:37:17 -08006969 }
6970 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006971 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6972 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006973 }
Zhi Huange830e682018-03-30 10:48:35 -07006974
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006975 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006976 if (transport_name) {
6977 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006978 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006979 }
Zhi Huange830e682018-03-30 10:48:35 -07006980
Steve Antonc7b964c2018-02-01 14:39:45 -08006981 for (const auto& entry : media_types_by_transport_name) {
6982 const std::string& transport_name = entry.first;
6983 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006984 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006985 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006986 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006987 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006988 }
6989 }
6990}
6991// Walk through the ConnectionInfos to gather best connection usage
6992// for IPv4 and IPv6.
6993void PeerConnection::ReportBestConnectionState(
6994 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006995 for (const cricket::TransportChannelStats& channel_stats :
6996 stats.channel_stats) {
6997 for (const cricket::ConnectionInfo& connection_info :
6998 channel_stats.connection_infos) {
6999 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007000 continue;
7001 }
7002
Steve Antonc7b964c2018-02-01 14:39:45 -08007003 const cricket::Candidate& local = connection_info.local_candidate;
7004 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007005
7006 // Increment the counter for IceCandidatePairType.
7007 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7008 (local.type() == RELAY_PORT_TYPE &&
7009 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007010 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7011 GetIceCandidatePairCounter(local, remote),
7012 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007013 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007014 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7015 GetIceCandidatePairCounter(local, remote),
7016 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007017 } else {
7018 RTC_CHECK(0);
7019 }
Steve Anton75737c02017-11-06 10:37:17 -08007020
7021 // Increment the counter for IP type.
7022 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007023 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7024 kBestConnections_IPv4,
7025 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007026 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007027 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7028 kBestConnections_IPv6,
7029 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007030 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007031 RTC_CHECK(!local.address().hostname().empty() &&
7032 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007033 }
7034
7035 return;
7036 }
7037 }
7038}
7039
7040void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007041 const cricket::TransportStats& stats,
7042 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007043 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7044 return;
7045 }
7046
7047 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7048 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7049 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7050 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7051 return;
7052 }
7053
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007054 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7055 for (cricket::MediaType media_type : media_types) {
7056 switch (media_type) {
7057 case cricket::MEDIA_TYPE_AUDIO:
7058 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7059 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7060 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7061 break;
7062 case cricket::MEDIA_TYPE_VIDEO:
7063 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7064 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7065 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7066 break;
7067 case cricket::MEDIA_TYPE_DATA:
7068 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7069 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7070 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7071 break;
7072 default:
7073 RTC_NOTREACHED();
7074 continue;
7075 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007076 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007077 }
7078
7079 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7080 for (cricket::MediaType media_type : media_types) {
7081 switch (media_type) {
7082 case cricket::MEDIA_TYPE_AUDIO:
7083 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7084 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7085 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7086 break;
7087 case cricket::MEDIA_TYPE_VIDEO:
7088 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7089 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7090 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7091 break;
7092 case cricket::MEDIA_TYPE_DATA:
7093 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7094 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7095 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7096 break;
7097 default:
7098 RTC_NOTREACHED();
7099 continue;
7100 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007101 }
Steve Anton75737c02017-11-06 10:37:17 -08007102 }
7103}
7104
7105void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007106 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007107 RTC_DCHECK(call_);
7108 call_->OnSentPacket(sent_packet);
7109}
7110
7111const std::string PeerConnection::GetTransportName(
7112 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007113 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007114 if (channel) {
7115 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007116 }
Steve Anton6fec8802017-12-04 10:37:29 -08007117 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007118 RTC_DCHECK(sctp_mid_);
7119 if (content_name == *sctp_mid_) {
7120 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007121 }
7122 }
7123 // Return an empty string if failed to retrieve the transport name.
7124 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007125}
7126
Steve Anton6fec8802017-12-04 10:37:29 -08007127void PeerConnection::DestroyTransceiverChannel(
7128 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7129 transceiver) {
7130 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007131
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007132 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007133 if (channel) {
7134 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007135 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007136 }
7137}
7138
7139void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007140 if (rtp_data_channel_) {
7141 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007142 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007143 rtp_data_channel_ = nullptr;
7144 }
7145
7146 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7147 // grab a reference to this PeerConnection. If this is called from the
7148 // PeerConnection destructor, the RefCountedObject vtable will have already
7149 // been destroyed (since it is a subclass of PeerConnection) and using
7150 // rtc::Bind will cause "Pure virtual function called" error to appear.
7151
7152 if (sctp_transport_) {
7153 OnDataChannelDestroyed();
7154 network_thread()->Invoke<void>(RTC_FROM_HERE,
7155 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007156 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007157 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007158
7159 if (media_transport_) {
7160 OnDataChannelDestroyed();
7161 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7162 RTC_DCHECK_RUN_ON(network_thread());
7163 TeardownMediaTransportForDataChannels_n();
7164 });
7165 }
Steve Anton6fec8802017-12-04 10:37:29 -08007166}
7167
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007168void PeerConnection::DestroyChannelInterface(
7169 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007170 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007171 switch (channel->media_type()) {
7172 case cricket::MEDIA_TYPE_AUDIO:
7173 channel_manager()->DestroyVoiceChannel(
7174 static_cast<cricket::VoiceChannel*>(channel));
7175 break;
7176 case cricket::MEDIA_TYPE_VIDEO:
7177 channel_manager()->DestroyVideoChannel(
7178 static_cast<cricket::VideoChannel*>(channel));
7179 break;
7180 case cricket::MEDIA_TYPE_DATA:
7181 channel_manager()->DestroyRtpDataChannel(
7182 static_cast<cricket::RtpDataChannel*>(channel));
7183 break;
7184 default:
7185 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7186 break;
7187 }
Zhi Huange830e682018-03-30 10:48:35 -07007188}
Steve Anton6fec8802017-12-04 10:37:29 -08007189
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007190bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007191 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007192 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007193 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007194 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007195 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007196 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007197 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007198 auto base_channel = GetChannel(mid);
7199 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007200 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007201 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007202 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007203 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007204 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007205
Karl Wiberg5966c502019-02-21 23:55:09 +01007206 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007207 // Only pass media transport to call object if media transport is used
7208 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007209 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007210 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007211
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007212 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007213}
7214
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007215void PeerConnection::OnSetStreams() {
7216 RTC_DCHECK_RUN_ON(signaling_thread());
7217 if (IsUnifiedPlan())
7218 UpdateNegotiationNeeded();
7219}
7220
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007221PeerConnectionObserver* PeerConnection::Observer() const {
7222 // In earlier production code, the pointer was not cleared on close,
7223 // which might have led to undefined behavior if the observer was not
7224 // deallocated, or strange crashes if it was.
7225 // We use CHECK in order to catch such behavior if it exists.
7226 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7227 RTC_CHECK(observer_);
7228 return observer_;
7229}
7230
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007231CryptoOptions PeerConnection::GetCryptoOptions() {
7232 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7233 // after it has been removed.
7234 return configuration_.crypto_options.has_value()
7235 ? *configuration_.crypto_options
7236 : factory_->options().crypto_options;
7237}
7238
Harald Alvestrand89061872018-01-02 14:08:34 +01007239void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007240 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007241 if (stats_collector_) {
7242 stats_collector_->ClearCachedStatsReport();
7243 }
7244}
7245
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007246void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007247 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7248 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007249}
7250
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007251void PeerConnection::UpdateNegotiationNeeded() {
7252 RTC_DCHECK_RUN_ON(signaling_thread());
7253 if (!IsUnifiedPlan()) {
7254 Observer()->OnRenegotiationNeeded();
7255 return;
7256 }
7257
7258 // If connection's [[IsClosed]] slot is true, abort these steps.
7259 if (IsClosed())
7260 return;
7261
7262 // If connection's signaling state is not "stable", abort these steps.
7263 if (signaling_state() != kStable)
7264 return;
7265
7266 // NOTE
7267 // The negotiation-needed flag will be updated once the state transitions to
7268 // "stable", as part of the steps for setting an RTCSessionDescription.
7269
7270 // If the result of checking if negotiation is needed is false, clear the
7271 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7272 // to false, and abort these steps.
7273 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7274 if (!is_negotiation_needed) {
7275 is_negotiation_needed_ = false;
7276 return;
7277 }
7278
7279 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7280 // steps.
7281 if (is_negotiation_needed_)
7282 return;
7283
7284 // Set connection's [[NegotiationNeeded]] slot to true.
7285 is_negotiation_needed_ = true;
7286
7287 // Queue a task that runs the following steps:
7288 // If connection's [[IsClosed]] slot is true, abort these steps.
7289 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7290 // Fire an event named negotiationneeded at connection.
7291 Observer()->OnRenegotiationNeeded();
7292}
7293
7294bool PeerConnection::CheckIfNegotiationIsNeeded() {
7295 RTC_DCHECK_RUN_ON(signaling_thread());
7296 // 1. If any implementation-specific negotiation is required, as described at
7297 // the start of this section, return true.
7298
7299 // 2. Let description be connection.[[CurrentLocalDescription]].
7300 const SessionDescriptionInterface* description = current_local_description();
7301 if (!description)
7302 return true;
7303
7304 // 3. If connection has created any RTCDataChannels, and no m= section in
7305 // description has been negotiated yet for data, return true.
7306 if (!sctp_data_channels_.empty()) {
7307 if (!cricket::GetFirstDataContent(description->description()->contents()))
7308 return true;
7309 }
7310
7311 // 4. For each transceiver in connection's set of transceivers, perform the
7312 // following checks:
7313 for (const auto& transceiver : transceivers_) {
7314 const ContentInfo* current_local_msection =
7315 FindTransceiverMSection(transceiver.get(), description);
7316
7317 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7318 transceiver.get(), current_remote_description());
7319
7320 // 4.3 If transceiver is stopped and is associated with an m= section,
7321 // but the associated m= section is not yet rejected in
7322 // connection.[[CurrentLocalDescription]] or
7323 // connection.[[CurrentRemoteDescription]], return true.
7324 if (transceiver->stopped()) {
7325 if (current_local_msection && !current_local_msection->rejected &&
7326 ((current_remote_msection && !current_remote_msection->rejected) ||
7327 !current_remote_msection)) {
7328 return true;
7329 }
7330 continue;
7331 }
7332
7333 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7334 // section in description, return true.
7335 if (!current_local_msection)
7336 return true;
7337
7338 const MediaContentDescription* current_local_media_description =
7339 current_local_msection->media_description();
7340 // 4.2 If transceiver isn't stopped and is associated with an m= section
7341 // in description then perform the following checks:
7342
7343 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7344 // associated m= section in description either doesn't contain a single
7345 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7346 // m= section, or the MSID values themselves, differ from what is in
7347 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7348 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7349 if (current_local_media_description->streams().size() == 0)
7350 return true;
7351
7352 std::vector<std::string> msection_msids;
7353 for (const auto& stream : current_local_media_description->streams()) {
7354 for (const std::string& msid : stream.stream_ids())
7355 msection_msids.push_back(msid);
7356 }
7357
7358 std::vector<std::string> transceiver_msids =
7359 transceiver->sender()->stream_ids();
7360 if (msection_msids.size() != transceiver_msids.size())
7361 return true;
7362
7363 absl::c_sort(transceiver_msids);
7364 absl::c_sort(msection_msids);
7365 if (transceiver_msids != msection_msids)
7366 return true;
7367 }
7368
7369 // 4.2.2 If description is of type "offer", and the direction of the
7370 // associated m= section in neither connection.[[CurrentLocalDescription]]
7371 // nor connection.[[CurrentRemoteDescription]] matches
7372 // transceiver.[[Direction]], return true.
7373 if (description->GetType() == SdpType::kOffer) {
7374 if (!current_remote_description())
7375 return true;
7376
7377 if (!current_remote_msection)
7378 return true;
7379
7380 RtpTransceiverDirection current_local_direction =
7381 current_local_media_description->direction();
7382 RtpTransceiverDirection current_remote_direction =
7383 current_remote_msection->media_description()->direction();
7384 if (transceiver->direction() != current_local_direction &&
7385 transceiver->direction() !=
7386 RtpTransceiverDirectionReversed(current_remote_direction)) {
7387 return true;
7388 }
7389 }
7390
7391 // 4.2.3 If description is of type "answer", and the direction of the
7392 // associated m= section in the description does not match
7393 // transceiver.[[Direction]] intersected with the offered direction (as
7394 // described in [JSEP] (section 5.3.1.)), return true.
7395 if (description->GetType() == SdpType::kAnswer) {
7396 if (!remote_description())
7397 return true;
7398
7399 const ContentInfo* offered_remote_msection =
7400 FindTransceiverMSection(transceiver.get(), remote_description());
7401
7402 RtpTransceiverDirection offered_direction =
7403 offered_remote_msection
7404 ? offered_remote_msection->media_description()->direction()
7405 : RtpTransceiverDirection::kInactive;
7406
7407 if (current_local_media_description->direction() !=
7408 (RtpTransceiverDirectionIntersection(
7409 transceiver->direction(),
7410 RtpTransceiverDirectionReversed(offered_direction)))) {
7411 return true;
7412 }
7413 }
7414 }
7415
7416 // If all the preceding checks were performed and true was not returned,
7417 // nothing remains to be negotiated; return false.
7418 return false;
7419}
7420
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007421} // namespace webrtc