blob: dcb6c8a67a57aa1cb90417626a7e9f3296dcc922 [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()) {
655 if (!content.description) {
656 continue;
657 }
658 has_spec_compliant |= content.description->HasSimulcast();
659 for (const StreamParams& sp : content.description->streams()) {
660 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;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200752 absl::optional<int> ice_check_interval_strong_connectivity;
753 absl::optional<int> ice_check_interval_weak_connectivity;
754 absl::optional<int> ice_check_min_interval;
755 absl::optional<int> ice_unwritable_timeout;
756 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800757 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200758 absl::optional<int> stun_candidate_keepalive_interval;
759 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200760 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800761 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200762 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700763 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700764 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700765 bool use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700766 bool use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700767 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100768 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800769 };
770 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
771 "Did you add something to RTCConfiguration and forget to "
772 "update operator==?");
773 return type == o.type && servers == o.servers &&
774 bundle_policy == o.bundle_policy &&
775 rtcp_mux_policy == o.rtcp_mux_policy &&
776 tcp_candidate_policy == o.tcp_candidate_policy &&
777 candidate_network_policy == o.candidate_network_policy &&
778 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
779 audio_jitter_buffer_fast_accelerate ==
780 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100781 audio_jitter_buffer_min_delay_ms ==
782 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100783 audio_jitter_buffer_enable_rtx_handling ==
784 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800785 ice_connection_receiving_timeout ==
786 o.ice_connection_receiving_timeout &&
787 ice_backup_candidate_pair_ping_interval ==
788 o.ice_backup_candidate_pair_ping_interval &&
789 continual_gathering_policy == o.continual_gathering_policy &&
790 certificates == o.certificates &&
791 prioritize_most_likely_ice_candidate_pairs ==
792 o.prioritize_most_likely_ice_candidate_pairs &&
793 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800794 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700795 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100796 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800797 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800798 screencast_min_bitrate == o.screencast_min_bitrate &&
799 combined_audio_video_bwe == o.combined_audio_video_bwe &&
800 enable_dtls_srtp == o.enable_dtls_srtp &&
801 ice_candidate_pool_size == o.ice_candidate_pool_size &&
802 prune_turn_ports == o.prune_turn_ports &&
803 presume_writable_when_fully_relayed ==
804 o.presume_writable_when_fully_relayed &&
805 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800806 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800807 ice_check_interval_strong_connectivity ==
808 o.ice_check_interval_strong_connectivity &&
809 ice_check_interval_weak_connectivity ==
810 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700811 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700812 ice_unwritable_timeout == o.ice_unwritable_timeout &&
813 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800814 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800815 stun_candidate_keepalive_interval ==
816 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200817 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800818 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800819 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700820 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700821 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700822 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700823 use_media_transport_for_data_channels ==
824 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700825 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100826 crypto_options == o.crypto_options &&
827 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800828}
829
830bool PeerConnectionInterface::RTCConfiguration::operator!=(
831 const PeerConnectionInterface::RTCConfiguration& o) const {
832 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800833}
834
zhihuang8f65cdf2016-05-06 18:40:30 -0700835// Generate a RTCP CNAME when a PeerConnection is created.
836std::string GenerateRtcpCname() {
837 std::string cname;
838 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100839 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800840 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700841 }
842 return cname;
843}
844
zhihuang1c378ed2017-08-17 14:10:50 -0700845bool ValidateOfferAnswerOptions(
846 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
847 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
848 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700849}
850
zhihuang1c378ed2017-08-17 14:10:50 -0700851// From |rtc_options|, fill parts of |session_options| shared by all generated
852// m= sections (in other words, nothing that involves a map/array).
853void ExtractSharedMediaSessionOptions(
854 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
855 cricket::MediaSessionOptions* session_options) {
856 session_options->vad_enabled = rtc_options.voice_activity_detection;
857 session_options->bundle_enabled = rtc_options.use_rtp_mux;
858}
zhihuanga77e6bb2017-08-14 18:17:48 -0700859
zhihuang38ede132017-06-15 12:52:32 -0700860PeerConnection::PeerConnection(PeerConnectionFactory* factory,
861 std::unique_ptr<RtcEventLog> event_log,
862 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000863 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700864 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100865 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700866 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700867 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700868 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100869 call_(std::move(call)),
870 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871
872PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100873 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800874 RTC_DCHECK_RUN_ON(signaling_thread());
875
Steve Anton8af21862017-12-15 11:20:13 -0800876 // Need to stop transceivers before destroying the stats collector because
877 // AudioRtpSender has a reference to the StatsCollector it will update when
878 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100879 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800880 transceiver->Stop();
881 }
Steve Anton4171afb2017-11-20 10:20:22 -0800882
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700883 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800884 if (stats_collector_) {
885 stats_collector_->WaitForPendingRequest();
886 stats_collector_ = nullptr;
887 }
Steve Anton75737c02017-11-06 10:37:17 -0800888
Steve Anton8af21862017-12-15 11:20:13 -0800889 // Don't destroy BaseChannels until after stats has been cleaned up so that
890 // the last stats request can still read from the channels.
891 DestroyAllChannels();
892
Mirko Bonadei675513b2017-11-09 11:09:25 +0100893 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800894
895 webrtc_session_desc_factory_.reset();
896 sctp_invoker_.reset();
897 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800898 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800899 transport_controller_.reset();
900
deadbeef91dd5672016-05-18 16:55:30 -0700901 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100902 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
903 RTC_DCHECK_RUN_ON(network_thread());
904 port_allocator_.reset();
905 });
eladalon248fd4f2017-09-06 05:18:15 -0700906 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700907 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100908 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700909 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800910 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700911 event_log_.reset();
912 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913}
914
Steve Anton8af21862017-12-15 11:20:13 -0800915void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800916 // Destroy video channels first since they may have a pointer to a voice
917 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100918 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800919 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800920 DestroyTransceiverChannel(transceiver);
921 }
922 }
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_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800925 DestroyTransceiverChannel(transceiver);
926 }
927 }
928 DestroyDataChannel();
929}
930
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000932 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700933 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100934 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100935 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100936 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700937
938 RTCError config_error = ValidateConfiguration(configuration);
939 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100940 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700941 return false;
942 }
943
Benjamin Wrightcab58882018-05-02 15:12:47 -0700944 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100945 RTC_LOG(LS_ERROR)
946 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100947 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800948 return false;
949 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200950
Benjamin Wrightcab58882018-05-02 15:12:47 -0700951 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800952 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100953 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100954 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800955 return false;
956 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700957
Benjamin Wrightcab58882018-05-02 15:12:47 -0700958 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700959 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700960 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700961 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800962
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200963 cricket::ServerAddresses stun_servers;
964 std::vector<cricket::RelayServerConfig> turn_servers;
965
966 RTCErrorType parse_error =
967 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
968 if (parse_error != RTCErrorType::NONE) {
969 return false;
970 }
971
deadbeef91dd5672016-05-18 16:55:30 -0700972 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700973 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100974 const auto pa_result =
975 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200976 RTC_FROM_HERE,
977 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100978 stun_servers, turn_servers, configuration));
979
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200980 // If initialization was successful, note if STUN or TURN servers
981 // were supplied.
982 if (!stun_servers.empty()) {
983 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
984 }
985 if (!turn_servers.empty()) {
986 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
987 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700989 // Send information about IPv4/IPv6 status.
990 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +0100991 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700992 address_family = kPeerConnection_IPv6;
993 } else {
994 address_family = kPeerConnection_IPv4;
995 }
996 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
997 kPeerConnectionAddressFamilyCounter_Max);
998
Zhi Huange830e682018-03-30 10:48:35 -0700999 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1000
Steve Anton75737c02017-11-06 10:37:17 -08001001 // RFC 3264: The numeric value of the session id and version in the
1002 // o line MUST be representable with a "64 bit signed integer".
1003 // Due to this constraint session id |session_id_| is max limited to
1004 // LLONG_MAX.
1005 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001006 JsepTransportController::Config config;
1007 config.redetermine_role_on_ice_restart =
1008 configuration.redetermine_role_on_ice_restart;
1009 config.ssl_max_version = factory_->options().ssl_max_version;
1010 config.disable_encryption = options.disable_encryption;
1011 config.bundle_policy = configuration.bundle_policy;
1012 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001013 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1014 // stub.
1015 config.crypto_options = configuration.crypto_options.has_value()
1016 ? *configuration.crypto_options
1017 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001018 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001019 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001020#if defined(ENABLE_EXTERNAL_AUTH)
1021 config.enable_external_auth = true;
1022#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001023 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001024
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001025 if (configuration.use_datagram_transport ||
1026 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001027 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001028 if (!factory_->media_transport_factory()) {
1029 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001030 << "PeerConnecton is initialized with use_media_transport = true or "
1031 << "use_media_transport_for_data_channels = true "
1032 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001033 return false;
1034 }
1035
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001036 if (configuration.use_media_transport ||
1037 configuration.use_media_transport_for_data_channels) {
1038 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1039 // RTP media transport is introduced. But until then, we require SDES to
1040 // be enabled.
1041 if (configuration.enable_dtls_srtp.has_value() &&
1042 configuration.enable_dtls_srtp.value()) {
1043 RTC_LOG(LS_WARNING)
1044 << "When media transport is used, SDES must be enabled. Set "
1045 "configuration.enable_dtls_srtp to false. use_media_transport="
1046 << configuration.use_media_transport
1047 << ", use_media_transport_for_data_channels="
1048 << configuration.use_media_transport_for_data_channels;
1049 return false;
1050 }
1051 }
1052
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001053 config.use_media_transport_for_media = configuration.use_media_transport;
1054 config.use_media_transport_for_data_channels =
1055 configuration.use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001056 config.use_datagram_transport = configuration.use_datagram_transport;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001057 config.media_transport_factory = factory_->media_transport_factory();
1058 }
1059
Zhi Huange830e682018-03-30 10:48:35 -07001060 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001061 signaling_thread(), network_thread(), port_allocator_.get(),
1062 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001063 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001064 this, &PeerConnection::OnTransportControllerConnectionState);
1065 transport_controller_->SignalStandardizedIceConnectionState.connect(
1066 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001067 transport_controller_->SignalConnectionState.connect(
1068 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001069 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001070 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001071 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001072 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001073 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001074 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1075 transport_controller_->SignalDtlsHandshakeError.connect(
1076 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1077
1078 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001079
deadbeefab9b2d12015-10-14 11:33:11 -07001080 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001081 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082
Steve Antonba818672017-11-06 10:21:57 -08001083 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001084 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001085
Steve Anton75737c02017-11-06 10:37:17 -08001086 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1087 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1088 if (!configuration.certificates.empty()) {
1089 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1090 // just picking the first one. The decision should be made based on the DTLS
1091 // handshake. The DTLS negotiations need to know about all certificates.
1092 certificate = configuration.certificates[0];
1093 }
1094
Steve Antond25da372017-11-06 14:50:29 -08001095 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001096
1097 if (options.disable_encryption) {
1098 dtls_enabled_ = false;
1099 } else {
1100 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001101 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001102 // |configuration| can override the default |dtls_enabled_| value.
1103 if (configuration.enable_dtls_srtp) {
1104 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1105 }
1106 }
1107
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001108 if (configuration.use_media_transport_for_data_channels) {
1109 if (configuration.enable_rtp_data_channel) {
1110 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1111 "use_media_transport_for_data_channels are "
1112 "incompatible and cannot both be set to true";
1113 return false;
1114 }
1115 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1116 } else if (configuration.enable_rtp_data_channel) {
1117 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1118 // set. It takes precendence over the disable_sctp_data_channels
1119 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001120 data_channel_type_ = cricket::DCT_RTP;
1121 } else {
1122 // DTLS has to be enabled to use SCTP.
1123 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1124 data_channel_type_ = cricket::DCT_SCTP;
1125 }
1126 }
1127
1128 video_options_.screencast_min_bitrate_kbps =
1129 configuration.screencast_min_bitrate;
1130 audio_options_.combined_audio_video_bwe =
1131 configuration.combined_audio_video_bwe;
1132
1133 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001134 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001135
1136 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001137 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001138
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001139 audio_options_.audio_jitter_buffer_min_delay_ms =
1140 configuration.audio_jitter_buffer_min_delay_ms;
1141
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001142 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1143 configuration.audio_jitter_buffer_enable_rtx_handling;
1144
Steve Anton75737c02017-11-06 10:37:17 -08001145 // Whether the certificate generator/certificate is null or not determines
1146 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1147 // the right instructions by clearing the variables if needed.
1148 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001149 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001150 certificate = nullptr;
1151 } else if (certificate) {
1152 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001153 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001154 }
1155
1156 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1157 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001158 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001159 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1160 this, &PeerConnection::OnCertificateReady);
1161
1162 if (options.disable_encryption) {
1163 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1164 }
1165
1166 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001167 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001168 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169
Steve Anton4171afb2017-11-20 10:20:22 -08001170 // Add default audio/video transceivers for Plan B SDP.
1171 if (!IsUnifiedPlan()) {
1172 transceivers_.push_back(
1173 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1174 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1175 transceivers_.push_back(
1176 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1177 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1178 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001179 int delay_ms =
1180 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001181 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1182 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001183
1184 if (dependencies.video_bitrate_allocator_factory) {
1185 video_bitrate_allocator_factory_ =
1186 std::move(dependencies.video_bitrate_allocator_factory);
1187 } else {
1188 video_bitrate_allocator_factory_ =
1189 CreateBuiltinVideoBitrateAllocatorFactory();
1190 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 return true;
1192}
1193
Steve Anton038834f2017-07-14 15:59:59 -07001194RTCError PeerConnection::ValidateConfiguration(
1195 const RTCConfiguration& config) const {
1196 if (config.ice_regather_interval_range &&
1197 config.continual_gathering_policy == GATHER_ONCE) {
1198 return RTCError(RTCErrorType::INVALID_PARAMETER,
1199 "ice_regather_interval_range specified but continual "
1200 "gathering policy is GATHER_ONCE");
1201 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001202 auto result =
1203 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1204 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001205}
1206
Yves Gerey665174f2018-06-19 15:03:05 +02001207rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001208 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001209 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1210 "Plan SdpSemantics. Please use GetSenders "
1211 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001212 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001213}
1214
Yves Gerey665174f2018-06-19 15:03:05 +02001215rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001216 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001217 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1218 "Plan SdpSemantics. Please use GetReceivers "
1219 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001220 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221}
1222
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001223bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001224 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001225 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1226 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001227 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 if (IsClosed()) {
1229 return false;
1230 }
deadbeefab9b2d12015-10-14 11:33:11 -07001231 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232 return false;
1233 }
deadbeefab9b2d12015-10-14 11:33:11 -07001234
1235 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001236 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1237 observer->SignalAudioTrackAdded.connect(this,
1238 &PeerConnection::OnAudioTrackAdded);
1239 observer->SignalAudioTrackRemoved.connect(
1240 this, &PeerConnection::OnAudioTrackRemoved);
1241 observer->SignalVideoTrackAdded.connect(this,
1242 &PeerConnection::OnVideoTrackAdded);
1243 observer->SignalVideoTrackRemoved.connect(
1244 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001245 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001246
deadbeefab9b2d12015-10-14 11:33:11 -07001247 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001248 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001249 }
1250 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001251 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001252 }
1253
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001254 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001255 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 return true;
1257}
1258
1259void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001260 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001261 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1262 "Plan SdpSemantics. Please use RemoveTrack "
1263 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001264 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001265 if (!IsClosed()) {
1266 for (const auto& track : local_stream->GetAudioTracks()) {
1267 RemoveAudioTrack(track.get(), local_stream);
1268 }
1269 for (const auto& track : local_stream->GetVideoTracks()) {
1270 RemoveVideoTrack(track.get(), local_stream);
1271 }
deadbeefab9b2d12015-10-14 11:33:11 -07001272 }
deadbeefab9b2d12015-10-14 11:33:11 -07001273 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001274 stream_observers_.erase(
1275 std::remove_if(
1276 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001277 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001278 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001279 }),
1280 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001281
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 if (IsClosed()) {
1283 return;
1284 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001285 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286}
1287
Steve Anton2d6c76a2018-01-05 17:10:52 -08001288RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001289 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001290 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001291 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001292 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001293 if (!track) {
1294 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1295 }
1296 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1297 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1299 "Track has invalid kind: " + track->kind());
1300 }
Steve Antonf9381f02017-12-14 10:23:57 -08001301 if (IsClosed()) {
1302 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1303 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001304 }
Steve Anton4171afb2017-11-20 10:20:22 -08001305 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001306 LOG_AND_RETURN_ERROR(
1307 RTCErrorType::INVALID_PARAMETER,
1308 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001309 }
Steve Antonf9381f02017-12-14 10:23:57 -08001310 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001311 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1312 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001313 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001314 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001315 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001316 }
1317 return sender_or_error;
1318}
deadbeefe1f9d832016-01-14 15:35:42 -08001319
Steve Antonf9381f02017-12-14 10:23:57 -08001320RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1321PeerConnection::AddTrackPlanB(
1322 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001323 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001324 if (stream_ids.size() > 1u) {
1325 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1326 "AddTrack with more than one stream is not "
1327 "supported with Plan B semantics.");
1328 }
1329 std::vector<std::string> adjusted_stream_ids = stream_ids;
1330 if (adjusted_stream_ids.empty()) {
1331 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1332 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001333 cricket::MediaType media_type =
1334 (track->kind() == MediaStreamTrackInterface::kAudioKind
1335 ? cricket::MEDIA_TYPE_AUDIO
1336 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001337 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001338 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001339 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001340 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001341 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001342 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001343 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001344 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001345 if (sender_info) {
1346 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001347 }
Steve Antonf9381f02017-12-14 10:23:57 -08001348 } else {
1349 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001350 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001351 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001352 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001353 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001354 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001355 if (sender_info) {
1356 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001357 }
deadbeefe1f9d832016-01-14 15:35:42 -08001358 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001359 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001360}
deadbeefe1f9d832016-01-14 15:35:42 -08001361
Steve Antonf9381f02017-12-14 10:23:57 -08001362RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1363PeerConnection::AddTrackUnifiedPlan(
1364 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001365 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001366 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1367 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001368 RTC_LOG(LS_INFO) << "Reusing an existing "
1369 << cricket::MediaTypeToString(transceiver->media_type())
1370 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001371 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001372 transceiver->internal()->set_direction(
1373 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001374 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001375 transceiver->internal()->set_direction(
1376 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001377 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001378 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001379 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001380 } else {
1381 cricket::MediaType media_type =
1382 (track->kind() == MediaStreamTrackInterface::kAudioKind
1383 ? cricket::MEDIA_TYPE_AUDIO
1384 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001385 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1386 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001387 std::string sender_id = track->id();
1388 // Avoid creating a sender with an existing ID by generating a random ID.
1389 // This can happen if this is the second time AddTrack has created a sender
1390 // for this track.
1391 if (FindSenderById(sender_id)) {
1392 sender_id = rtc::CreateRandomUuid();
1393 }
Florent Castelli892acf02018-10-01 22:47:20 +02001394 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1396 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001397 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001398 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001399 }
Steve Antonf9381f02017-12-14 10:23:57 -08001400 return transceiver->sender();
1401}
1402
1403rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1404PeerConnection::FindFirstTransceiverForAddedTrack(
1405 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1406 RTC_DCHECK(track);
1407 for (auto transceiver : transceivers_) {
1408 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001409 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001410 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001411 !transceiver->internal()->has_ever_been_used_to_send() &&
1412 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001413 return transceiver;
1414 }
1415 }
1416 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001417}
1418
1419bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1420 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001421 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001422}
1423
Steve Anton24db5732018-07-23 10:27:33 -07001424RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001425 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001426 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001427 if (!sender) {
1428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1429 }
deadbeefe1f9d832016-01-14 15:35:42 -08001430 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001431 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1432 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001433 }
Steve Antonf9381f02017-12-14 10:23:57 -08001434 if (IsUnifiedPlan()) {
1435 auto transceiver = FindTransceiverBySender(sender);
1436 if (!transceiver || !sender->track()) {
1437 return RTCError::OK();
1438 }
1439 sender->SetTrack(nullptr);
1440 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001441 transceiver->internal()->set_direction(
1442 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001443 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001444 transceiver->internal()->set_direction(
1445 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001446 }
Steve Anton4171afb2017-11-20 10:20:22 -08001447 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001448 bool removed;
1449 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1450 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1451 } else {
1452 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1453 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1454 }
1455 if (!removed) {
1456 LOG_AND_RETURN_ERROR(
1457 RTCErrorType::INVALID_PARAMETER,
1458 "Couldn't find sender " + sender->id() + " to remove.");
1459 }
Steve Anton4171afb2017-11-20 10:20:22 -08001460 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001461 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001462 return RTCError::OK();
1463}
1464
1465rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1466PeerConnection::FindTransceiverBySender(
1467 rtc::scoped_refptr<RtpSenderInterface> sender) {
1468 for (auto transceiver : transceivers_) {
1469 if (transceiver->sender() == sender) {
1470 return transceiver;
1471 }
1472 }
1473 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001474}
1475
Steve Anton9158ef62017-11-27 13:01:52 -08001476RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1477PeerConnection::AddTransceiver(
1478 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1479 return AddTransceiver(track, RtpTransceiverInit());
1480}
1481
1482RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1483PeerConnection::AddTransceiver(
1484 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1485 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001486 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001487 RTC_CHECK(IsUnifiedPlan())
1488 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001489 if (!track) {
1490 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1491 }
1492 cricket::MediaType media_type;
1493 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1494 media_type = cricket::MEDIA_TYPE_AUDIO;
1495 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1496 media_type = cricket::MEDIA_TYPE_VIDEO;
1497 } else {
1498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1499 "Track kind is not audio or video");
1500 }
1501 return AddTransceiver(media_type, track, init);
1502}
1503
1504RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1505PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1506 return AddTransceiver(media_type, RtpTransceiverInit());
1507}
1508
1509RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1510PeerConnection::AddTransceiver(cricket::MediaType media_type,
1511 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001512 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001513 RTC_CHECK(IsUnifiedPlan())
1514 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001515 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1516 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1517 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1518 "media type is not audio or video");
1519 }
1520 return AddTransceiver(media_type, nullptr, init);
1521}
1522
1523RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1524PeerConnection::AddTransceiver(
1525 cricket::MediaType media_type,
1526 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001527 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001528 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001529 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1530 media_type == cricket::MEDIA_TYPE_VIDEO));
1531 if (track) {
1532 RTC_DCHECK_EQ(media_type,
1533 (track->kind() == MediaStreamTrackInterface::kAudioKind
1534 ? cricket::MEDIA_TYPE_AUDIO
1535 : cricket::MEDIA_TYPE_VIDEO));
1536 }
1537
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001538 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1539 init.send_encodings.size(), 0, 7, 8);
1540
Amit Hilbuchaa584152019-02-06 17:09:52 -08001541 size_t num_rids = absl::c_count_if(init.send_encodings,
1542 [](const RtpEncodingParameters& encoding) {
1543 return !encoding.rid.empty();
1544 });
1545 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001546 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001547 RTCErrorType::INVALID_PARAMETER,
1548 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001549 }
1550
Amit Hilbuchf4770402019-04-08 14:11:57 -07001551 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1552 [](const RtpEncodingParameters& encoding) {
1553 return !IsLegalRsidName(encoding.rid);
1554 })) {
1555 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1556 "Invalid RID value provided.");
1557 }
1558
Amit Hilbuchaa584152019-02-06 17:09:52 -08001559 if (absl::c_any_of(init.send_encodings,
1560 [](const RtpEncodingParameters& encoding) {
1561 return encoding.ssrc.has_value();
1562 })) {
1563 LOG_AND_RETURN_ERROR(
1564 RTCErrorType::UNSUPPORTED_PARAMETER,
1565 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001566 }
1567
1568 RtpParameters parameters;
1569 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001570
1571 // Encodings are dropped from the tail if too many are provided.
1572 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1573 parameters.encodings.erase(
1574 parameters.encodings.begin() + kMaxSimulcastStreams,
1575 parameters.encodings.end());
1576 }
1577
1578 // Single RID should be removed.
1579 if (parameters.encodings.size() == 1 &&
1580 !parameters.encodings[0].rid.empty()) {
1581 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1582 parameters.encodings[0].rid.clear();
1583 }
1584
1585 // If RIDs were not provided, they are generated for simulcast scenario.
1586 if (parameters.encodings.size() > 1 && num_rids == 0) {
1587 rtc::UniqueStringGenerator rid_generator;
1588 for (RtpEncodingParameters& encoding : parameters.encodings) {
1589 encoding.rid = rid_generator();
1590 }
1591 }
1592
Florent Castelli892acf02018-10-01 22:47:20 +02001593 if (UnimplementedRtpParameterHasValue(parameters)) {
1594 LOG_AND_RETURN_ERROR(
1595 RTCErrorType::UNSUPPORTED_PARAMETER,
1596 "Attempted to set an unimplemented parameter of RtpParameters.");
1597 }
Steve Anton9158ef62017-11-27 13:01:52 -08001598
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001599 auto result = cricket::CheckRtpParametersValues(parameters);
1600 if (!result.ok()) {
1601 LOG_AND_RETURN_ERROR(result.type(), result.message());
1602 }
1603
Steve Anton3d954a62018-04-02 11:27:23 -07001604 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1605 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001606 // Set the sender ID equal to the track ID if the track is specified unless
1607 // that sender ID is already in use.
1608 std::string sender_id =
1609 (track && !FindSenderById(track->id()) ? track->id()
1610 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001611 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001612 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001613 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1614 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1615 transceiver->internal()->set_direction(init.direction);
1616
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001617 if (update_negotiation_needed) {
1618 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001619 }
Steve Antonf9381f02017-12-14 10:23:57 -08001620
1621 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1622}
1623
Steve Anton02ee47c2018-01-10 16:26:06 -08001624rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1625PeerConnection::CreateSender(
1626 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001627 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001628 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001629 const std::vector<std::string>& stream_ids,
1630 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001631 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001632 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001633 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1634 RTC_DCHECK(!track ||
1635 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1636 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1637 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001638 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001639 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001640 } else {
1641 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1642 RTC_DCHECK(!track ||
1643 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1644 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001645 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001646 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001647 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001648 bool set_track_succeeded = sender->SetTrack(track);
1649 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001650 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001651 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001652 return sender;
1653}
1654
1655rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1656PeerConnection::CreateReceiver(cricket::MediaType media_type,
1657 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001658 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1659 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001660 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001661 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001662 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1663 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001664 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001665 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001666 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001667 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001668 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1669 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001670 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001671 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001672 return receiver;
1673}
1674
1675rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1676PeerConnection::CreateAndAddTransceiver(
1677 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1678 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1679 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001680 // Ensure that the new sender does not have an ID that is already in use by
1681 // another sender.
1682 // Allow receiver IDs to conflict since those come from remote SDP (which
1683 // could be invalid, but should not cause a crash).
1684 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001685 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001686 signaling_thread(),
1687 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001688 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001689 transceiver->internal()->SignalNegotiationNeeded.connect(
1690 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001691 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001692}
1693
Steve Anton52d86772018-02-20 15:48:12 -08001694void PeerConnection::OnNegotiationNeeded() {
1695 RTC_DCHECK_RUN_ON(signaling_thread());
1696 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001697 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001698}
1699
deadbeeffac06552015-11-25 11:26:01 -08001700rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001701 const std::string& kind,
1702 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001703 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001704 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1705 "Plan SdpSemantics. Please use AddTransceiver "
1706 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001707 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001708 if (IsClosed()) {
1709 return nullptr;
1710 }
Steve Anton4171afb2017-11-20 10:20:22 -08001711
Seth Hampson5b4f0752018-04-02 16:31:36 -07001712 // Internally we need to have one stream with Plan B semantics, so we
1713 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001714 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001715 if (stream_id.empty()) {
1716 stream_ids.push_back(rtc::CreateRandomUuid());
1717 RTC_LOG(LS_INFO)
1718 << "No stream_id specified for sender. Generated stream ID: "
1719 << stream_ids[0];
1720 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001721 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001722 }
1723
Steve Anton4171afb2017-11-20 10:20:22 -08001724 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001725 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001726 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001727 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001728 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001729 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001730 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001731 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001732 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001733 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001734 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001735 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001736 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001737 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001738 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001739 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001740 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001741 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001742 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001743 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001744 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001745
deadbeefe1f9d832016-01-14 15:35:42 -08001746 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001747}
1748
deadbeef70ab1a12015-09-28 16:53:55 -07001749std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1750 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001751 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001752 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001753 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001754 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001755 }
1756 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001757}
1758
Steve Anton4171afb2017-11-20 10:20:22 -08001759std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1760PeerConnection::GetSendersInternal() const {
1761 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1762 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001763 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001764 auto senders = transceiver->internal()->senders();
1765 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1766 }
1767 return all_senders;
1768}
1769
deadbeef70ab1a12015-09-28 16:53:55 -07001770std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1771PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001772 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001773 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001774 for (const auto& receiver : GetReceiversInternal()) {
1775 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001776 }
1777 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001778}
1779
Steve Anton4171afb2017-11-20 10:20:22 -08001780std::vector<
1781 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1782PeerConnection::GetReceiversInternal() const {
1783 std::vector<
1784 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1785 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001786 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001787 auto receivers = transceiver->internal()->receivers();
1788 all_receivers.insert(all_receivers.end(), receivers.begin(),
1789 receivers.end());
1790 }
1791 return all_receivers;
1792}
1793
Steve Anton9158ef62017-11-27 13:01:52 -08001794std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1795PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001796 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001797 RTC_CHECK(IsUnifiedPlan())
1798 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001799 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001800 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001801 all_transceivers.push_back(transceiver);
1802 }
1803 return all_transceivers;
1804}
1805
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001806bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001807 MediaStreamTrackInterface* track,
1808 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001809 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001810 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001811 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001812 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813 return false;
1814 }
1815
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001816 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001817 // The StatsCollector is used to tell if a track is valid because it may
1818 // remember tracks that the PeerConnection previously removed.
1819 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001820 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1821 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001822 return false;
1823 }
Steve Antonad182762018-09-05 20:22:40 +00001824 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1825 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 return true;
1827}
1828
hbos74e1a4f2016-09-15 23:33:01 -07001829void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001830 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001831 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001832 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001833 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001834 stats_collector_->GetStatsReport(callback);
1835}
1836
Henrik Boström1df1bf82018-03-20 13:24:20 +01001837void PeerConnection::GetStats(
1838 rtc::scoped_refptr<RtpSenderInterface> selector,
1839 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1840 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001841 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001842 RTC_DCHECK(callback);
1843 RTC_DCHECK(stats_collector_);
1844 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1845 if (selector) {
1846 for (const auto& proxy_transceiver : transceivers_) {
1847 for (const auto& proxy_sender :
1848 proxy_transceiver->internal()->senders()) {
1849 if (proxy_sender == selector) {
1850 internal_sender = proxy_sender->internal();
1851 break;
1852 }
1853 }
1854 if (internal_sender)
1855 break;
1856 }
1857 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001858 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001859 // belong to the PeerConnection (in Plan B, senders can be removed from the
1860 // PeerConnection). This means that "all the stats objects representing the
1861 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1862 // produces an empty stats report.
1863 stats_collector_->GetStatsReport(internal_sender, callback);
1864}
1865
1866void PeerConnection::GetStats(
1867 rtc::scoped_refptr<RtpReceiverInterface> selector,
1868 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1869 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001870 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001871 RTC_DCHECK(callback);
1872 RTC_DCHECK(stats_collector_);
1873 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1874 if (selector) {
1875 for (const auto& proxy_transceiver : transceivers_) {
1876 for (const auto& proxy_receiver :
1877 proxy_transceiver->internal()->receivers()) {
1878 if (proxy_receiver == selector) {
1879 internal_receiver = proxy_receiver->internal();
1880 break;
1881 }
1882 }
1883 if (internal_receiver)
1884 break;
1885 }
1886 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001887 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001888 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1889 // the PeerConnection). This means that "all the stats objects representing
1890 // the selector" is an empty set. Invoking GetStatsReport() with a null
1891 // selector produces an empty stats report.
1892 stats_collector_->GetStatsReport(internal_receiver, callback);
1893}
1894
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001895PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001896 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897 return signaling_state_;
1898}
1899
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900PeerConnectionInterface::IceConnectionState
1901PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001902 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001903 return ice_connection_state_;
1904}
1905
Alex Loiko9289eda2018-11-23 16:18:59 +00001906PeerConnectionInterface::IceConnectionState
1907PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001908 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001909 return standardized_ice_connection_state_;
1910}
1911
Jonas Olsson635474e2018-10-18 15:58:17 +02001912PeerConnectionInterface::PeerConnectionState
1913PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001914 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001915 return connection_state_;
1916}
1917
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918PeerConnectionInterface::IceGatheringState
1919PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001920 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921 return ice_gathering_state_;
1922}
1923
Yves Gerey665174f2018-06-19 15:03:05 +02001924rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925 const std::string& label,
1926 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001927 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001928 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001929
deadbeefab9b2d12015-10-14 11:33:11 -07001930 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001931
kwibergd1fe2812016-04-27 06:47:29 -07001932 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001933 if (config) {
1934 internal_config.reset(new InternalDataChannelInit(*config));
1935 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001936 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001937 InternalCreateDataChannel(label, internal_config.get()));
1938 if (!channel.get()) {
1939 return nullptr;
1940 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001941
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001942 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1943 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001944 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001945 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001946 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001947 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001948 return DataChannelProxy::Create(signaling_thread(), channel.get());
1949}
1950
1951void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001952 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001953 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001954 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001955
nisse7ce109a2017-01-31 00:57:56 -08001956 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001957 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001958 return;
1959 }
deadbeefab9b2d12015-10-14 11:33:11 -07001960
Steve Anton8d3444d2017-10-20 15:30:51 -07001961 if (IsClosed()) {
1962 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001963 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001964 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001965 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001966 return;
1967 }
1968
zhihuang1c378ed2017-08-17 14:10:50 -07001969 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001970 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001971 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001972 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001973 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001974 return;
1975 }
1976
Steve Anton22da89f2018-01-25 13:58:07 -08001977 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1978 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1979 if (IsUnifiedPlan()) {
1980 RTCError error = HandleLegacyOfferOptions(options);
1981 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001982 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001983 return;
1984 }
1985 }
1986
zhihuang1c378ed2017-08-17 14:10:50 -07001987 cricket::MediaSessionOptions session_options;
1988 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001989 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990}
1991
Steve Anton22da89f2018-01-25 13:58:07 -08001992RTCError PeerConnection::HandleLegacyOfferOptions(
1993 const RTCOfferAnswerOptions& options) {
1994 RTC_DCHECK(IsUnifiedPlan());
1995
1996 if (options.offer_to_receive_audio == 0) {
1997 RemoveRecvDirectionFromReceivingTransceiversOfType(
1998 cricket::MEDIA_TYPE_AUDIO);
1999 } else if (options.offer_to_receive_audio == 1) {
2000 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2001 } else if (options.offer_to_receive_audio > 1) {
2002 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2003 "offer_to_receive_audio > 1 is not supported.");
2004 }
2005
2006 if (options.offer_to_receive_video == 0) {
2007 RemoveRecvDirectionFromReceivingTransceiversOfType(
2008 cricket::MEDIA_TYPE_VIDEO);
2009 } else if (options.offer_to_receive_video == 1) {
2010 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2011 } else if (options.offer_to_receive_video > 1) {
2012 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2013 "offer_to_receive_video > 1 is not supported.");
2014 }
2015
2016 return RTCError::OK();
2017}
2018
2019void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2020 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002021 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002022 RtpTransceiverDirection new_direction =
2023 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2024 if (new_direction != transceiver->direction()) {
2025 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2026 << " transceiver (MID="
2027 << transceiver->mid().value_or("<not set>") << ") from "
2028 << RtpTransceiverDirectionToString(
2029 transceiver->direction())
2030 << " to "
2031 << RtpTransceiverDirectionToString(new_direction)
2032 << " since CreateOffer specified offer_to_receive=0";
2033 transceiver->internal()->set_direction(new_direction);
2034 }
Steve Anton22da89f2018-01-25 13:58:07 -08002035 }
2036}
2037
2038void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2039 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002040 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002041 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002042 RTC_LOG(LS_INFO)
2043 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2044 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002045 RtpTransceiverInit init;
2046 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002047 AddTransceiver(media_type, nullptr, init,
2048 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002049 }
2050}
2051
2052std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2053PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2054 std::vector<
2055 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2056 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002057 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002058 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002059 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2060 receiving_transceivers.push_back(transceiver);
2061 }
2062 }
2063 return receiving_transceivers;
2064}
2065
htaa2a49d92016-03-04 02:51:39 -08002066void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2067 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002068 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002069 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002070 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002071 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002072 return;
2073 }
2074
Steve Antondffead82018-02-06 10:31:29 -08002075 if (!(signaling_state_ == kHaveRemoteOffer ||
2076 signaling_state_ == kHaveLocalPrAnswer)) {
2077 std::string error =
2078 "PeerConnection cannot create an answer in a state other than "
2079 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002080 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002081 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002082 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002083 return;
2084 }
2085
Steve Antondffead82018-02-06 10:31:29 -08002086 // The remote description should be set if we're in the right state.
2087 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002088
Steve Anton22da89f2018-01-25 13:58:07 -08002089 if (IsUnifiedPlan()) {
2090 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2091 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2092 "supported with Unified Plan semantics. Use the "
2093 "RtpTransceiver API instead.";
2094 }
2095 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2096 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2097 "supported with Unified Plan semantics. Use the "
2098 "RtpTransceiver API instead.";
2099 }
2100 }
2101
htaa2a49d92016-03-04 02:51:39 -08002102 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002103 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002104
Steve Antond25da372017-11-06 14:50:29 -08002105 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002106}
2107
2108void PeerConnection::SetLocalDescription(
2109 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002110 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002111 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002112 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002113
Steve Anton80dd7b52018-02-16 17:08:42 -08002114 // The SetLocalDescription contract is that we take ownership of the session
2115 // description regardless of the outcome, so wrap it in a unique_ptr right
2116 // away. Ideally, SetLocalDescription's signature will be changed to take the
2117 // description as a unique_ptr argument to formalize this agreement.
2118 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2119
nisse7ce109a2017-01-31 00:57:56 -08002120 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002121 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122 return;
2123 }
Steve Anton8a006912017-12-04 15:25:56 -08002124
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002126 PostSetSessionDescriptionFailure(
2127 observer,
2128 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129 return;
2130 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002131
Steve Anton80dd7b52018-02-16 17:08:42 -08002132 // If a session error has occurred the PeerConnection is in a possibly
2133 // inconsistent state so fail right away.
2134 if (session_error() != SessionError::kNone) {
2135 std::string error_message = GetSessionErrorMsg();
2136 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002137 PostSetSessionDescriptionFailure(
2138 observer,
2139 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002140 return;
2141 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002142
Steve Anton80dd7b52018-02-16 17:08:42 -08002143 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2144 if (!error.ok()) {
2145 std::string error_message = GetSetDescriptionErrorMessage(
2146 cricket::CS_LOCAL, desc->GetType(), error);
2147 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002148 PostSetSessionDescriptionFailure(
2149 observer,
2150 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 return;
2152 }
2153
2154 // Grab the description type before moving ownership to ApplyLocalDescription,
2155 // which may destroy it before returning.
2156 const SdpType type = desc->GetType();
2157
2158 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002159 // |desc| may be destroyed at this point.
2160
2161 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002162 // If ApplyLocalDescription fails, the PeerConnection could be in an
2163 // inconsistent state, so act conservatively here and set the session error
2164 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2165 SetSessionError(SessionError::kContent, error.message());
2166 std::string error_message =
2167 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2168 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002169 PostSetSessionDescriptionFailure(
2170 observer,
2171 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002172 return;
2173 }
Steve Anton8a006912017-12-04 15:25:56 -08002174 RTC_DCHECK(local_description());
2175
2176 PostSetSessionDescriptionSuccess(observer);
2177
Steve Antonad182762018-09-05 20:22:40 +00002178 // MaybeStartGathering needs to be called after posting
2179 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2180 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002181 transport_controller_->MaybeStartGathering();
2182
Steve Antona3a92c22017-12-07 10:27:41 -08002183 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002184 // TODO(deadbeef): We already had to hop to the network thread for
2185 // MaybeStartGathering...
2186 network_thread()->Invoke<void>(
2187 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2188 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002189 // Make UMA notes about what was agreed to.
2190 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002191 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002192
2193 if (IsUnifiedPlan()) {
2194 bool was_negotiation_needed = is_negotiation_needed_;
2195 UpdateNegotiationNeeded();
2196 if (signaling_state() == kStable && was_negotiation_needed &&
2197 is_negotiation_needed_) {
2198 Observer()->OnRenegotiationNeeded();
2199 }
2200 }
2201
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002202 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002203}
2204
2205RTCError PeerConnection::ApplyLocalDescription(
2206 std::unique_ptr<SessionDescriptionInterface> desc) {
2207 RTC_DCHECK_RUN_ON(signaling_thread());
2208 RTC_DCHECK(desc);
2209
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 // Update stats here so that we have the most recent stats for tracks and
2211 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002212 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002213
Steve Antondcc3c022017-12-22 16:02:54 -08002214 // Take a reference to the old local description since it's used below to
2215 // compare against the new local description. When setting the new local
2216 // description, grab ownership of the replaced session description in case it
2217 // is the same as |old_local_description|, to keep it alive for the duration
2218 // of the method.
2219 const SessionDescriptionInterface* old_local_description =
2220 local_description();
2221 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002222 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002223 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002224 replaced_local_description = pending_local_description_
2225 ? std::move(pending_local_description_)
2226 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002227 current_local_description_ = std::move(desc);
2228 pending_local_description_ = nullptr;
2229 current_remote_description_ = std::move(pending_remote_description_);
2230 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002231 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002232 pending_local_description_ = std::move(desc);
2233 }
2234 // The session description to apply now must be accessed by
2235 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002236 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002237
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002238 // Report statistics about any use of simulcast.
2239 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2240 *local_description()->description());
2241
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002242 if (!is_caller_) {
2243 if (remote_description()) {
2244 // Remote description was applied first, so this PC is the callee.
2245 is_caller_ = false;
2246 } else {
2247 // Local description is applied first, so this PC is the caller.
2248 is_caller_ = true;
2249 }
2250 }
2251
Zhi Huange830e682018-03-30 10:48:35 -07002252 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2253 if (!error.ok()) {
2254 return error;
2255 }
2256
Steve Antondcc3c022017-12-22 16:02:54 -08002257 if (IsUnifiedPlan()) {
2258 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002259 cricket::CS_LOCAL, *local_description(), old_local_description,
2260 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002261 if (!error.ok()) {
2262 return error;
2263 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002264 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2265 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002266 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002267 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2268 // Note that code paths that don't set MID won't be able to use
2269 // information about DTLS transports.
2270 if (transceiver->mid()) {
2271 auto dtls_transport =
2272 LookupDtlsTransportByMidInternal(*transceiver->mid());
2273 transceiver->internal()->sender_internal()->set_transport(
2274 dtls_transport);
2275 transceiver->internal()->receiver_internal()->set_transport(
2276 dtls_transport);
2277 }
2278
Steve Antondcc3c022017-12-22 16:02:54 -08002279 const ContentInfo* content =
2280 FindMediaSectionForTransceiver(transceiver, local_description());
2281 if (!content) {
2282 continue;
2283 }
2284 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002285 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2286 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002287 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002288 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2289 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2290 // "recvonly", process the removal of a remote track for the media
2291 // description, given transceiver, removeList, and muteTracks.
2292 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2293 (transceiver->internal()->fired_direction() &&
2294 RtpTransceiverDirectionHasRecv(
2295 *transceiver->internal()->fired_direction()))) {
2296 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2297 &removed_streams);
2298 }
2299 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2300 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002301 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002302 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002303 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002304 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002305 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002306 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002307 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002308 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002309 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002310 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002311 }
2312 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002313 // Media channels will be created only when offer is set. These may use new
2314 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002315 if (type == SdpType::kOffer) {
2316 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2317 // description is applied. Restore back to old description.
2318 RTCError error = CreateChannels(*local_description()->description());
2319 if (!error.ok()) {
2320 return error;
2321 }
2322 }
Steve Antondcc3c022017-12-22 16:02:54 -08002323 // Remove unused channels if MediaContentDescription is rejected.
2324 RemoveUnusedChannels(local_description()->description());
2325 }
Steve Anton8a006912017-12-04 15:25:56 -08002326
Zhi Huange830e682018-03-30 10:48:35 -07002327 error = UpdateSessionState(type, cricket::CS_LOCAL,
2328 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002329 if (!error.ok()) {
2330 return error;
2331 }
Steve Antondcc3c022017-12-22 16:02:54 -08002332
Steve Anton8a006912017-12-04 15:25:56 -08002333 if (remote_description()) {
2334 // Now that we have a local description, we can push down remote candidates.
2335 UseCandidatesInSessionDescription(remote_description());
2336 }
2337
2338 pending_ice_restarts_.clear();
2339 if (session_error() != SessionError::kNone) {
2340 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2341 }
2342
deadbeefab9b2d12015-10-14 11:33:11 -07002343 // If setting the description decided our SSL role, allocate any necessary
2344 // SCTP sids.
2345 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002346 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002347 AllocateSctpSids(role);
2348 }
2349
Steve Antond3679212018-01-17 17:41:02 -08002350 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002351 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002352 const ContentInfo* content =
2353 FindMediaSectionForTransceiver(transceiver, local_description());
2354 if (!content) {
2355 continue;
2356 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002357 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2358 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002359 // 0 is a special value meaning "this sender has no associated send
2360 // stream". Need to call this so the sender won't attempt to configure
2361 // a no longer existing stream and run into DCHECKs in the lower
2362 // layers.
2363 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002364 } else {
2365 // Get the StreamParams from the channel which could generate SSRCs.
2366 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002367 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002368 streams[0].stream_ids());
2369 transceiver->internal()->sender_internal()->SetSsrc(
2370 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002371 }
2372 }
2373 } else {
2374 // Plan B semantics.
2375
Steve Antondcc3c022017-12-22 16:02:54 -08002376 // Update state and SSRC of local MediaStreams and DataChannels based on the
2377 // local session description.
2378 const cricket::ContentInfo* audio_content =
2379 GetFirstAudioContent(local_description()->description());
2380 if (audio_content) {
2381 if (audio_content->rejected) {
2382 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2383 } else {
2384 const cricket::AudioContentDescription* audio_desc =
2385 audio_content->media_description()->as_audio();
2386 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2387 }
deadbeeffaac4972015-11-12 15:33:07 -08002388 }
deadbeefab9b2d12015-10-14 11:33:11 -07002389
Steve Antondcc3c022017-12-22 16:02:54 -08002390 const cricket::ContentInfo* video_content =
2391 GetFirstVideoContent(local_description()->description());
2392 if (video_content) {
2393 if (video_content->rejected) {
2394 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2395 } else {
2396 const cricket::VideoContentDescription* video_desc =
2397 video_content->media_description()->as_video();
2398 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2399 }
deadbeeffaac4972015-11-12 15:33:07 -08002400 }
deadbeefab9b2d12015-10-14 11:33:11 -07002401 }
2402
2403 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002404 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002405 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002406 const cricket::RtpDataContentDescription* rtp_data_desc =
2407 data_content->media_description()->as_rtp_data();
2408 // rtp_data_desc will be null if this is an SCTP description.
2409 if (rtp_data_desc) {
2410 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002411 }
2412 }
2413
Steve Anton8a006912017-12-04 15:25:56 -08002414 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415}
2416
Steve Anton06817cd2018-12-18 15:55:30 -08002417// The SDP parser used to populate these values by default for the 'content
2418// name' if an a=mid line was absent.
2419static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2420 switch (media_type) {
2421 case cricket::MEDIA_TYPE_AUDIO:
2422 return cricket::CN_AUDIO;
2423 case cricket::MEDIA_TYPE_VIDEO:
2424 return cricket::CN_VIDEO;
2425 case cricket::MEDIA_TYPE_DATA:
2426 return cricket::CN_DATA;
2427 }
2428 RTC_NOTREACHED();
2429 return "";
2430}
2431
2432void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002433 cricket::SessionDescription* new_remote_description) {
2434 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002435 const cricket::ContentInfos& local_contents =
2436 (local_description() ? local_description()->description()->contents()
2437 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002438 const cricket::ContentInfos& remote_contents =
2439 (remote_description() ? remote_description()->description()->contents()
2440 : cricket::ContentInfos());
2441 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2442 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002443 if (!content.name.empty()) {
2444 continue;
2445 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002446 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002447 absl::string_view source_explanation;
2448 if (IsUnifiedPlan()) {
2449 if (i < local_contents.size()) {
2450 new_mid = local_contents[i].name;
2451 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002452 } else if (i < remote_contents.size()) {
2453 new_mid = remote_contents[i].name;
2454 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002455 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002456 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002457 source_explanation = "generated just now";
2458 }
2459 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002460 new_mid = std::string(
2461 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002462 source_explanation = "to match pre-existing behavior";
2463 }
Steve Antond7180cc2019-02-07 10:44:53 -08002464 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002465 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002466 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002467 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2468 << " is missing an a=mid line. Filling in the value '"
2469 << new_mid << "' " << source_explanation << ".";
2470 }
2471}
2472
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002473void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002474 SetSessionDescriptionObserver* observer,
2475 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002476 SetRemoteDescription(
2477 std::unique_ptr<SessionDescriptionInterface>(desc),
2478 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2479 new SetRemoteDescriptionObserverAdapter(this, observer)));
2480}
2481
2482void PeerConnection::SetRemoteDescription(
2483 std::unique_ptr<SessionDescriptionInterface> desc,
2484 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002485 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002486 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002487
nisse7ce109a2017-01-31 00:57:56 -08002488 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002489 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 return;
2491 }
Steve Anton8a006912017-12-04 15:25:56 -08002492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002494 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002495 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002496 return;
2497 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002498
Steve Anton80dd7b52018-02-16 17:08:42 -08002499 // If a session error has occurred the PeerConnection is in a possibly
2500 // inconsistent state so fail right away.
2501 if (session_error() != SessionError::kNone) {
2502 std::string error_message = GetSessionErrorMsg();
2503 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2504 observer->OnSetRemoteDescriptionComplete(
2505 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2506 return;
2507 }
Steve Anton71439a62018-02-15 11:53:06 -08002508
Steve Antonba42e992018-04-09 14:10:01 -07002509 if (desc->GetType() == SdpType::kOffer) {
2510 // Report to UMA the format of the received offer.
2511 ReportSdpFormatReceived(*desc);
2512 }
2513
Steve Anton06817cd2018-12-18 15:55:30 -08002514 // Handle remote descriptions missing a=mid lines for interop with legacy end
2515 // points.
2516 FillInMissingRemoteMids(desc->description());
2517
Steve Anton80dd7b52018-02-16 17:08:42 -08002518 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002519 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002520 std::string error_message = GetSetDescriptionErrorMessage(
2521 cricket::CS_REMOTE, desc->GetType(), error);
2522 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002523 observer->OnSetRemoteDescriptionComplete(
2524 RTCError(error.type(), std::move(error_message)));
2525 return;
2526 }
Steve Anton71439a62018-02-15 11:53:06 -08002527
Steve Anton80dd7b52018-02-16 17:08:42 -08002528 // Grab the description type before moving ownership to
2529 // ApplyRemoteDescription, which may destroy it before returning.
2530 const SdpType type = desc->GetType();
2531
2532 error = ApplyRemoteDescription(std::move(desc));
2533 // |desc| may be destroyed at this point.
2534
2535 if (!error.ok()) {
2536 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2537 // inconsistent state, so act conservatively here and set the session error
2538 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2539 SetSessionError(SessionError::kContent, error.message());
2540 std::string error_message =
2541 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2542 RTC_LOG(LS_ERROR) << error_message;
2543 observer->OnSetRemoteDescriptionComplete(
2544 RTCError(error.type(), std::move(error_message)));
2545 return;
2546 }
2547 RTC_DCHECK(remote_description());
2548
2549 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002550 // TODO(deadbeef): We already had to hop to the network thread for
2551 // MaybeStartGathering...
2552 network_thread()->Invoke<void>(
2553 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2554 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002555 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002556 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002557 }
2558
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002559 if (IsUnifiedPlan()) {
2560 bool was_negotiation_needed = is_negotiation_needed_;
2561 UpdateNegotiationNeeded();
2562 if (signaling_state() == kStable && was_negotiation_needed &&
2563 is_negotiation_needed_) {
2564 Observer()->OnRenegotiationNeeded();
2565 }
2566 }
2567
Steve Anton8a006912017-12-04 15:25:56 -08002568 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002569 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002570}
2571
2572RTCError PeerConnection::ApplyRemoteDescription(
2573 std::unique_ptr<SessionDescriptionInterface> desc) {
2574 RTC_DCHECK_RUN_ON(signaling_thread());
2575 RTC_DCHECK(desc);
2576
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002577 // Update stats here so that we have the most recent stats for tracks and
2578 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002579 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002580
Steve Antondcc3c022017-12-22 16:02:54 -08002581 // Take a reference to the old remote description since it's used below to
2582 // compare against the new remote description. When setting the new remote
2583 // description, grab ownership of the replaced session description in case it
2584 // is the same as |old_remote_description|, to keep it alive for the duration
2585 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002586 const SessionDescriptionInterface* old_remote_description =
2587 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002588 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002589 SdpType type = desc->GetType();
2590 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002591 replaced_remote_description = pending_remote_description_
2592 ? std::move(pending_remote_description_)
2593 : std::move(current_remote_description_);
2594 current_remote_description_ = std::move(desc);
2595 pending_remote_description_ = nullptr;
2596 current_local_description_ = std::move(pending_local_description_);
2597 } else {
2598 replaced_remote_description = std::move(pending_remote_description_);
2599 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002600 }
Steve Anton8a006912017-12-04 15:25:56 -08002601 // The session description to apply now must be accessed by
2602 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002603 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002605 // Report statistics about any use of simulcast.
2606 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2607 *remote_description()->description());
2608
Zhi Huange830e682018-03-30 10:48:35 -07002609 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2610 if (!error.ok()) {
2611 return error;
2612 }
Steve Anton8a006912017-12-04 15:25:56 -08002613 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002614 if (IsUnifiedPlan()) {
2615 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002616 cricket::CS_REMOTE, *remote_description(), local_description(),
2617 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002618 if (!error.ok()) {
2619 return error;
2620 }
Steve Antondcc3c022017-12-22 16:02:54 -08002621 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002622 // Media channels will be created only when offer is set. These may use new
2623 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002624 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002625 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002626 // description is applied. Restore back to old description.
2627 RTCError error = CreateChannels(*remote_description()->description());
2628 if (!error.ok()) {
2629 return error;
2630 }
2631 }
Steve Antondcc3c022017-12-22 16:02:54 -08002632 // Remove unused channels if MediaContentDescription is rejected.
2633 RemoveUnusedChannels(remote_description()->description());
2634 }
Steve Anton8a006912017-12-04 15:25:56 -08002635
Zhi Huange830e682018-03-30 10:48:35 -07002636 // NOTE: Candidates allocation will be initiated only when
2637 // SetLocalDescription is called.
2638 error = UpdateSessionState(type, cricket::CS_REMOTE,
2639 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002640 if (!error.ok()) {
2641 return error;
2642 }
2643
2644 if (local_description() &&
2645 !UseCandidatesInSessionDescription(remote_description())) {
2646 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2647 }
2648
2649 if (old_remote_description) {
2650 for (const cricket::ContentInfo& content :
2651 old_remote_description->description()->contents()) {
2652 // Check if this new SessionDescription contains new ICE ufrag and
2653 // password that indicates the remote peer requests an ICE restart.
2654 // TODO(deadbeef): When we start storing both the current and pending
2655 // remote description, this should reset pending_ice_restarts and compare
2656 // against the current description.
2657 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2658 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002659 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002660 pending_ice_restarts_.insert(content.name);
2661 }
2662 } else {
2663 // We retain all received candidates only if ICE is not restarted.
2664 // When ICE is restarted, all previous candidates belong to an old
2665 // generation and should not be kept.
2666 // TODO(deadbeef): This goes against the W3C spec which says the remote
2667 // description should only contain candidates from the last set remote
2668 // description plus any candidates added since then. We should remove
2669 // this once we're sure it won't break anything.
2670 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2671 old_remote_description, content.name, mutable_remote_description());
2672 }
2673 }
2674 }
2675
2676 if (session_error() != SessionError::kNone) {
2677 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2678 }
2679
2680 // Set the the ICE connection state to connecting since the connection may
2681 // become writable with peer reflexive candidates before any remote candidate
2682 // is signaled.
2683 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2684 // is to have a new signal the indicates a change in checking state from the
2685 // transport and expose a new checking() member from transport that can be
2686 // read to determine the current checking state. The existing SignalConnecting
2687 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002688 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002689 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002690 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2691 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2692 }
2693
deadbeefab9b2d12015-10-14 11:33:11 -07002694 // If setting the description decided our SSL role, allocate any necessary
2695 // SCTP sids.
2696 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002697 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002698 AllocateSctpSids(role);
2699 }
2700
Steve Antondcc3c022017-12-22 16:02:54 -08002701 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002702 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002703 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002704 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002705 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002706 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002707 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002708 const ContentInfo* content =
2709 FindMediaSectionForTransceiver(transceiver, remote_description());
2710 if (!content) {
2711 continue;
2712 }
2713 const MediaContentDescription* media_desc = content->media_description();
2714 RtpTransceiverDirection local_direction =
2715 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002716 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2717 // RTCSessionDescription: Set the associated remote streams given
2718 // transceiver.[[Receiver]], msids, addList, and removeList".
2719 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2720 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2721 std::vector<std::string> stream_ids;
2722 if (!media_desc->streams().empty()) {
2723 // The remote description has signaled the stream IDs.
2724 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002725 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002726 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2727 << " (" << GetStreamIdsString(stream_ids) << ").";
2728 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2729 stream_ids, &added_streams,
2730 &removed_streams);
2731 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2732 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2733 // and transceiver's current direction is neither sendrecv nor recvonly,
2734 // process the addition of a remote track for the media description.
2735 if (!transceiver->fired_direction() ||
2736 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2737 RTC_LOG(LS_INFO)
2738 << "Processing the addition of a remote track for MID="
2739 << content->name << ".";
2740 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002741 }
Steve Antondcc3c022017-12-22 16:02:54 -08002742 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002743 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002744 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2745 // removal of a remote track for the media description, given transceiver,
2746 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002747 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002748 (transceiver->fired_direction() &&
2749 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2750 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2751 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002752 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002753 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002754 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002755 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002756 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002757 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002758 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002759 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002760 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002761 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2762 if (transceiver->mid()) {
2763 auto dtls_transport =
2764 LookupDtlsTransportByMidInternal(*transceiver->mid());
2765 transceiver->internal()->sender_internal()->set_transport(
2766 dtls_transport);
2767 transceiver->internal()->receiver_internal()->set_transport(
2768 dtls_transport);
2769 }
Steve Antondcc3c022017-12-22 16:02:54 -08002770 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002771 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002772 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002773 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002774 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2775 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002776 transceiver->Stop();
2777 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002778 if (!content->rejected &&
2779 RtpTransceiverDirectionHasRecv(local_direction)) {
2780 // Set ssrc to 0 in the case of an unsignalled ssrc.
2781 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002782 if (!media_desc->streams().empty() &&
2783 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002784 ssrc = media_desc->streams()[0].first_ssrc();
2785 }
2786 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002787 }
Steve Antondcc3c022017-12-22 16:02:54 -08002788 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002789 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002790 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002791 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002792 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002793 observer->OnTrack(transceiver);
2794 observer->OnAddTrack(transceiver->receiver(),
2795 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002796 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002797 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002798 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002799 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002800 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002801 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002802 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002803 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002804 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002805 }
Steve Antondcc3c022017-12-22 16:02:54 -08002806 }
2807
Henrik Boströmfdb92012017-11-09 19:55:44 +01002808 const cricket::ContentInfo* audio_content =
2809 GetFirstAudioContent(remote_description()->description());
2810 const cricket::ContentInfo* video_content =
2811 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002812 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002813 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002814 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002815 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002816 const cricket::RtpDataContentDescription* rtp_data_desc =
2817 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002818
2819 // Check if the descriptions include streams, just in case the peer supports
2820 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002821 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002822 (audio_desc && !audio_desc->streams().empty()) ||
2823 (video_desc && !video_desc->streams().empty())) {
2824 remote_peer_supports_msid_ = true;
2825 }
deadbeefab9b2d12015-10-14 11:33:11 -07002826
2827 // We wait to signal new streams until we finish processing the description,
2828 // since only at that point will new streams have all their tracks.
2829 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2830
Steve Antondcc3c022017-12-22 16:02:54 -08002831 if (!IsUnifiedPlan()) {
2832 // TODO(steveanton): When removing RTP senders/receivers in response to a
2833 // rejected media section, there is some cleanup logic that expects the
2834 // voice/ video channel to still be set. But in this method the voice/video
2835 // channel would have been destroyed by the SetRemoteDescription caller
2836 // above so the cleanup that relies on them fails to run. The RemoveSenders
2837 // calls should be moved to right before the DestroyChannel calls to fix
2838 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002839
Steve Antondcc3c022017-12-22 16:02:54 -08002840 // Find all audio rtp streams and create corresponding remote AudioTracks
2841 // and MediaStreams.
2842 if (audio_content) {
2843 if (audio_content->rejected) {
2844 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2845 } else {
2846 bool default_audio_track_needed =
2847 !remote_peer_supports_msid_ &&
2848 RtpTransceiverDirectionHasSend(audio_desc->direction());
2849 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2850 default_audio_track_needed, audio_desc->type(),
2851 new_streams);
2852 }
deadbeeffaac4972015-11-12 15:33:07 -08002853 }
deadbeefab9b2d12015-10-14 11:33:11 -07002854
Steve Antondcc3c022017-12-22 16:02:54 -08002855 // Find all video rtp streams and create corresponding remote VideoTracks
2856 // and MediaStreams.
2857 if (video_content) {
2858 if (video_content->rejected) {
2859 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2860 } else {
2861 bool default_video_track_needed =
2862 !remote_peer_supports_msid_ &&
2863 RtpTransceiverDirectionHasSend(video_desc->direction());
2864 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2865 default_video_track_needed, video_desc->type(),
2866 new_streams);
2867 }
deadbeeffaac4972015-11-12 15:33:07 -08002868 }
deadbeefab9b2d12015-10-14 11:33:11 -07002869
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002870 // If this is an RTP data transport, update the DataChannels with the
2871 // information from the remote peer.
2872 if (rtp_data_desc) {
2873 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002874 }
deadbeefab9b2d12015-10-14 11:33:11 -07002875
Steve Antondcc3c022017-12-22 16:02:54 -08002876 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002877 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002878 for (size_t i = 0; i < new_streams->count(); ++i) {
2879 MediaStreamInterface* new_stream = new_streams->at(i);
2880 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002881 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002882 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2883 }
deadbeefab9b2d12015-10-14 11:33:11 -07002884
Steve Antondcc3c022017-12-22 16:02:54 -08002885 UpdateEndedRemoteMediaStreams();
2886 }
deadbeefab9b2d12015-10-14 11:33:11 -07002887
Steve Anton8a006912017-12-04 15:25:56 -08002888 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002889}
2890
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002891void PeerConnection::SetAssociatedRemoteStreams(
2892 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2893 const std::vector<std::string>& stream_ids,
2894 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2895 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2896 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2897 for (const std::string& stream_id : stream_ids) {
2898 rtc::scoped_refptr<MediaStreamInterface> stream =
2899 remote_streams_->find(stream_id);
2900 if (!stream) {
2901 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2902 MediaStream::Create(stream_id));
2903 remote_streams_->AddStream(stream);
2904 added_streams->push_back(stream);
2905 }
2906 media_streams.push_back(stream);
2907 }
2908 // Special case: "a=msid" missing, use random stream ID.
2909 if (media_streams.empty() &&
2910 !(remote_description()->description()->msid_signaling() &
2911 cricket::kMsidSignalingMediaSection)) {
2912 if (!missing_msid_default_stream_) {
2913 missing_msid_default_stream_ = MediaStreamProxy::Create(
2914 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2915 added_streams->push_back(missing_msid_default_stream_);
2916 }
2917 media_streams.push_back(missing_msid_default_stream_);
2918 }
2919 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2920 receiver->streams();
2921 // SetStreams() will add/remove the receiver's track to/from the streams. This
2922 // differs from the spec - the spec uses an "addList" and "removeList" to
2923 // update the stream-track relationships in a later step. We do this earlier,
2924 // changing the order of things, but the end-result is the same.
2925 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2926 // instead. https://crbug.com/webrtc/9480
2927 receiver->SetStreams(media_streams);
2928 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2929}
2930
Steve Anton0f5400a2018-07-17 14:25:36 -07002931void PeerConnection::ProcessRemovalOfRemoteTrack(
2932 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2933 transceiver,
2934 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2935 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2936 RTC_DCHECK(transceiver->mid());
2937 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2938 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002939 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002940 transceiver->internal()->receiver_internal()->streams();
2941 // This will remove the remote track from the streams.
2942 transceiver->internal()->receiver_internal()->set_stream_ids({});
2943 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002944 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2945}
2946
2947void PeerConnection::RemoveRemoteStreamsIfEmpty(
2948 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2949 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2950 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2951 // streams, see if the stream was removed by checking if this was the last
2952 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002953 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002954 if (remote_stream->GetAudioTracks().empty() &&
2955 remote_stream->GetVideoTracks().empty()) {
2956 remote_streams_->RemoveStream(remote_stream);
2957 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002958 }
2959 }
2960}
2961
Steve Antondcc3c022017-12-22 16:02:54 -08002962RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2963 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002964 const SessionDescriptionInterface& new_session,
2965 const SessionDescriptionInterface* old_local_description,
2966 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002967 RTC_DCHECK(IsUnifiedPlan());
2968
Steve Anton7464fca2018-01-19 11:10:37 -08002969 const cricket::ContentGroup* bundle_group = nullptr;
2970 if (new_session.GetType() == SdpType::kOffer) {
2971 auto bundle_group_or_error =
2972 GetEarlyBundleGroup(*new_session.description());
2973 if (!bundle_group_or_error.ok()) {
2974 return bundle_group_or_error.MoveError();
2975 }
2976 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002977 }
Steve Antondcc3c022017-12-22 16:02:54 -08002978
Steve Antondcc3c022017-12-22 16:02:54 -08002979 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002980 for (size_t i = 0; i < new_contents.size(); ++i) {
2981 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002982 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002983 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002984 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2985 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002986 const cricket::ContentInfo* old_local_content = nullptr;
2987 if (old_local_description &&
2988 i < old_local_description->description()->contents().size()) {
2989 old_local_content =
2990 &old_local_description->description()->contents()[i];
2991 }
2992 const cricket::ContentInfo* old_remote_content = nullptr;
2993 if (old_remote_description &&
2994 i < old_remote_description->description()->contents().size()) {
2995 old_remote_content =
2996 &old_remote_description->description()->contents()[i];
2997 }
Steve Antondcc3c022017-12-22 16:02:54 -08002998 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002999 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3000 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003001 if (!transceiver_or_error.ok()) {
3002 return transceiver_or_error.MoveError();
3003 }
3004 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003005 RTCError error =
3006 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3007 if (!error.ok()) {
3008 return error;
3009 }
3010 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003011 if (GetDataMid() && new_content.name != *GetDataMid()) {
3012 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003013 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3014 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003015 continue;
3016 }
3017 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3018 if (!error.ok()) {
3019 return error;
3020 }
Steve Antondcc3c022017-12-22 16:02:54 -08003021 } else {
3022 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3023 "Unknown section type.");
3024 }
3025 }
3026
3027 return RTCError::OK();
3028}
3029
3030RTCError PeerConnection::UpdateTransceiverChannel(
3031 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3032 transceiver,
3033 const cricket::ContentInfo& content,
3034 const cricket::ContentGroup* bundle_group) {
3035 RTC_DCHECK(IsUnifiedPlan());
3036 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003037 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003038 if (content.rejected) {
3039 if (channel) {
3040 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003041 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003042 }
3043 } else {
3044 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003045 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003046 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003047 } else {
Steve Anton69470252018-02-09 11:43:08 -08003048 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003049 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003050 }
3051 if (!channel) {
3052 LOG_AND_RETURN_ERROR(
3053 RTCErrorType::INTERNAL_ERROR,
3054 "Failed to create channel for mid=" + content.name);
3055 }
3056 transceiver->internal()->SetChannel(channel);
3057 }
3058 }
3059 return RTCError::OK();
3060}
3061
Steve Antonfa2260d2017-12-28 16:38:23 -08003062RTCError PeerConnection::UpdateDataChannel(
3063 cricket::ContentSource source,
3064 const cricket::ContentInfo& content,
3065 const cricket::ContentGroup* bundle_group) {
3066 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003067 // If data channels are disabled, ignore this media section. CreateAnswer
3068 // will take care of rejecting it.
3069 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003070 }
3071 if (content.rejected) {
3072 DestroyDataChannel();
3073 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003074 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003075 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003076 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3077 "Failed to create data channel.");
3078 }
3079 }
3080 if (source == cricket::CS_REMOTE) {
3081 const MediaContentDescription* data_desc = content.media_description();
3082 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3083 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3084 }
3085 }
3086 }
3087 return RTCError::OK();
3088}
3089
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003090// This method will extract any send encodings that were sent by the remote
3091// connection. This is currently only relevant for Simulcast scenario (where
3092// the number of layers may be communicated by the server).
3093static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3094 const MediaContentDescription& desc) {
3095 if (!desc.HasSimulcast()) {
3096 return {};
3097 }
3098 std::vector<RtpEncodingParameters> result;
3099 const SimulcastDescription& simulcast = desc.simulcast_description();
3100
3101 // This is a remote description, the parameters we are after should appear
3102 // as receive streams.
3103 for (const auto& alternatives : simulcast.receive_layers()) {
3104 RTC_DCHECK(!alternatives.empty());
3105 // There is currently no way to specify or choose from alternatives.
3106 // We will always use the first alternative, which is the most preferred.
3107 const SimulcastLayer& layer = alternatives[0];
3108 RtpEncodingParameters parameters;
3109 parameters.rid = layer.rid;
3110 parameters.active = !layer.is_paused;
3111 result.push_back(parameters);
3112 }
3113
3114 return result;
3115}
3116
3117static RTCError UpdateSimulcastLayerStatusInSender(
3118 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003119 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003120 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003121 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003122 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003123
3124 // The simulcast envelope cannot be changed, only the status of the streams.
3125 // So we will iterate over the send encodings rather than the layers.
3126 for (RtpEncodingParameters& encoding : parameters.encodings) {
3127 auto iter = std::find_if(layers.begin(), layers.end(),
3128 [&encoding](const SimulcastLayer& layer) {
3129 return layer.rid == encoding.rid;
3130 });
3131 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003132 if (iter == layers.end()) {
3133 disabled_layers.push_back(encoding.rid);
3134 continue;
3135 }
3136
3137 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003138 }
3139
Amit Hilbuch619b2942019-02-26 15:55:19 -08003140 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003141 if (result.ok()) {
3142 result = sender->DisableEncodingLayers(disabled_layers);
3143 }
3144
3145 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003146}
3147
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003148static bool SimulcastIsRejected(
3149 const ContentInfo* local_content,
3150 const MediaContentDescription& answer_media_desc) {
3151 bool simulcast_offered = local_content &&
3152 local_content->media_description() &&
3153 local_content->media_description()->HasSimulcast();
3154 bool simulcast_answered = answer_media_desc.HasSimulcast();
3155 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3156 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3157 return simulcast_offered && (!simulcast_answered || !rids_supported);
3158}
3159
Amit Hilbuch2297d332019-02-19 12:49:22 -08003160static RTCError DisableSimulcastInSender(
3161 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003162 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003163 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003164 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003165 return RTCError::OK();
3166 }
3167
Amit Hilbuch2297d332019-02-19 12:49:22 -08003168 std::vector<std::string> disabled_layers;
3169 std::transform(
3170 parameters.encodings.begin() + 1, parameters.encodings.end(),
3171 std::back_inserter(disabled_layers),
3172 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3173 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003174}
3175
Steve Antondcc3c022017-12-22 16:02:54 -08003176RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3177PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003178 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003179 size_t mline_index,
3180 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003181 const ContentInfo* old_local_content,
3182 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003183 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003184 // If this is an offer then the m= section might be recycled. If the m=
3185 // section is being recycled (defined as: rejected in the current local or
3186 // remote description and not rejected in new description), dissociate the
3187 // currently associated RtpTransceiver by setting its mid property to null,
3188 // and discard the mapping between the transceiver and its m= section index.
3189 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3190 old_remote_content)) {
3191 // We want to dissociate the transceiver that has the rejected mid.
3192 const std::string& old_mid =
3193 (old_local_content && old_local_content->rejected)
3194 ? old_local_content->name
3195 : old_remote_content->name;
3196 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003197 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003198 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3199 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003200 old_transceiver->internal()->set_mid(absl::nullopt);
3201 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003202 }
3203 }
3204 const MediaContentDescription* media_desc = content.media_description();
3205 auto transceiver = GetAssociatedTransceiver(content.name);
3206 if (source == cricket::CS_LOCAL) {
3207 // Find the RtpTransceiver that corresponds to this m= section, using the
3208 // mapping between transceivers and m= section indices established when
3209 // creating the offer.
3210 if (!transceiver) {
3211 transceiver = GetTransceiverByMLineIndex(mline_index);
3212 }
3213 if (!transceiver) {
3214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3215 "Unknown transceiver");
3216 }
3217 } else {
3218 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3219 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3220 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003221 // When simulcast is requested, a transceiver cannot be associated because
3222 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003223 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003224 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3225 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003226 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3227 }
3228 // If no RtpTransceiver was found in the previous step, create one with a
3229 // recvonly direction.
3230 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003231 RTC_LOG(LS_INFO) << "Adding "
3232 << cricket::MediaTypeToString(media_desc->type())
3233 << " transceiver for MID=" << content.name
3234 << " at i=" << mline_index
3235 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003236 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003237 std::vector<RtpEncodingParameters> send_encodings =
3238 GetSendEncodingsFromRemoteDescription(*media_desc);
3239 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3240 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003241 std::string receiver_id;
3242 if (!media_desc->streams().empty()) {
3243 receiver_id = media_desc->streams()[0].id;
3244 } else {
3245 receiver_id = rtc::CreateRandomUuid();
3246 }
3247 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003248 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003249 transceiver->internal()->set_direction(
3250 RtpTransceiverDirection::kRecvOnly);
3251 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003252
3253 // Check if the offer indicated simulcast but the answer rejected it.
3254 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003255 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003256 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003257 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003258 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003259 if (!error.ok()) {
3260 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3261 return std::move(error);
3262 }
3263 }
Steve Antondcc3c022017-12-22 16:02:54 -08003264 }
3265 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003266 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003267 LOG_AND_RETURN_ERROR(
3268 RTCErrorType::INVALID_PARAMETER,
3269 "Transceiver type does not match media description type.");
3270 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003271 if (media_desc->HasSimulcast()) {
3272 std::vector<SimulcastLayer> layers =
3273 source == cricket::CS_LOCAL
3274 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3275 : media_desc->simulcast_description()
3276 .receive_layers()
3277 .GetAllLayers();
3278 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003279 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003280 if (!error.ok()) {
3281 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3282 return std::move(error);
3283 }
3284 }
Steve Antondcc3c022017-12-22 16:02:54 -08003285 // Associate the found or created RtpTransceiver with the m= section by
3286 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3287 // section, and establish a mapping between the transceiver and the index of
3288 // the m= section.
3289 transceiver->internal()->set_mid(content.name);
3290 transceiver->internal()->set_mline_index(mline_index);
3291 return std::move(transceiver);
3292}
3293
3294rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3295PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3296 RTC_DCHECK(IsUnifiedPlan());
3297 for (auto transceiver : transceivers_) {
3298 if (transceiver->mid() == mid) {
3299 return transceiver;
3300 }
3301 }
3302 return nullptr;
3303}
3304
3305rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3306PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3307 RTC_DCHECK(IsUnifiedPlan());
3308 for (auto transceiver : transceivers_) {
3309 if (transceiver->internal()->mline_index() == mline_index) {
3310 return transceiver;
3311 }
3312 }
3313 return nullptr;
3314}
3315
3316rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3317PeerConnection::FindAvailableTransceiverToReceive(
3318 cricket::MediaType media_type) const {
3319 RTC_DCHECK(IsUnifiedPlan());
3320 // From JSEP section 5.10 (Applying a Remote Description):
3321 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3322 // the same type that were added to the PeerConnection by addTrack and are not
3323 // associated with any m= section and are not stopped, find the first such
3324 // RtpTransceiver.
3325 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003326 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003327 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3328 !transceiver->stopped()) {
3329 return transceiver;
3330 }
3331 }
3332 return nullptr;
3333}
3334
Steve Antoned10bd92017-12-05 10:52:59 -08003335const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3336 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3337 transceiver,
3338 const SessionDescriptionInterface* sdesc) const {
3339 RTC_DCHECK(transceiver);
3340 RTC_DCHECK(sdesc);
3341 if (IsUnifiedPlan()) {
3342 if (!transceiver->internal()->mid()) {
3343 // This transceiver is not associated with a media section yet.
3344 return nullptr;
3345 }
3346 return sdesc->description()->GetContentByName(
3347 *transceiver->internal()->mid());
3348 } else {
3349 // Plan B only allows at most one audio and one video section, so use the
3350 // first media section of that type.
3351 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003352 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003353 }
3354}
3355
deadbeef46c73892016-11-16 19:42:04 -08003356PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003357 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003358 return configuration_;
3359}
3360
deadbeef293e9262017-01-11 12:28:30 -08003361bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3362 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003363 RTC_DCHECK_RUN_ON(signaling_thread());
3364 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003365 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003366 if (IsClosed()) {
3367 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3368 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3369 }
3370
Qingsi Wanga2d60672018-04-11 16:57:45 -07003371 // According to JSEP, after setLocalDescription, changing the candidate pool
3372 // size is not allowed, and changing the set of ICE servers will not result
3373 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003374 if (local_description() && configuration.ice_candidate_pool_size !=
3375 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003376 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3377 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003378 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003379 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003380
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003381 if (local_description() &&
3382 configuration.use_media_transport != configuration_.use_media_transport) {
3383 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3384 "SetLocalDescription.";
3385 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3386 }
3387
3388 if (remote_description() &&
3389 configuration.use_media_transport != configuration_.use_media_transport) {
3390 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3391 "SetRemoteDescription.";
3392 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3393 }
3394
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003395 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003396 configuration.use_media_transport_for_data_channels !=
3397 configuration_.use_media_transport_for_data_channels) {
3398 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3399 "after calling SetLocalDescription.";
3400 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3401 }
3402
3403 if (remote_description() &&
3404 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 SetRemoteDescription.";
3408 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3409 }
3410
3411 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003412 configuration.crypto_options != configuration_.crypto_options) {
3413 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3414 "SetLocalDescription.";
3415 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3416 }
3417
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003418 if (local_description() && configuration.use_datagram_transport !=
3419 configuration_.use_datagram_transport) {
3420 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3421 "after calling SetLocalDescription.";
3422 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3423 }
3424
3425 if (remote_description() && configuration.use_datagram_transport !=
3426 configuration_.use_datagram_transport) {
3427 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3428 "after calling SetRemoteDescription.";
3429 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3430 }
3431
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003432 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003433 configuration.use_media_transport ||
3434 configuration.use_datagram_transport) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003435 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3436 << "Media transport requires MaxBundle policy.";
3437 }
3438
deadbeef293e9262017-01-11 12:28:30 -08003439 // The simplest (and most future-compatible) way to tell if the config was
3440 // modified in an invalid way is to copy each property we do support
3441 // modifying, then use operator==. There are far more properties we don't
3442 // support modifying than those we do, and more could be added.
3443 RTCConfiguration modified_config = configuration_;
3444 modified_config.servers = configuration.servers;
3445 modified_config.type = configuration.type;
3446 modified_config.ice_candidate_pool_size =
3447 configuration.ice_candidate_pool_size;
3448 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003449 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003450 modified_config.ice_check_interval_strong_connectivity =
3451 configuration.ice_check_interval_strong_connectivity;
3452 modified_config.ice_check_interval_weak_connectivity =
3453 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003454 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3455 modified_config.ice_unwritable_min_checks =
3456 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003457 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003458 modified_config.stun_candidate_keepalive_interval =
3459 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003460 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003461 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003462 modified_config.active_reset_srtp_params =
3463 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003464 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003465 modified_config.use_media_transport_for_data_channels =
3466 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003467 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003468 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003469 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3470 }
3471
Steve Anton038834f2017-07-14 15:59:59 -07003472 // Validate the modified configuration.
3473 RTCError validate_error = ValidateConfiguration(modified_config);
3474 if (!validate_error.ok()) {
3475 return SafeSetError(std::move(validate_error), error);
3476 }
3477
deadbeef293e9262017-01-11 12:28:30 -08003478 // Note that this isn't possible through chromium, since it's an unsigned
3479 // short in WebIDL.
3480 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003481 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003482 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3483 }
3484
3485 // Parse ICE servers before hopping to network thread.
3486 cricket::ServerAddresses stun_servers;
3487 std::vector<cricket::RelayServerConfig> turn_servers;
3488 RTCErrorType parse_error =
3489 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3490 if (parse_error != RTCErrorType::NONE) {
3491 return SafeSetError(parse_error, error);
3492 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003493 // Note if STUN or TURN servers were supplied.
3494 if (!stun_servers.empty()) {
3495 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3496 }
3497 if (!turn_servers.empty()) {
3498 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3499 }
deadbeef293e9262017-01-11 12:28:30 -08003500
3501 // In theory this shouldn't fail.
3502 if (!network_thread()->Invoke<bool>(
3503 RTC_FROM_HERE,
3504 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3505 stun_servers, turn_servers, modified_config.type,
3506 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003507 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003508 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003509 modified_config.stun_candidate_keepalive_interval,
3510 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003511 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003512 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3513 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003514
deadbeefd1a38b52016-12-10 13:15:33 -08003515 // As described in JSEP, calling setConfiguration with new ICE servers or
3516 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3517 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003518 if (modified_config.servers != configuration_.servers ||
3519 modified_config.type != configuration_.type ||
3520 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003521 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003522 }
skvladd1f5fda2017-02-03 16:54:05 -08003523
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003524 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003525 transport_controller_->SetMediaTransportSettings(
3526 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003527 modified_config.use_media_transport_for_data_channels,
3528 modified_config.use_datagram_transport);
skvladd1f5fda2017-02-03 16:54:05 -08003529
Zhi Huangb57e1692018-06-12 11:41:11 -07003530 if (configuration_.active_reset_srtp_params !=
3531 modified_config.active_reset_srtp_params) {
3532 transport_controller_->SetActiveResetSrtpParams(
3533 modified_config.active_reset_srtp_params);
3534 }
3535
deadbeef293e9262017-01-11 12:28:30 -08003536 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003537 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003538 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003539}
3540
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003541bool PeerConnection::AddIceCandidate(
3542 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003543 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003544 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003545 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003546 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003547 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003548 return false;
3549 }
Steve Antond25da372017-11-06 14:50:29 -08003550
3551 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003552 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003553 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003554 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003555 return false;
3556 }
3557
3558 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003559 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003560 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003561 return false;
3562 }
3563
3564 bool valid = false;
3565 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3566 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003567 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003568 return false;
3569 }
3570
3571 // Add this candidate to the remote session description.
3572 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003573 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003574 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003575 return false;
3576 }
3577
3578 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003579 bool result = UseCandidate(ice_candidate);
3580 if (result) {
3581 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003582 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3583 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3584 }
3585 if (ice_candidate->candidate().address().IsPrivateIP()) {
3586 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3587 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003588 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3589 } else {
3590 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3591 }
3592 return result;
Steve Antond25da372017-11-06 14:50:29 -08003593 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003594 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003595 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003596 return true;
3597 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003598}
3599
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003600bool PeerConnection::RemoveIceCandidates(
3601 const std::vector<cricket::Candidate>& candidates) {
3602 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003603 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003604 if (IsClosed()) {
3605 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3606 return false;
3607 }
3608
Steve Antond25da372017-11-06 14:50:29 -08003609 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003610 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3611 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003612 return false;
3613 }
3614
3615 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003616 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003617 return false;
3618 }
3619
3620 size_t number_removed =
3621 mutable_remote_description()->RemoveCandidates(candidates);
3622 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003623 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003624 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003625 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003626 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003627 }
3628
3629 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003630 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3631 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003632 RTC_LOG(LS_ERROR)
3633 << "RemoveIceCandidates: Error when removing remote candidates: "
3634 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003635 }
3636 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003637}
3638
Niels Möller0c4f7be2018-05-07 14:01:37 +02003639RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003640 if (!worker_thread()->IsCurrent()) {
3641 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003642 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003643 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003644 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003645
Niels Möller0c4f7be2018-05-07 14:01:37 +02003646 const bool has_min = bitrate.min_bitrate_bps.has_value();
3647 const bool has_start = bitrate.start_bitrate_bps.has_value();
3648 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003649 if (has_min && *bitrate.min_bitrate_bps < 0) {
3650 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3651 "min_bitrate_bps <= 0");
3652 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003653 if (has_start) {
3654 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003655 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003656 "start_bitrate_bps < min_bitrate_bps");
3657 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003658 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3659 "curent_bitrate_bps < 0");
3660 }
3661 }
3662 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003663 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003664 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003665 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003666 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3667 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3668 "max_bitrate_bps < min_bitrate_bps");
3669 } else if (*bitrate.max_bitrate_bps < 0) {
3670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3671 "max_bitrate_bps < 0");
3672 }
3673 }
3674
zstein4b979802017-06-02 14:37:37 -07003675 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003676 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003677
3678 return RTCError::OK();
3679}
3680
Alex Narest78609d52017-10-20 10:37:47 +02003681void PeerConnection::SetBitrateAllocationStrategy(
3682 std::unique_ptr<rtc::BitrateAllocationStrategy>
3683 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003684 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003685 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3686 // move-capture values in lambdas.
3687 struct Task {
3688 PeerConnection* const pc;
3689 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3690 void operator()() {
3691 RTC_DCHECK_RUN_ON(pc->worker_thread());
3692 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3693 }
3694 };
3695 worker_thread()->Invoke<void>(
3696 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003697 return;
3698 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003699 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003700 RTC_DCHECK(call_.get());
3701 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3702}
3703
henrika5f6bf242017-11-01 11:06:56 +01003704void PeerConnection::SetAudioPlayout(bool playout) {
3705 if (!worker_thread()->IsCurrent()) {
3706 worker_thread()->Invoke<void>(
3707 RTC_FROM_HERE,
3708 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3709 return;
3710 }
3711 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003712 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003713 audio_state->SetPlayout(playout);
3714}
3715
3716void PeerConnection::SetAudioRecording(bool recording) {
3717 if (!worker_thread()->IsCurrent()) {
3718 worker_thread()->Invoke<void>(
3719 RTC_FROM_HERE,
3720 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3721 return;
3722 }
3723 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003724 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003725 audio_state->SetRecording(recording);
3726}
3727
Steve Anton8c0f7a72017-10-03 10:03:10 -07003728std::unique_ptr<rtc::SSLCertificate>
3729PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003730 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3731 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003732 return nullptr;
3733 }
Steve Antonf25303e2018-10-16 15:23:31 -07003734 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003735}
3736
Zhi Huang70b820f2018-01-27 14:16:15 -08003737std::unique_ptr<rtc::SSLCertChain>
3738PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003739 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003740 auto audio_transceiver = GetFirstAudioTransceiver();
3741 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003742 return nullptr;
3743 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003744 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003745 audio_transceiver->internal()->channel()->transport_name());
3746}
3747
3748rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3749PeerConnection::GetFirstAudioTransceiver() const {
3750 for (auto transceiver : transceivers_) {
3751 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3752 return transceiver;
3753 }
3754 }
3755 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003756}
3757
Bjorn Tereliusde939432017-11-20 17:38:14 +01003758bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3759 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003760 // TODO(eladalon): In C++14, this can be done with a lambda.
3761 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003762 bool operator()() {
3763 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3764 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003765 PeerConnection* const pc;
3766 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003767 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003768 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003769 return worker_thread()->Invoke<bool>(
3770 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003771}
3772
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003773bool PeerConnection::StartRtcEventLog(
3774 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003775 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3776 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3777 output_period_ms = 5000;
3778 }
3779 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003780}
3781
ivoc14d5dbe2016-07-04 07:06:55 -07003782void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003783 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003784 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3785}
3786
Harald Alvestrandad88c882018-11-28 16:47:46 +01003787rtc::scoped_refptr<DtlsTransportInterface>
3788PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003789 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003790 return transport_controller_->LookupDtlsTransportByMid(mid);
3791}
3792
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003793rtc::scoped_refptr<DtlsTransport>
3794PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003795 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003796 return transport_controller_->LookupDtlsTransportByMid(mid);
3797}
3798
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003799rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3800 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003801 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003802 return sctp_transport_;
3803}
3804
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003805const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003806 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003807 return pending_local_description_ ? pending_local_description_.get()
3808 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003809}
3810
3811const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003812 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003813 return pending_remote_description_ ? pending_remote_description_.get()
3814 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003815}
3816
deadbeeffe4a8a42016-12-20 17:56:17 -08003817const SessionDescriptionInterface* PeerConnection::current_local_description()
3818 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003819 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003820 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003821}
3822
3823const SessionDescriptionInterface* PeerConnection::current_remote_description()
3824 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003825 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003826 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003827}
3828
3829const SessionDescriptionInterface* PeerConnection::pending_local_description()
3830 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003831 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003832 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003833}
3834
3835const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3836 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003837 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003838 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003839}
3840
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003841void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003842 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003843 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003844 // Update stats here so that we have the most recent stats for tracks and
3845 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003846 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003847
Steve Anton75737c02017-11-06 10:37:17 -08003848 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003849 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003850
Mirko Bonadei739baf02019-01-27 17:29:42 +01003851 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003852 transceiver->Stop();
3853 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003854
3855 // Ensure that all asynchronous stats requests are completed before destroying
3856 // the transport controller below.
3857 if (stats_collector_) {
3858 stats_collector_->WaitForPendingRequest();
3859 }
3860
3861 // Don't destroy BaseChannels until after stats has been cleaned up so that
3862 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003863 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003864
Qingsi Wang93a84392018-01-30 17:13:09 -08003865 // The event log is used in the transport controller, which must be outlived
3866 // by the former. CreateOffer by the peer connection is implemented
3867 // asynchronously and if the peer connection is closed without resetting the
3868 // WebRTC session description factory, the session description factory would
3869 // call the transport controller.
3870 webrtc_session_desc_factory_.reset();
3871 transport_controller_.reset();
3872
deadbeef42a42632017-03-10 15:18:00 -08003873 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003874 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3875 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003876
Steve Anton978b8762017-09-29 12:15:02 -07003877 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003878 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003879 call_.reset();
3880 // The event log must outlive call (and any other object that uses it).
3881 event_log_.reset();
3882 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003883 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003884 // The .h file says that observer can be discarded after close() returns.
3885 // Make sure this is true.
3886 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003887}
3888
Steve Antonad182762018-09-05 20:22:40 +00003889void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003890 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003891 switch (msg->message_id) {
3892 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3893 SetSessionDescriptionMsg* param =
3894 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3895 param->observer->OnSuccess();
3896 delete param;
3897 break;
3898 }
3899 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3900 SetSessionDescriptionMsg* param =
3901 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3902 param->observer->OnFailure(std::move(param->error));
3903 delete param;
3904 break;
3905 }
3906 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3907 CreateSessionDescriptionMsg* param =
3908 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3909 param->observer->OnFailure(std::move(param->error));
3910 delete param;
3911 break;
3912 }
3913 case MSG_GETSTATS: {
3914 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3915 StatsReports reports;
3916 stats_->GetStats(param->track, &reports);
3917 param->observer->OnComplete(reports);
3918 delete param;
3919 break;
3920 }
3921 case MSG_FREE_DATACHANNELS: {
3922 sctp_data_channels_to_free_.clear();
3923 break;
3924 }
3925 case MSG_REPORT_USAGE_PATTERN: {
3926 ReportUsagePattern();
3927 break;
3928 }
3929 default:
3930 RTC_NOTREACHED() << "Not implemented";
3931 break;
3932 }
3933}
3934
Steve Antonafb0bb72018-02-20 11:35:37 -08003935cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3936 RTC_DCHECK(!IsUnifiedPlan());
3937 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3938 GetAudioTransceiver()->internal()->channel());
3939 if (voice_channel) {
3940 return voice_channel->media_channel();
3941 } else {
3942 return nullptr;
3943 }
3944}
3945
3946cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3947 RTC_DCHECK(!IsUnifiedPlan());
3948 auto* video_channel = static_cast<cricket::VideoChannel*>(
3949 GetVideoTransceiver()->internal()->channel());
3950 if (video_channel) {
3951 return video_channel->media_channel();
3952 } else {
3953 return nullptr;
3954 }
3955}
3956
Steve Anton4171afb2017-11-20 10:20:22 -08003957void PeerConnection::CreateAudioReceiver(
3958 MediaStreamInterface* stream,
3959 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003960 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3961 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003962 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3963 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003964 auto* audio_receiver = new AudioRtpReceiver(
3965 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003966 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003967 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3968 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3969 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003970 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003971 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003972 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003973}
3974
Steve Anton4171afb2017-11-20 10:20:22 -08003975void PeerConnection::CreateVideoReceiver(
3976 MediaStreamInterface* stream,
3977 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003978 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3979 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003980 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3981 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003982 auto* video_receiver = new VideoRtpReceiver(
3983 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003984 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003985 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3986 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3987 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003988 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003989 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003990 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003991}
3992
deadbeef70ab1a12015-09-28 16:53:55 -07003993// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3994// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003995rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003996 const RtpSenderInfo& remote_sender_info) {
3997 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3998 if (!receiver) {
3999 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4000 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004001 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004002 }
Steve Anton4171afb2017-11-20 10:20:22 -08004003 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4004 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4005 } else {
4006 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4007 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004008 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004009}
4010
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004011void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4012 MediaStreamInterface* stream) {
4013 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004014 RTC_DCHECK(track);
4015 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004016 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004017 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004018 // We already have a sender for this track, so just change the stream_id
4019 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004020 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004021 return;
4022 }
4023
4024 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004025 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004026 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004027 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004028 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004029 // If the sender has already been configured in SDP, we call SetSsrc,
4030 // which will connect the sender to the underlying transport. This can
4031 // occur if a local session description that contains the ID of the sender
4032 // is set before AddStream is called. It can also occur if the local
4033 // session description is not changed and RemoveStream is called, and
4034 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004035 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004036 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004037 if (sender_info) {
4038 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004039 }
4040}
4041
4042// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4043// indefinitely, when we have unified plan SDP.
4044void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4045 MediaStreamInterface* stream) {
4046 RTC_DCHECK(!IsClosed());
4047 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004048 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004049 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4050 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004051 return;
4052 }
Steve Anton4171afb2017-11-20 10:20:22 -08004053 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004054}
4055
4056void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4057 MediaStreamInterface* stream) {
4058 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004059 RTC_DCHECK(track);
4060 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004061 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004062 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004063 // We already have a sender for this track, so just change the stream_id
4064 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004065 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004066 return;
4067 }
4068
4069 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004070 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004071 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004072 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004073 GetVideoTransceiver()->internal()->AddSender(new_sender);
4074 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004075 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004076 if (sender_info) {
4077 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004078 }
4079}
4080
4081void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4082 MediaStreamInterface* stream) {
4083 RTC_DCHECK(!IsClosed());
4084 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004085 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004086 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4087 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004088 return;
4089 }
Steve Anton4171afb2017-11-20 10:20:22 -08004090 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004091}
4092
Steve Antonba818672017-11-06 10:21:57 -08004093void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004094 if (ice_connection_state_ == new_state) {
4095 return;
4096 }
4097
deadbeefcbecd352015-09-23 11:50:27 -07004098 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004099 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004100 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004101 return;
4102 }
Steve Antonba818672017-11-06 10:21:57 -08004103
Mirko Bonadei675513b2017-11-09 11:09:25 +01004104 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4105 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004106 RTC_DCHECK(ice_connection_state_ !=
4107 PeerConnectionInterface::kIceConnectionClosed);
4108
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004109 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004110 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004111}
4112
Alex Loiko9289eda2018-11-23 16:18:59 +00004113void PeerConnection::SetStandardizedIceConnectionState(
4114 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004115 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004116 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004117 }
4118
4119 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004120 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004121 }
4122
4123 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4124 << standardized_ice_connection_state_ << " => " << new_state;
4125
Alex Loiko9289eda2018-11-23 16:18:59 +00004126 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004127 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004128}
4129
Jonas Olsson635474e2018-10-18 15:58:17 +02004130void PeerConnection::SetConnectionState(
4131 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004132 if (connection_state_ == new_state)
4133 return;
4134 if (IsClosed())
4135 return;
4136 connection_state_ = new_state;
4137 Observer()->OnConnectionChange(new_state);
4138}
4139
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004140void PeerConnection::OnIceGatheringChange(
4141 PeerConnectionInterface::IceGatheringState new_state) {
4142 if (IsClosed()) {
4143 return;
4144 }
4145 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004146 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004147}
4148
jbauch81bf7b02017-03-25 08:31:12 -07004149void PeerConnection::OnIceCandidate(
4150 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004151 if (IsClosed()) {
4152 return;
4153 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004154 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004155 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4156 candidate->candidate().address().IsPrivateIP()) {
4157 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4158 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004159 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4160 candidate->candidate().address().IsUnresolvedIP()) {
4161 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4162 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004163 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004164}
4165
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004166void PeerConnection::OnIceCandidatesRemoved(
4167 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004168 if (IsClosed()) {
4169 return;
4170 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004171 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004172}
4173
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004174void PeerConnection::ChangeSignalingState(
4175 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004176 if (signaling_state_ == signaling_state) {
4177 return;
4178 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004179 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4180 << GetSignalingStateString(signaling_state_)
4181 << " New state: "
4182 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004183 signaling_state_ = signaling_state;
4184 if (signaling_state == kClosed) {
4185 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004186 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004187 standardized_ice_connection_state_ =
4188 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004189 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4190 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004191 if (ice_gathering_state_ != kIceGatheringComplete) {
4192 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004193 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004194 }
4195 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004196 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004197}
4198
deadbeefeb459812015-12-15 19:24:43 -08004199void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4200 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004201 if (IsClosed()) {
4202 return;
4203 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004204 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004205 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004206}
4207
deadbeefeb459812015-12-15 19:24:43 -08004208void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4209 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004210 if (IsClosed()) {
4211 return;
4212 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004213 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004214 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004215}
4216
4217void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4218 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004219 if (IsClosed()) {
4220 return;
4221 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004222 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004223 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004224}
4225
4226void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4227 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004228 if (IsClosed()) {
4229 return;
4230 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004231 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004232 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004233}
4234
Henrik Boström31638672017-11-23 17:48:32 +01004235void PeerConnection::PostSetSessionDescriptionSuccess(
4236 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004237 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4238 signaling_thread()->Post(RTC_FROM_HERE, this,
4239 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004240}
4241
deadbeefab9b2d12015-10-14 11:33:11 -07004242void PeerConnection::PostSetSessionDescriptionFailure(
4243 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004244 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004245 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004246 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4247 msg->error = std::move(error);
4248 signaling_thread()->Post(RTC_FROM_HERE, this,
4249 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004250}
4251
4252void PeerConnection::PostCreateSessionDescriptionFailure(
4253 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004254 RTCError error) {
4255 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004256 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4257 msg->error = std::move(error);
4258 signaling_thread()->Post(RTC_FROM_HERE, this,
4259 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004260}
4261
zhihuang1c378ed2017-08-17 14:10:50 -07004262void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004263 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004264 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004265 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004266
Steve Antondcc3c022017-12-22 16:02:54 -08004267 if (IsUnifiedPlan()) {
4268 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4269 } else {
4270 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4271 }
4272
Steve Antonfa2260d2017-12-28 16:38:23 -08004273 // Intentionally unset the data channel type for RTP data channel with the
4274 // second condition. Otherwise the RTP data channels would be successfully
4275 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4276 // when building with chromium. We want to leave RTP data channels broken, so
4277 // people won't try to use them.
4278 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4279 session_options->data_channel_type = data_channel_type();
4280 }
4281
Steve Antondcc3c022017-12-22 16:02:54 -08004282 // Apply ICE restart flag and renomination flag.
4283 for (auto& options : session_options->media_description_options) {
4284 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4285 options.transport_options.enable_ice_renomination =
4286 configuration_.enable_ice_renomination;
4287 }
4288
4289 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004290 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004291 session_options->pooled_ice_credentials =
4292 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4293 RTC_FROM_HERE,
4294 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4295 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004296 session_options->offer_extmap_allow_mixed =
4297 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004298
4299 if (configuration_.enable_dtls_srtp &&
4300 !configuration_.enable_dtls_srtp.value()) {
4301 session_options->media_transport_settings =
4302 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4303 }
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004304 // Allow fallback for using obsolete SCTP syntax.
4305 // Note that the default in |session_options| is true, while
4306 // the default in |options| is false.
4307 session_options->use_obsolete_sctp_sdp =
4308 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004309}
4310
4311void PeerConnection::GetOptionsForPlanBOffer(
4312 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4313 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004314 // Figure out transceiver directional preferences.
4315 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4316 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4317
4318 // By default, generate sendrecv/recvonly m= sections.
4319 bool recv_audio = true;
4320 bool recv_video = true;
4321
4322 // By default, only offer a new m= section if we have media to send with it.
4323 bool offer_new_audio_description = send_audio;
4324 bool offer_new_video_description = send_video;
4325 bool offer_new_data_description = HasDataChannels();
4326
4327 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004328 if (offer_answer_options.offer_to_receive_audio !=
4329 RTCOfferAnswerOptions::kUndefined) {
4330 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004331 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004332 offer_new_audio_description ||
4333 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004334 }
Steve Antondcc3c022017-12-22 16:02:54 -08004335 if (offer_answer_options.offer_to_receive_video !=
4336 RTCOfferAnswerOptions::kUndefined) {
4337 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004338 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004339 offer_new_video_description ||
4340 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004341 }
4342
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004343 absl::optional<size_t> audio_index;
4344 absl::optional<size_t> video_index;
4345 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004346 // If a current description exists, generate m= sections in the same order,
4347 // using the first audio/video/data section that appears and rejecting
4348 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004349 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004350 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004351 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004352 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4353 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4354 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004355 }
4356
zhihuang1c378ed2017-08-17 14:10:50 -07004357 // Add audio/video/data m= sections to the end if needed.
4358 if (!audio_index && offer_new_audio_description) {
4359 session_options->media_description_options.push_back(
4360 cricket::MediaDescriptionOptions(
4361 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004362 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4363 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004364 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004365 }
zhihuang1c378ed2017-08-17 14:10:50 -07004366 if (!video_index && offer_new_video_description) {
4367 session_options->media_description_options.push_back(
4368 cricket::MediaDescriptionOptions(
4369 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004370 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4371 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004372 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004373 }
zhihuang1c378ed2017-08-17 14:10:50 -07004374 if (!data_index && offer_new_data_description) {
4375 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004376 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004377 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004378 }
4379
4380 cricket::MediaDescriptionOptions* audio_media_description_options =
4381 !audio_index ? nullptr
4382 : &session_options->media_description_options[*audio_index];
4383 cricket::MediaDescriptionOptions* video_media_description_options =
4384 !video_index ? nullptr
4385 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004386
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004387 AddPlanBRtpSenderOptions(GetSendersInternal(),
4388 audio_media_description_options,
4389 video_media_description_options,
4390 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004391}
4392
Steve Antondcc3c022017-12-22 16:02:54 -08004393static cricket::MediaDescriptionOptions
4394GetMediaDescriptionOptionsForTransceiver(
4395 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4396 transceiver,
4397 const std::string& mid) {
4398 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004399 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004400 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004401 media_description_options.codec_preferences =
4402 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004403 // This behavior is specified in JSEP. The gist is that:
4404 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4405 // sendrecv.
4406 // 2. If the MSID is included, then it must be included in any subsequent
4407 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004408 if (transceiver->stopped() ||
4409 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4410 !transceiver->internal()->has_ever_been_used_to_send())) {
4411 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004412 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004413
4414 cricket::SenderOptions sender_options;
4415 sender_options.track_id = transceiver->sender()->id();
4416 sender_options.stream_ids = transceiver->sender()->stream_ids();
4417
4418 // The following sets up RIDs and Simulcast.
4419 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004420 RtpParameters send_parameters =
4421 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004422 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4423 send_parameters.encodings.end(),
4424 [](const RtpEncodingParameters& encoding) {
4425 return !encoding.rid.empty();
4426 });
4427
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004428 std::vector<RidDescription> send_rids;
4429 SimulcastLayerList send_layers;
4430 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4431 if (encoding.rid.empty()) {
4432 continue;
4433 }
4434 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4435 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4436 }
4437
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004438 if (has_rids) {
4439 sender_options.rids = send_rids;
4440 }
4441
4442 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004443 // When RIDs are configured, we must set num_sim_layers to 0 to.
4444 // Otherwise, num_sim_layers must be 1 because either there is no
4445 // simulcast, or simulcast is acheived by munging the SDP.
4446 sender_options.num_sim_layers = has_rids ? 0 : 1;
4447 media_description_options.sender_options.push_back(sender_options);
4448
Steve Antondcc3c022017-12-22 16:02:54 -08004449 return media_description_options;
4450}
4451
Steve Anton5c72e712018-12-10 14:25:30 -08004452// Returns the ContentInfo at mline index |i|, or null if none exists.
4453static const ContentInfo* GetContentByIndex(
4454 const SessionDescriptionInterface* sdesc,
4455 size_t i) {
4456 if (!sdesc) {
4457 return nullptr;
4458 }
4459 const ContentInfos& contents = sdesc->description()->contents();
4460 return (i < contents.size() ? &contents[i] : nullptr);
4461}
4462
Steve Antondcc3c022017-12-22 16:02:54 -08004463void PeerConnection::GetOptionsForUnifiedPlanOffer(
4464 const RTCOfferAnswerOptions& offer_answer_options,
4465 cricket::MediaSessionOptions* session_options) {
4466 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4467 // Offers) and 5.2.2 (Subsequent Offers).
4468 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4469 const ContentInfos& local_contents =
4470 (local_description() ? local_description()->description()->contents()
4471 : ContentInfos());
4472 const ContentInfos& remote_contents =
4473 (remote_description() ? remote_description()->description()->contents()
4474 : ContentInfos());
4475 // The mline indices that can be recycled. New transceivers should reuse these
4476 // slots first.
4477 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004478 // First, go through each media section that exists in either the local or
4479 // remote description and generate a media section in this offer for the
4480 // associated transceiver. If a media section can be recycled, generate a
4481 // default, rejected media section here that can be later overwritten.
4482 for (size_t i = 0;
4483 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4484 // Either |local_content| or |remote_content| is non-null.
4485 const ContentInfo* local_content =
4486 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004487 const ContentInfo* current_local_content =
4488 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004489 const ContentInfo* remote_content =
4490 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004491 const ContentInfo* current_remote_content =
4492 GetContentByIndex(current_remote_description(), i);
4493 bool had_been_rejected =
4494 (current_local_content && current_local_content->rejected) ||
4495 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004496 const std::string& mid =
4497 (local_content ? local_content->name : remote_content->name);
4498 cricket::MediaType media_type =
4499 (local_content ? local_content->media_description()->type()
4500 : remote_content->media_description()->type());
4501 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4502 media_type == cricket::MEDIA_TYPE_VIDEO) {
4503 auto transceiver = GetAssociatedTransceiver(mid);
4504 RTC_CHECK(transceiver);
4505 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004506 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004507 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004508 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004509 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4510 RtpTransceiverDirection::kInactive,
4511 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004512 recycleable_mline_indices.push(i);
4513 } else {
4514 session_options->media_description_options.push_back(
4515 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4516 // CreateOffer shouldn't really cause any state changes in
4517 // PeerConnection, but we need a way to match new transceivers to new
4518 // media sections in SetLocalDescription and JSEP specifies this is done
4519 // by recording the index of the media section generated for the
4520 // transceiver in the offer.
4521 transceiver->internal()->set_mline_index(i);
4522 }
4523 } else {
4524 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004525 RTC_CHECK(GetDataMid());
4526 if (had_been_rejected || mid != *GetDataMid()) {
4527 session_options->media_description_options.push_back(
4528 GetMediaDescriptionOptionsForRejectedData(mid));
4529 } else {
4530 session_options->media_description_options.push_back(
4531 GetMediaDescriptionOptionsForActiveData(mid));
4532 }
Steve Antondcc3c022017-12-22 16:02:54 -08004533 }
4534 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004535
Steve Antondcc3c022017-12-22 16:02:54 -08004536 // Next, look for transceivers that are newly added (that is, are not stopped
4537 // and not associated). Reuse media sections marked as recyclable first,
4538 // otherwise append to the end of the offer. New media sections should be
4539 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004540 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004541 if (transceiver->mid() || transceiver->stopped()) {
4542 continue;
4543 }
4544 size_t mline_index;
4545 if (!recycleable_mline_indices.empty()) {
4546 mline_index = recycleable_mline_indices.front();
4547 recycleable_mline_indices.pop();
4548 session_options->media_description_options[mline_index] =
4549 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004550 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004551 } else {
4552 mline_index = session_options->media_description_options.size();
4553 session_options->media_description_options.push_back(
4554 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004555 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004556 }
4557 // See comment above for why CreateOffer changes the transceiver's state.
4558 transceiver->internal()->set_mline_index(mline_index);
4559 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004560 // Lastly, add a m-section if we have local data channels and an m section
4561 // does not already exist.
4562 if (!GetDataMid() && HasDataChannels()) {
4563 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004564 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004565 }
Steve Antondcc3c022017-12-22 16:02:54 -08004566}
4567
4568void PeerConnection::GetOptionsForAnswer(
4569 const RTCOfferAnswerOptions& offer_answer_options,
4570 cricket::MediaSessionOptions* session_options) {
4571 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4572
4573 if (IsUnifiedPlan()) {
4574 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4575 } else {
4576 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4577 }
4578
Steve Antonfa2260d2017-12-28 16:38:23 -08004579 // Intentionally unset the data channel type for RTP data channel. Otherwise
4580 // the RTP data channels would be successfully negotiated by default and the
4581 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4582 // We want to leave RTP data channels broken, so people won't try to use them.
4583 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4584 session_options->data_channel_type = data_channel_type();
4585 }
4586
Steve Antondcc3c022017-12-22 16:02:54 -08004587 // Apply ICE renomination flag.
4588 for (auto& options : session_options->media_description_options) {
4589 options.transport_options.enable_ice_renomination =
4590 configuration_.enable_ice_renomination;
4591 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004592
4593 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004594 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004595 session_options->pooled_ice_credentials =
4596 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4597 RTC_FROM_HERE,
4598 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4599 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004600}
4601
Steve Antondcc3c022017-12-22 16:02:54 -08004602void PeerConnection::GetOptionsForPlanBAnswer(
4603 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004604 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004605 // Figure out transceiver directional preferences.
4606 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4607 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4608
4609 // By default, generate sendrecv/recvonly m= sections. The direction is also
4610 // restricted by the direction in the offer.
4611 bool recv_audio = true;
4612 bool recv_video = true;
4613
4614 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004615 if (offer_answer_options.offer_to_receive_audio !=
4616 RTCOfferAnswerOptions::kUndefined) {
4617 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004618 }
Steve Antondcc3c022017-12-22 16:02:54 -08004619 if (offer_answer_options.offer_to_receive_video !=
4620 RTCOfferAnswerOptions::kUndefined) {
4621 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004622 }
4623
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004624 absl::optional<size_t> audio_index;
4625 absl::optional<size_t> video_index;
4626 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004627
4628 // Generate m= sections that match those in the offer.
4629 // Note that mediasession.cc will handle intersection our preferred
4630 // direction with the offered direction.
4631 GenerateMediaDescriptionOptions(
4632 remote_description(),
4633 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4634 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4635 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004636
4637 cricket::MediaDescriptionOptions* audio_media_description_options =
4638 !audio_index ? nullptr
4639 : &session_options->media_description_options[*audio_index];
4640 cricket::MediaDescriptionOptions* video_media_description_options =
4641 !video_index ? nullptr
4642 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004643
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004644 AddPlanBRtpSenderOptions(GetSendersInternal(),
4645 audio_media_description_options,
4646 video_media_description_options,
4647 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004648}
zhihuangaf388472016-11-02 16:49:48 -07004649
Steve Antondcc3c022017-12-22 16:02:54 -08004650void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4651 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4652 cricket::MediaSessionOptions* session_options) {
4653 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4654 // Answers) and 5.3.2 (Subsequent Answers).
4655 RTC_DCHECK(remote_description());
4656 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4657 for (const ContentInfo& content :
4658 remote_description()->description()->contents()) {
4659 cricket::MediaType media_type = content.media_description()->type();
4660 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4661 media_type == cricket::MEDIA_TYPE_VIDEO) {
4662 auto transceiver = GetAssociatedTransceiver(content.name);
4663 RTC_CHECK(transceiver);
4664 session_options->media_description_options.push_back(
4665 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4666 } else {
4667 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004668 // Reject all data sections if data channels are disabled.
4669 // Reject a data section if it has already been rejected.
4670 // Reject all data sections except for the first one.
4671 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4672 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004673 session_options->media_description_options.push_back(
4674 GetMediaDescriptionOptionsForRejectedData(content.name));
4675 } else {
4676 session_options->media_description_options.push_back(
4677 GetMediaDescriptionOptionsForActiveData(content.name));
4678 }
Steve Antondcc3c022017-12-22 16:02:54 -08004679 }
4680 }
htaa2a49d92016-03-04 02:51:39 -08004681}
4682
zhihuang1c378ed2017-08-17 14:10:50 -07004683void PeerConnection::GenerateMediaDescriptionOptions(
4684 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004685 RtpTransceiverDirection audio_direction,
4686 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004687 absl::optional<size_t>* audio_index,
4688 absl::optional<size_t>* video_index,
4689 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004690 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004691 for (const cricket::ContentInfo& content :
4692 session_desc->description()->contents()) {
4693 if (IsAudioContent(&content)) {
4694 // If we already have an audio m= section, reject this extra one.
4695 if (*audio_index) {
4696 session_options->media_description_options.push_back(
4697 cricket::MediaDescriptionOptions(
4698 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004699 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004700 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004701 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004702 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004703 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4704 content.name, audio_direction,
4705 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004706 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004707 }
4708 } else if (IsVideoContent(&content)) {
4709 // If we already have an video m= section, reject this extra one.
4710 if (*video_index) {
4711 session_options->media_description_options.push_back(
4712 cricket::MediaDescriptionOptions(
4713 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004714 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004715 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004716 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004717 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004718 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4719 content.name, video_direction,
4720 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004721 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004722 }
4723 } else {
4724 RTC_DCHECK(IsDataContent(&content));
4725 // If we already have an data m= section, reject this extra one.
4726 if (*data_index) {
4727 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004728 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004729 } else {
4730 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004731 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004732 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004733 }
4734 }
htaa2a49d92016-03-04 02:51:39 -08004735 }
deadbeefab9b2d12015-10-14 11:33:11 -07004736}
4737
Steve Antonfa2260d2017-12-28 16:38:23 -08004738cricket::MediaDescriptionOptions
4739PeerConnection::GetMediaDescriptionOptionsForActiveData(
4740 const std::string& mid) const {
4741 // Direction for data sections is meaningless, but legacy endpoints might
4742 // expect sendrecv.
4743 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4744 RtpTransceiverDirection::kSendRecv,
4745 /*stopped=*/false);
4746 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4747 return options;
4748}
4749
4750cricket::MediaDescriptionOptions
4751PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4752 const std::string& mid) const {
4753 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4754 RtpTransceiverDirection::kInactive,
4755 /*stopped=*/true);
4756 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4757 return options;
4758}
4759
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004760absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004761 switch (data_channel_type_) {
4762 case cricket::DCT_RTP:
4763 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004764 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004765 }
4766 return rtp_data_channel_->content_name();
4767 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004768 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004769 case cricket::DCT_MEDIA_TRANSPORT:
4770 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004771 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004772 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004773 }
4774}
4775
Steve Anton4171afb2017-11-20 10:20:22 -08004776void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4777 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4778 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004779 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004780}
4781
Steve Anton4171afb2017-11-20 10:20:22 -08004782void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004783 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004784 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004785 cricket::MediaType media_type,
4786 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004787 RTC_DCHECK(!IsUnifiedPlan());
4788
Steve Anton4171afb2017-11-20 10:20:22 -08004789 std::vector<RtpSenderInfo>* current_senders =
4790 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004791
Steve Anton4171afb2017-11-20 10:20:22 -08004792 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004793 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004794 for (auto sender_it = current_senders->begin();
4795 sender_it != current_senders->end();
4796 /* incremented manually */) {
4797 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004798 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004799 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004800 std::string params_stream_id;
4801 if (params) {
4802 params_stream_id =
4803 (!params->first_stream_id().empty() ? params->first_stream_id()
4804 : kDefaultStreamId);
4805 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004806 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004807 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004808 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004809 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004810 sender_exists) {
4811 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004812 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004813 OnRemoteSenderRemoved(info, media_type);
4814 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004815 }
4816 }
4817
Steve Anton4171afb2017-11-20 10:20:22 -08004818 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004819 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004820 if (!params.has_ssrcs()) {
4821 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4822 // sender, this means it is coming from a Unified Plan endpoint,so we just
4823 // create a default.
4824 default_sender_needed = true;
4825 break;
4826 }
4827
Seth Hampson845e8782018-03-02 11:34:10 -08004828 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004829 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004830 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4831 // not supported in Plan B, we just take the first here and create the
4832 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004833 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004834 (!params.first_stream_id().empty() ? params.first_stream_id()
4835 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004836 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004837 uint32_t ssrc = params.first_ssrc();
4838
4839 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004840 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004841 if (!stream) {
4842 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004843 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004844 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004845 remote_streams_->AddStream(stream);
4846 new_streams->AddStream(stream);
4847 }
4848
Steve Anton4171afb2017-11-20 10:20:22 -08004849 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004850 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004851 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004852 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004853 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004854 }
4855 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004856
Steve Anton4171afb2017-11-20 10:20:22 -08004857 // Add default sender if necessary.
4858 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004859 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004860 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004861 if (!default_stream) {
4862 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004863 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004864 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004865 remote_streams_->AddStream(default_stream);
4866 new_streams->AddStream(default_stream);
4867 }
Steve Anton4171afb2017-11-20 10:20:22 -08004868 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4869 ? kDefaultAudioSenderId
4870 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004871 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004872 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004873 if (!default_sender_info) {
4874 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004875 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004876 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004877 }
4878 }
deadbeefab9b2d12015-10-14 11:33:11 -07004879}
4880
Steve Anton4171afb2017-11-20 10:20:22 -08004881void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4882 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004883 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4884 << " receiver for track_id=" << sender_info.sender_id
4885 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004886
Steve Anton3d954a62018-04-02 11:27:23 -07004887 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004888 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004889 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004890 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004891 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004892 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004893 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004894 }
4895}
4896
Steve Anton4171afb2017-11-20 10:20:22 -08004897void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4898 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004899 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4900 << " receiver for track_id=" << sender_info.sender_id
4901 << " and stream_id=" << sender_info.stream_id;
4902
Seth Hampson845e8782018-03-02 11:34:10 -08004903 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004904
Henrik Boström933d8b02017-10-10 10:05:16 -07004905 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004906 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004907 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4908 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004909 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004910 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004911 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004912 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004913 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004914 }
4915 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004916 // Stopping or destroying a VideoRtpReceiver will end the
4917 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004918 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004919 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004920 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004921 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004922 // There's no guarantee the track is still available, e.g. the track may
4923 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004924 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004925 }
4926 } else {
nisseede5da42017-01-12 05:15:36 -08004927 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004928 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004929 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004930 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004931 }
deadbeefab9b2d12015-10-14 11:33:11 -07004932}
4933
4934void PeerConnection::UpdateEndedRemoteMediaStreams() {
4935 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4936 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4937 MediaStreamInterface* stream = remote_streams_->at(i);
4938 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4939 streams_to_remove.push_back(stream);
4940 }
4941 }
4942
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004943 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004944 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004945 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004946 }
4947}
4948
Steve Anton4171afb2017-11-20 10:20:22 -08004949void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004950 const std::vector<cricket::StreamParams>& streams,
4951 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004952 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004953
Seth Hampson845e8782018-03-02 11:34:10 -08004954 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004955 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004956 for (auto sender_it = current_senders->begin();
4957 sender_it != current_senders->end();
4958 /* incremented manually */) {
4959 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004960 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004961 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4962 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004963 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004964 OnLocalSenderRemoved(info, media_type);
4965 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004966 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004967 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004968 }
4969 }
4970
Steve Anton4171afb2017-11-20 10:20:22 -08004971 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004972 for (const cricket::StreamParams& params : streams) {
4973 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004974 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004975 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004976 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004977 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004978 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004979 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004980 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004981 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004982 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004983 }
4984 }
4985}
4986
Steve Anton4171afb2017-11-20 10:20:22 -08004987void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4988 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004989 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004990 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004991 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004992 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4993 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004994 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004995 return;
4996 }
4997
deadbeeffac06552015-11-25 11:26:01 -08004998 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004999 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005000 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005001 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005002 }
deadbeeffac06552015-11-25 11:26:01 -08005003
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005004 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005005 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005006}
5007
Steve Anton4171afb2017-11-20 10:20:22 -08005008void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5009 cricket::MediaType media_type) {
5010 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005011 if (!sender) {
5012 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005013 // SessionDescriptions has been renegotiated.
5014 return;
5015 }
deadbeeffac06552015-11-25 11:26:01 -08005016
5017 // A sender has been removed from the SessionDescription but it's still
5018 // associated with the PeerConnection. This only occurs if the SDP doesn't
5019 // match with the calls to CreateSender, AddStream and RemoveStream.
5020 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005021 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005022 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005023 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005024 }
deadbeeffac06552015-11-25 11:26:01 -08005025
Steve Anton4171afb2017-11-20 10:20:22 -08005026 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005027}
5028
5029void PeerConnection::UpdateLocalRtpDataChannels(
5030 const cricket::StreamParamsVec& streams) {
5031 std::vector<std::string> existing_channels;
5032
5033 // Find new and active data channels.
5034 for (const cricket::StreamParams& params : streams) {
5035 // |it->sync_label| is actually the data channel label. The reason is that
5036 // we use the same naming of data channels as we do for
5037 // MediaStreams and Tracks.
5038 // For MediaStreams, the sync_label is the MediaStream label and the
5039 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005040 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005041 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005042 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005043 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005044 continue;
5045 }
5046 // Set the SSRC the data channel should use for sending.
5047 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5048 existing_channels.push_back(data_channel_it->first);
5049 }
5050
5051 UpdateClosingRtpDataChannels(existing_channels, true);
5052}
5053
5054void PeerConnection::UpdateRemoteRtpDataChannels(
5055 const cricket::StreamParamsVec& streams) {
5056 std::vector<std::string> existing_channels;
5057
5058 // Find new and active data channels.
5059 for (const cricket::StreamParams& params : streams) {
5060 // The data channel label is either the mslabel or the SSRC if the mslabel
5061 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005062 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005063 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005064 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005065 auto data_channel_it = rtp_data_channels_.find(label);
5066 if (data_channel_it == rtp_data_channels_.end()) {
5067 // This is a new data channel.
5068 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5069 } else {
5070 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5071 }
5072 existing_channels.push_back(label);
5073 }
5074
5075 UpdateClosingRtpDataChannels(existing_channels, false);
5076}
5077
5078void PeerConnection::UpdateClosingRtpDataChannels(
5079 const std::vector<std::string>& active_channels,
5080 bool is_local_update) {
5081 auto it = rtp_data_channels_.begin();
5082 while (it != rtp_data_channels_.end()) {
5083 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005084 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005085 ++it;
5086 continue;
5087 }
5088
5089 if (is_local_update) {
5090 data_channel->SetSendSsrc(0);
5091 } else {
5092 data_channel->RemotePeerRequestClose();
5093 }
5094
5095 if (data_channel->state() == DataChannel::kClosed) {
5096 rtp_data_channels_.erase(it);
5097 it = rtp_data_channels_.begin();
5098 } else {
5099 ++it;
5100 }
5101 }
5102}
5103
5104void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5105 uint32_t remote_ssrc) {
5106 rtc::scoped_refptr<DataChannel> channel(
5107 InternalCreateDataChannel(label, nullptr));
5108 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005109 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005110 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005111 return;
5112 }
5113 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005114 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5115 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005116 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005117}
5118
5119rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5120 const std::string& label,
5121 const InternalDataChannelInit* config) {
5122 if (IsClosed()) {
5123 return nullptr;
5124 }
Steve Anton75737c02017-11-06 10:37:17 -08005125 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005126 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005127 << "InternalCreateDataChannel: Data is not supported in this call.";
5128 return nullptr;
5129 }
5130 InternalDataChannelInit new_config =
5131 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005132 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005133 if (new_config.id < 0) {
5134 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005135 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005136 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005137 RTC_LOG(LS_ERROR)
5138 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005139 return nullptr;
5140 }
5141 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005142 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005143 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005144 return nullptr;
5145 }
5146 }
5147
Steve Anton75737c02017-11-06 10:37:17 -08005148 rtc::scoped_refptr<DataChannel> channel(
5149 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005150 if (!channel) {
5151 sid_allocator_.ReleaseSid(new_config.id);
5152 return nullptr;
5153 }
5154
5155 if (channel->data_channel_type() == cricket::DCT_RTP) {
5156 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005157 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5158 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005159 return nullptr;
5160 }
5161 rtp_data_channels_[channel->label()] = channel;
5162 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005163 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005164 sctp_data_channels_.push_back(channel);
5165 channel->SignalClosed.connect(this,
5166 &PeerConnection::OnSctpDataChannelClosed);
5167 }
5168
Steve Anton2d8609c2018-01-23 16:38:46 -08005169 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005170 return channel;
5171}
5172
5173bool PeerConnection::HasDataChannels() const {
5174 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5175}
5176
5177void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005178 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005179 for (const auto& channel : sctp_data_channels_) {
5180 if (channel->id() < 0) {
5181 int sid;
5182 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005183 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5184 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005185 continue;
5186 }
5187 channel->SetSctpSid(sid);
5188 }
5189 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005190 // Since closing modifies the list of channels, we have to do the actual
5191 // closing outside the loop.
5192 for (const auto& channel : channels_to_close) {
5193 channel->CloseAbruptly();
5194 }
deadbeefab9b2d12015-10-14 11:33:11 -07005195}
5196
5197void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005198 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005199 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5200 ++it) {
5201 if (it->get() == channel) {
5202 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005203 // After the closing procedure is done, it's safe to use this ID for
5204 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005205 sid_allocator_.ReleaseSid(channel->id());
5206 }
deadbeefbd292462015-12-14 18:15:29 -08005207 // Since this method is triggered by a signal from the DataChannel,
5208 // we can't free it directly here; we need to free it asynchronously.
5209 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005210 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005211 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5212 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005213 return;
5214 }
5215 }
5216}
5217
deadbeefab9b2d12015-10-14 11:33:11 -07005218void PeerConnection::OnDataChannelDestroyed() {
5219 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5220 // DataChannel may callback to us and try to modify the list.
5221 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5222 temp_rtp_dcs.swap(rtp_data_channels_);
5223 for (const auto& kv : temp_rtp_dcs) {
5224 kv.second->OnTransportChannelDestroyed();
5225 }
5226
5227 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5228 temp_sctp_dcs.swap(sctp_data_channels_);
5229 for (const auto& channel : temp_sctp_dcs) {
5230 channel->OnTransportChannelDestroyed();
5231 }
5232}
5233
5234void PeerConnection::OnDataChannelOpenMessage(
5235 const std::string& label,
5236 const InternalDataChannelInit& config) {
5237 rtc::scoped_refptr<DataChannel> channel(
5238 InternalCreateDataChannel(label, &config));
5239 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005240 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005241 return;
5242 }
5243
deadbeefa601f5c2016-06-06 14:27:39 -07005244 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5245 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005246 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005247 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005248}
5249
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005250bool PeerConnection::HandleOpenMessage_s(
5251 const cricket::ReceiveDataParams& params,
5252 const rtc::CopyOnWriteBuffer& buffer) {
5253 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5254 // Received OPEN message; parse and signal that a new data channel should
5255 // be created.
5256 std::string label;
5257 InternalDataChannelInit config;
5258 config.id = params.ssrc;
5259 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5260 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5261 << params.ssrc;
5262 return true;
5263 }
5264 config.open_handshake_role = InternalDataChannelInit::kAcker;
5265 OnDataChannelOpenMessage(label, config);
5266 return true;
5267 }
5268 return false;
5269}
5270
Steve Anton4171afb2017-11-20 10:20:22 -08005271rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5272PeerConnection::GetAudioTransceiver() const {
5273 // This method only works with Plan B SDP, where there is a single
5274 // audio/video transceiver.
5275 RTC_DCHECK(!IsUnifiedPlan());
5276 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005277 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005278 return transceiver;
5279 }
5280 }
5281 RTC_NOTREACHED();
5282 return nullptr;
5283}
5284
5285rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5286PeerConnection::GetVideoTransceiver() const {
5287 // This method only works with Plan B SDP, where there is a single
5288 // audio/video transceiver.
5289 RTC_DCHECK(!IsUnifiedPlan());
5290 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005291 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005292 return transceiver;
5293 }
5294 }
5295 RTC_NOTREACHED();
5296 return nullptr;
5297}
5298
5299// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5300// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005301bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005302 switch (type) {
5303 case cricket::MEDIA_TYPE_AUDIO:
5304 return !GetAudioTransceiver()->internal()->senders().empty();
5305 case cricket::MEDIA_TYPE_VIDEO:
5306 return !GetVideoTransceiver()->internal()->senders().empty();
5307 case cricket::MEDIA_TYPE_DATA:
5308 return false;
5309 }
5310 RTC_NOTREACHED();
5311 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005312}
5313
Steve Anton4171afb2017-11-20 10:20:22 -08005314rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5315PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005316 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005317 for (auto sender : transceiver->internal()->senders()) {
5318 if (sender->track() == track) {
5319 return sender;
5320 }
5321 }
5322 }
5323 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005324}
5325
Steve Anton4171afb2017-11-20 10:20:22 -08005326rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5327PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005328 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005329 for (auto sender : transceiver->internal()->senders()) {
5330 if (sender->id() == sender_id) {
5331 return sender;
5332 }
5333 }
5334 }
5335 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005336}
5337
Steve Anton4171afb2017-11-20 10:20:22 -08005338rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5339PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005340 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005341 for (auto receiver : transceiver->internal()->receivers()) {
5342 if (receiver->id() == receiver_id) {
5343 return receiver;
5344 }
5345 }
5346 }
5347 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005348}
5349
Steve Anton4171afb2017-11-20 10:20:22 -08005350std::vector<PeerConnection::RtpSenderInfo>*
5351PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5352 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5353 media_type == cricket::MEDIA_TYPE_VIDEO);
5354 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5355 ? &remote_audio_sender_infos_
5356 : &remote_video_sender_infos_;
5357}
5358
5359std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005360 cricket::MediaType media_type) {
5361 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5362 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005363 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5364 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005365}
5366
Steve Anton4171afb2017-11-20 10:20:22 -08005367const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5368 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005369 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005370 const std::string sender_id) const {
5371 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005372 if (sender_info.stream_id == stream_id &&
5373 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005374 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005375 }
5376 }
5377 return nullptr;
5378}
5379
5380DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5381 for (const auto& channel : sctp_data_channels_) {
5382 if (channel->id() == sid) {
5383 return channel;
5384 }
5385 }
5386 return nullptr;
5387}
5388
Karl Wibergfb3be392019-03-22 14:13:22 +01005389PeerConnection::InitializePortAllocatorResult
5390PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005391 const cricket::ServerAddresses& stun_servers,
5392 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005393 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005394 RTC_DCHECK_RUN_ON(network_thread());
5395
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005396 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005397 // To handle both internal and externally created port allocator, we will
5398 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005399 int port_allocator_flags = port_allocator_->flags();
5400 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5401 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5402 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005403 // If the disable-IPv6 flag was specified, we'll not override it
5404 // by experiment.
5405 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005406 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005407 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5408 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005409 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005410 }
5411
zhihuangb09b3f92017-03-07 14:40:51 -08005412 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005413 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005414 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005415 }
5416
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005417 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005418 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005419 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005420 }
5421
honghaiz60347052016-05-31 18:29:12 -07005422 if (configuration.candidate_network_policy ==
5423 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005424 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005425 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005426 }
5427
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005428 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005429 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005430 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5431 }
5432
Karl Wibergfb3be392019-03-22 14:13:22 +01005433 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005434 // No step delay is used while allocating ports.
5435 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005436 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005437 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005438 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005439
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005440 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005441 for (auto& turn_server : turn_servers_copy) {
5442 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005443 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005444 // Call this last since it may create pooled allocator sessions using the
5445 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005446 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005447 stun_servers, std::move(turn_servers_copy),
5448 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5449 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005450 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005451
5452 InitializePortAllocatorResult res;
5453 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5454 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005455}
5456
deadbeef91dd5672016-05-18 16:55:30 -07005457bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005458 const cricket::ServerAddresses& stun_servers,
5459 const std::vector<cricket::RelayServerConfig>& turn_servers,
5460 IceTransportsType type,
5461 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005462 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005463 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005464 absl::optional<int> stun_candidate_keepalive_interval,
5465 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005466 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005467 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005468 // According to JSEP, after setLocalDescription, changing the candidate pool
5469 // size is not allowed, and changing the set of ICE servers will not result
5470 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005471 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005472 port_allocator_->FreezeCandidatePool();
5473 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005474 // Add the custom tls turn servers if they exist.
5475 auto turn_servers_copy = turn_servers;
5476 for (auto& turn_server : turn_servers_copy) {
5477 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5478 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005479 // Call this last since it may create pooled allocator sessions using the
5480 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005481 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005482 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5483 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005484}
5485
Steve Antonba818672017-11-06 10:21:57 -08005486cricket::ChannelManager* PeerConnection::channel_manager() const {
5487 return factory_->channel_manager();
5488}
5489
Elad Alon99c3fe52017-10-13 16:29:40 +02005490bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005491 std::unique_ptr<RtcEventLogOutput> output,
5492 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005493 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005494 if (!event_log_) {
5495 return false;
5496 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005497 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005498}
5499
5500void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005501 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005502 if (event_log_) {
5503 event_log_->StopLogging();
5504 }
ivoc14d5dbe2016-07-04 07:06:55 -07005505}
nisseeaabdf62017-05-05 02:23:02 -07005506
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005507cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005508 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005509 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005510 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005511 if (channel && channel->content_name() == content_name) {
5512 return channel;
5513 }
Steve Anton75737c02017-11-06 10:37:17 -08005514 }
5515 if (rtp_data_channel() &&
5516 rtp_data_channel()->content_name() == content_name) {
5517 return rtp_data_channel();
5518 }
5519 return nullptr;
5520}
5521
5522bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005523 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005524 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005525 RTC_LOG(LS_INFO)
5526 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005527 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005528 return false;
5529 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005530 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005531 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005532 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005533 return false;
5534 }
5535
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005536 absl::optional<rtc::SSLRole> dtls_role;
5537 if (sctp_mid_) {
5538 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5539 } else if (is_caller_) {
5540 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5541 }
Zhi Huange830e682018-03-30 10:48:35 -07005542 if (dtls_role) {
5543 *role = *dtls_role;
5544 return true;
5545 }
5546 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005547}
5548
5549bool PeerConnection::GetSslRole(const std::string& content_name,
5550 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005551 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005552 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005553 RTC_LOG(LS_INFO)
5554 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005555 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005556 return false;
5557 }
5558
Zhi Huange830e682018-03-30 10:48:35 -07005559 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5560 if (dtls_role) {
5561 *role = *dtls_role;
5562 return true;
5563 }
5564 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005565}
5566
Steve Antonf8470812017-12-04 10:46:21 -08005567void PeerConnection::SetSessionError(SessionError error,
5568 const std::string& error_desc) {
5569 RTC_DCHECK_RUN_ON(signaling_thread());
5570 if (error != session_error_) {
5571 session_error_ = error;
5572 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005573 }
5574}
5575
Zhi Huange830e682018-03-30 10:48:35 -07005576RTCError PeerConnection::UpdateSessionState(
5577 SdpType type,
5578 cricket::ContentSource source,
5579 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005580 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005581
5582 // If there's already a pending error then no state transition should happen.
5583 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005584 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005585
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005586 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005587 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005588 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005589 }
5590
5591 // Update the signaling state according to the specified state machine (see
5592 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005593 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005594 ChangeSignalingState(source == cricket::CS_LOCAL
5595 ? PeerConnectionInterface::kHaveLocalOffer
5596 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005597 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005598 ChangeSignalingState(source == cricket::CS_LOCAL
5599 ? PeerConnectionInterface::kHaveLocalPrAnswer
5600 : PeerConnectionInterface::kHaveRemotePrAnswer);
5601 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005602 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005603 ChangeSignalingState(PeerConnectionInterface::kStable);
5604 }
5605
5606 // Update internal objects according to the session description's media
5607 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005608 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005609 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005610 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005611 }
5612
Steve Anton8a006912017-12-04 15:25:56 -08005613 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005614}
5615
Steve Anton8a006912017-12-04 15:25:56 -08005616RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005617 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005618 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005619 const SessionDescriptionInterface* sdesc =
5620 (source == cricket::CS_LOCAL ? local_description()
5621 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005622 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005623
5624 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005625 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005626 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005627 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005628 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005629 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005630 continue;
5631 }
5632 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005633 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005634 if (!content_desc) {
5635 continue;
5636 }
5637 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005638 bool success = (source == cricket::CS_LOCAL)
5639 ? channel->SetLocalContent(content_desc, type, &error)
5640 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005641 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005642 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005643 }
5644 }
5645
5646 // If using the RtpDataChannel, push down the new SDP section for it too.
5647 if (rtp_data_channel_) {
5648 const ContentInfo* data_content =
5649 cricket::GetFirstDataContent(sdesc->description());
5650 if (data_content && !data_content->rejected) {
5651 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005652 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005653 if (data_desc) {
5654 std::string error;
5655 bool success =
5656 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005657 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005658 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005659 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005660 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005661 }
Steve Anton75737c02017-11-06 10:37:17 -08005662 }
5663 }
5664 }
Steve Antoned10bd92017-12-05 10:52:59 -08005665
Steve Anton75737c02017-11-06 10:37:17 -08005666 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5667 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005668 if (sctp_transport_ && local_description() && remote_description()) {
5669 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5670 local_description()->description());
5671 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5672 remote_description()->description());
5673 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005674 int max_message_size;
5675 // A remote max message size of zero means "any size supported".
5676 // We configure the connection with our own max message size.
5677 if (remote_sctp_description->max_message_size() == 0) {
5678 max_message_size = local_sctp_description->max_message_size();
5679 } else {
5680 max_message_size =
5681 std::min(local_sctp_description->max_message_size(),
5682 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005683 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005684 sctp_transport_->Start(local_sctp_description->port(),
5685 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005686 }
Steve Anton75737c02017-11-06 10:37:17 -08005687 }
Steve Antoned10bd92017-12-05 10:52:59 -08005688
Steve Anton8a006912017-12-04 15:25:56 -08005689 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005690}
5691
Steve Anton8a006912017-12-04 15:25:56 -08005692RTCError PeerConnection::PushdownTransportDescription(
5693 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005694 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005695 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005696
Zhi Huange830e682018-03-30 10:48:35 -07005697 if (source == cricket::CS_LOCAL) {
5698 const SessionDescriptionInterface* sdesc = local_description();
5699 RTC_DCHECK(sdesc);
5700 return transport_controller_->SetLocalDescription(type,
5701 sdesc->description());
5702 } else {
5703 const SessionDescriptionInterface* sdesc = remote_description();
5704 RTC_DCHECK(sdesc);
5705 return transport_controller_->SetRemoteDescription(type,
5706 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005707 }
Steve Anton75737c02017-11-06 10:37:17 -08005708}
5709
5710bool PeerConnection::GetTransportDescription(
5711 const SessionDescription* description,
5712 const std::string& content_name,
5713 cricket::TransportDescription* tdesc) {
5714 if (!description || !tdesc) {
5715 return false;
5716 }
5717 const TransportInfo* transport_info =
5718 description->GetTransportInfoByName(content_name);
5719 if (!transport_info) {
5720 return false;
5721 }
5722 *tdesc = transport_info->description;
5723 return true;
5724}
5725
Steve Anton75737c02017-11-06 10:37:17 -08005726cricket::IceConfig PeerConnection::ParseIceConfig(
5727 const PeerConnectionInterface::RTCConfiguration& config) const {
5728 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005729 switch (config.continual_gathering_policy) {
5730 case PeerConnectionInterface::GATHER_ONCE:
5731 gathering_policy = cricket::GATHER_ONCE;
5732 break;
5733 case PeerConnectionInterface::GATHER_CONTINUALLY:
5734 gathering_policy = cricket::GATHER_CONTINUALLY;
5735 break;
5736 default:
5737 RTC_NOTREACHED();
5738 gathering_policy = cricket::GATHER_ONCE;
5739 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005740
Steve Anton75737c02017-11-06 10:37:17 -08005741 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005742 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5743 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005744 ice_config.prioritize_most_likely_candidate_pairs =
5745 config.prioritize_most_likely_ice_candidate_pairs;
5746 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005747 RTCConfigurationToIceConfigOptionalInt(
5748 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005749 ice_config.continual_gathering_policy = gathering_policy;
5750 ice_config.presume_writable_when_fully_relayed =
5751 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005752 ice_config.ice_check_interval_strong_connectivity =
5753 config.ice_check_interval_strong_connectivity;
5754 ice_config.ice_check_interval_weak_connectivity =
5755 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005756 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005757 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5758 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005759 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005760 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005761 ice_config.regather_all_networks_interval_range =
5762 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005763 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005764 return ice_config;
5765}
5766
Steve Anton75737c02017-11-06 10:37:17 -08005767bool PeerConnection::SendData(const cricket::SendDataParams& params,
5768 const rtc::CopyOnWriteBuffer& payload,
5769 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005770 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005771 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5772 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5773 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005774 return false;
5775 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005776 if (media_transport_) {
5777 SendDataParams send_params;
5778 send_params.type = ToWebrtcDataMessageType(params.type);
5779 send_params.ordered = params.ordered;
5780 if (params.max_rtx_count >= 0) {
5781 send_params.max_rtx_count = params.max_rtx_count;
5782 } else if (params.max_rtx_ms >= 0) {
5783 send_params.max_rtx_ms = params.max_rtx_ms;
5784 }
5785 return media_transport_->SendData(params.sid, send_params, payload).ok();
5786 }
Steve Anton75737c02017-11-06 10:37:17 -08005787 return rtp_data_channel_
5788 ? rtp_data_channel_->SendData(params, payload, result)
5789 : network_thread()->Invoke<bool>(
5790 RTC_FROM_HERE,
5791 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005792 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005793}
5794
5795bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005796 RTC_DCHECK_RUN_ON(signaling_thread());
5797 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005798 // Don't log an error here, because DataChannels are expected to call
5799 // ConnectDataChannel in this state. It's the only way to initially tell
5800 // whether or not the underlying transport is ready.
5801 return false;
5802 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005803 if (media_transport_) {
5804 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5805 &DataChannel::OnChannelReady);
5806 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5807 &DataChannel::OnDataReceived);
5808 SignalMediaTransportChannelClosing_s.connect(
5809 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5810 SignalMediaTransportChannelClosed_s.connect(
5811 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5812 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005813 rtp_data_channel_->SignalReadyToSendData.connect(
5814 webrtc_data_channel, &DataChannel::OnChannelReady);
5815 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5816 &DataChannel::OnDataReceived);
5817 } else {
5818 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5819 &DataChannel::OnChannelReady);
5820 SignalSctpDataReceived.connect(webrtc_data_channel,
5821 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005822 SignalSctpClosingProcedureStartedRemotely.connect(
5823 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5824 SignalSctpClosingProcedureComplete.connect(
5825 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005826 }
5827 return true;
5828}
5829
5830void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005831 RTC_DCHECK_RUN_ON(signaling_thread());
5832 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005833 RTC_LOG(LS_ERROR)
5834 << "DisconnectDataChannel called when rtp_data_channel_ and "
5835 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005836 return;
5837 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005838 if (media_transport_) {
5839 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5840 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5841 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5842 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5843 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005844 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5845 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5846 } else {
5847 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5848 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005849 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5850 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005851 }
5852}
5853
5854void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005855 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005856 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005857 return;
5858 }
Steve Anton75737c02017-11-06 10:37:17 -08005859 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005860 RTC_LOG(LS_ERROR)
5861 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005862 return;
5863 }
5864 network_thread()->Invoke<void>(
5865 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005866 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005867}
5868
5869void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005870 if (media_transport_) {
5871 media_transport_->CloseChannel(sid);
5872 return;
5873 }
Steve Anton75737c02017-11-06 10:37:17 -08005874 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005875 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005876 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005877 return;
5878 }
5879 network_thread()->Invoke<void>(
5880 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005881 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005882}
5883
5884bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005885 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005886 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005887 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005888 sctp_ready_to_send_data_;
5889}
5890
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005891void PeerConnection::OnDataReceived(int channel_id,
5892 DataMessageType type,
5893 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005894 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005895 cricket::ReceiveDataParams params;
5896 params.sid = channel_id;
5897 params.type = ToCricketDataMessageType(type);
5898 media_transport_invoker_->AsyncInvoke<void>(
5899 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5900 RTC_DCHECK_RUN_ON(signaling_thread());
5901 if (!HandleOpenMessage_s(params, buffer)) {
5902 SignalMediaTransportReceivedData_s(params, buffer);
5903 }
5904 });
5905}
5906
5907void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005908 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005909 media_transport_invoker_->AsyncInvoke<void>(
5910 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5911 RTC_DCHECK_RUN_ON(signaling_thread());
5912 SignalMediaTransportChannelClosing_s(channel_id);
5913 });
5914}
5915
5916void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005917 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005918 media_transport_invoker_->AsyncInvoke<void>(
5919 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5920 RTC_DCHECK_RUN_ON(signaling_thread());
5921 SignalMediaTransportChannelClosed_s(channel_id);
5922 });
5923}
5924
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005925absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005926 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005927 if (sctp_mid_ && transport_controller_) {
5928 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5929 if (dtls_transport) {
5930 return dtls_transport->transport_name();
5931 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005932 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005933 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005934 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005935}
5936
Qingsi Wang72a43a12018-02-20 16:03:18 -08005937cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5938 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005939 network_thread()->Invoke<void>(
5940 RTC_FROM_HERE,
5941 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5942 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005943 return candidate_states_list;
5944}
5945
Steve Anton5dfde182018-02-06 10:34:40 -08005946std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5947 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005948 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005949 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005950 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005951 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005952 if (channel) {
5953 transport_names_by_mid[channel->content_name()] =
5954 channel->transport_name();
5955 }
Steve Anton75737c02017-11-06 10:37:17 -08005956 }
Steve Anton5dfde182018-02-06 10:34:40 -08005957 if (rtp_data_channel_) {
5958 transport_names_by_mid[rtp_data_channel_->content_name()] =
5959 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005960 }
5961 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005962 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005963 RTC_DCHECK(transport_name);
5964 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005965 }
Steve Anton5dfde182018-02-06 10:34:40 -08005966 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005967}
5968
Steve Anton5dfde182018-02-06 10:34:40 -08005969std::map<std::string, cricket::TransportStats>
5970PeerConnection::GetTransportStatsByNames(
5971 const std::set<std::string>& transport_names) {
5972 if (!network_thread()->IsCurrent()) {
5973 return network_thread()
5974 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5975 RTC_FROM_HERE,
5976 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005977 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005978 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005979 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5980 for (const std::string& transport_name : transport_names) {
5981 cricket::TransportStats transport_stats;
5982 bool success =
5983 transport_controller_->GetStats(transport_name, &transport_stats);
5984 if (success) {
5985 transport_stats_by_name[transport_name] = std::move(transport_stats);
5986 } else {
5987 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5988 << transport_name;
5989 }
5990 }
5991 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005992}
5993
5994bool PeerConnection::GetLocalCertificate(
5995 const std::string& transport_name,
5996 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005997 if (!certificate) {
5998 return false;
5999 }
6000 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6001 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006002}
6003
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006004std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006005 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006006 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006007}
6008
6009cricket::DataChannelType PeerConnection::data_channel_type() const {
6010 return data_channel_type_;
6011}
6012
6013bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006014 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006015 return pending_ice_restarts_.find(content_name) !=
6016 pending_ice_restarts_.end();
6017}
6018
Steve Anton75737c02017-11-06 10:37:17 -08006019bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6020 return transport_controller_->NeedsIceRestart(content_name);
6021}
6022
6023void PeerConnection::OnCertificateReady(
6024 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6025 transport_controller_->SetLocalCertificate(certificate);
6026}
6027
6028void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006029 SetSessionError(SessionError::kTransport,
6030 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006031}
6032
Alex Loiko9289eda2018-11-23 16:18:59 +00006033void PeerConnection::OnTransportControllerConnectionState(
6034 cricket::IceConnectionState state) {
6035 switch (state) {
6036 case cricket::kIceConnectionConnecting:
6037 // If the current state is Connected or Completed, then there were
6038 // writable channels but now there are not, so the next state must
6039 // be Disconnected.
6040 // kIceConnectionConnecting is currently used as the default,
6041 // un-connected state by the TransportController, so its only use is
6042 // detecting disconnections.
6043 if (ice_connection_state_ ==
6044 PeerConnectionInterface::kIceConnectionConnected ||
6045 ice_connection_state_ ==
6046 PeerConnectionInterface::kIceConnectionCompleted) {
6047 SetIceConnectionState(
6048 PeerConnectionInterface::kIceConnectionDisconnected);
6049 }
6050 break;
6051 case cricket::kIceConnectionFailed:
6052 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6053 break;
6054 case cricket::kIceConnectionConnected:
6055 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6056 "all transports are writable.";
6057 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6058 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6059 break;
6060 case cricket::kIceConnectionCompleted:
6061 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6062 "all transports are complete.";
6063 if (ice_connection_state_ !=
6064 PeerConnectionInterface::kIceConnectionConnected) {
6065 // If jumping directly from "checking" to "connected",
6066 // signal "connected" first.
6067 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6068 }
6069 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6070 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6071 ReportTransportStats();
6072 break;
6073 default:
6074 RTC_NOTREACHED();
6075 }
6076}
6077
Steve Anton75737c02017-11-06 10:37:17 -08006078void PeerConnection::OnTransportControllerCandidatesGathered(
6079 const std::string& transport_name,
6080 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006081 int sdp_mline_index;
6082 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006083 RTC_LOG(LS_ERROR)
6084 << "OnTransportControllerCandidatesGathered: content name "
6085 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006086 return;
6087 }
6088
6089 for (cricket::Candidates::const_iterator citer = candidates.begin();
6090 citer != candidates.end(); ++citer) {
6091 // Use transport_name as the candidate media id.
6092 std::unique_ptr<JsepIceCandidate> candidate(
6093 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6094 if (local_description()) {
6095 mutable_local_description()->AddCandidate(candidate.get());
6096 }
6097 OnIceCandidate(std::move(candidate));
6098 }
6099}
6100
6101void PeerConnection::OnTransportControllerCandidatesRemoved(
6102 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006103 // Sanity check.
6104 for (const cricket::Candidate& candidate : candidates) {
6105 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006106 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006107 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006108 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006109 return;
6110 }
6111 }
6112
6113 if (local_description()) {
6114 mutable_local_description()->RemoveCandidates(candidates);
6115 }
6116 OnIceCandidatesRemoved(candidates);
6117}
6118
6119void PeerConnection::OnTransportControllerDtlsHandshakeError(
6120 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006121 RTC_HISTOGRAM_ENUMERATION(
6122 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6123 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006124}
6125
Steve Antoned10bd92017-12-05 10:52:59 -08006126void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006127 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006128 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006129 if (channel && !channel->enabled()) {
6130 channel->Enable(true);
6131 }
Steve Anton75737c02017-11-06 10:37:17 -08006132 }
6133
Steve Anton4171afb2017-11-20 10:20:22 -08006134 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006135 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006136 }
Steve Anton75737c02017-11-06 10:37:17 -08006137}
6138
6139// Returns the media index for a local ice candidate given the content name.
6140bool PeerConnection::GetLocalCandidateMediaIndex(
6141 const std::string& content_name,
6142 int* sdp_mline_index) {
6143 if (!local_description() || !sdp_mline_index) {
6144 return false;
6145 }
6146
6147 bool content_found = false;
6148 const ContentInfos& contents = local_description()->description()->contents();
6149 for (size_t index = 0; index < contents.size(); ++index) {
6150 if (contents[index].name == content_name) {
6151 *sdp_mline_index = static_cast<int>(index);
6152 content_found = true;
6153 break;
6154 }
6155 }
6156 return content_found;
6157}
6158
6159bool PeerConnection::UseCandidatesInSessionDescription(
6160 const SessionDescriptionInterface* remote_desc) {
6161 if (!remote_desc) {
6162 return true;
6163 }
6164 bool ret = true;
6165
6166 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6167 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6168 for (size_t n = 0; n < candidates->count(); ++n) {
6169 const IceCandidateInterface* candidate = candidates->at(n);
6170 bool valid = false;
6171 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6172 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006173 RTC_LOG(LS_INFO)
6174 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006175 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006176 }
6177 continue;
6178 }
6179 ret = UseCandidate(candidate);
6180 if (!ret) {
6181 break;
6182 }
6183 }
6184 }
6185 return ret;
6186}
6187
6188bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006189 RTCErrorOr<const cricket::ContentInfo*> result =
6190 FindContentInfo(remote_description(), candidate);
6191 if (!result.ok()) {
6192 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6193 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006194 return false;
6195 }
Steve Anton75737c02017-11-06 10:37:17 -08006196 std::vector<cricket::Candidate> candidates;
6197 candidates.push_back(candidate->candidate());
6198 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006199 RTCError error = transport_controller_->AddRemoteCandidates(
6200 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006201 if (error.ok()) {
6202 // Candidates successfully submitted for checking.
6203 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6204 ice_connection_state_ ==
6205 PeerConnectionInterface::kIceConnectionDisconnected) {
6206 // If state is New, then the session has just gotten its first remote ICE
6207 // candidates, so go to Checking.
6208 // If state is Disconnected, the session is re-using old candidates or
6209 // receiving additional ones, so go to Checking.
6210 // If state is Connected, stay Connected.
6211 // TODO(bemasc): If state is Connected, and the new candidates are for a
6212 // newly added transport, then the state actually _should_ move to
6213 // checking. Add a way to distinguish that case.
6214 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6215 }
6216 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006217 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006218 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006219 }
6220 return true;
6221}
6222
Guido Urdaneta41633172019-05-23 20:12:29 +02006223RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6224 const SessionDescriptionInterface* description,
6225 const IceCandidateInterface* candidate) {
6226 if (candidate->sdp_mline_index() >= 0) {
6227 size_t mediacontent_index =
6228 static_cast<size_t>(candidate->sdp_mline_index());
6229 size_t content_size = description->description()->contents().size();
6230 if (mediacontent_index < content_size) {
6231 return &description->description()->contents()[mediacontent_index];
6232 } else {
6233 return RTCError(RTCErrorType::INVALID_RANGE,
6234 "Media line index (" +
6235 rtc::ToString(candidate->sdp_mline_index()) +
6236 ") out of range (number of mlines: " +
6237 rtc::ToString(content_size) + ").");
6238 }
6239 } else if (!candidate->sdp_mid().empty()) {
6240 auto& contents = description->description()->contents();
6241 auto it = absl::c_find_if(
6242 contents, [candidate](const cricket::ContentInfo& content_info) {
6243 return content_info.mid() == candidate->sdp_mid();
6244 });
6245 if (it == contents.end()) {
6246 return RTCError(
6247 RTCErrorType::INVALID_PARAMETER,
6248 "Mid " + candidate->sdp_mid() +
6249 " specified but no media section with that mid found.");
6250 } else {
6251 return &*it;
6252 }
6253 }
6254
6255 return RTCError(RTCErrorType::INVALID_PARAMETER,
6256 "Neither sdp_mline_index nor sdp_mid specified.");
6257}
6258
Steve Anton75737c02017-11-06 10:37:17 -08006259void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006260 // Destroy video channel first since it may have a pointer to the
6261 // voice channel.
6262 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006263 if (!video_info || video_info->rejected) {
6264 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006265 }
6266
Steve Anton6fec8802017-12-04 10:37:29 -08006267 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6268 if (!audio_info || audio_info->rejected) {
6269 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006270 }
6271
6272 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6273 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006274 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006275 }
6276}
6277
Steve Antondcc3c022017-12-22 16:02:54 -08006278RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6279 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006280 const cricket::ContentGroup* bundle_group = nullptr;
6281 if (configuration_.bundle_policy ==
6282 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006283 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006284 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6286 "max-bundle configured but session description "
6287 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006288 }
6289 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006290 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006291}
6292
6293RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006294 // Creating the media channels. Transports should already have been created
6295 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006296 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006297 if (voice && !voice->rejected &&
6298 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006299 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006300 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006301 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6302 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006303 }
6304 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6305 }
6306
Steve Antondcc3c022017-12-22 16:02:54 -08006307 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006308 if (video && !video->rejected &&
6309 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006310 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006311 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006312 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6313 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006314 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006315 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006316 }
6317
Steve Antondcc3c022017-12-22 16:02:54 -08006318 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006319 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006320 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006321 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006322 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6323 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006324 }
6325 }
6326
Steve Anton8a006912017-12-04 15:25:56 -08006327 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006328}
6329
Steve Anton4171afb2017-11-20 10:20:22 -08006330// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006331cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006332 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006333 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006334 MediaTransportConfig media_transport_config =
6335 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006336
Steve Anton75737c02017-11-06 10:37:17 -08006337 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006338 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006339 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6340 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006341 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006342 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006343 }
Steve Anton75737c02017-11-06 10:37:17 -08006344 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6345 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006346 voice_channel->SignalSentPacket.connect(this,
6347 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006348 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006349
Steve Antoneda6ccd2017-12-04 10:21:55 -08006350 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006351}
6352
Steve Anton4171afb2017-11-20 10:20:22 -08006353// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006354cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006355 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006356 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006357 MediaTransportConfig media_transport_config =
6358 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006359
Steve Anton75737c02017-11-06 10:37:17 -08006360 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006361 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006362 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6363 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006364 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006365 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006366 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006367 }
Steve Anton75737c02017-11-06 10:37:17 -08006368 video_channel->SignalDtlsSrtpSetupFailure.connect(
6369 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006370 video_channel->SignalSentPacket.connect(this,
6371 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006372 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006373
Steve Antoneda6ccd2017-12-04 10:21:55 -08006374 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006375}
6376
Zhi Huange830e682018-03-30 10:48:35 -07006377bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006378 switch (data_channel_type_) {
6379 case cricket::DCT_MEDIA_TRANSPORT:
6380 if (network_thread()->Invoke<bool>(
6381 RTC_FROM_HERE,
6382 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6383 this, mid))) {
6384 for (const auto& channel : sctp_data_channels_) {
6385 channel->OnTransportChannelCreated();
6386 }
6387 return true;
6388 }
Steve Anton75737c02017-11-06 10:37:17 -08006389 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006390 case cricket::DCT_SCTP:
6391 if (!sctp_factory_) {
6392 RTC_LOG(LS_ERROR)
6393 << "Trying to create SCTP transport, but didn't compile with "
6394 "SCTP support (HAVE_SCTP)";
6395 return false;
6396 }
6397 if (!network_thread()->Invoke<bool>(
6398 RTC_FROM_HERE,
6399 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6400 return false;
6401 }
6402 for (const auto& channel : sctp_data_channels_) {
6403 channel->OnTransportChannelCreated();
6404 }
6405 return true;
6406 case cricket::DCT_RTP:
6407 default:
6408 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6409 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6410 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006411 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006412 if (!rtp_data_channel_) {
6413 return false;
6414 }
6415 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6416 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6417 rtp_data_channel_->SignalSentPacket.connect(
6418 this, &PeerConnection::OnSentPacket_w);
6419 rtp_data_channel_->SetRtpTransport(rtp_transport);
6420 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006421 }
6422
Steve Anton75737c02017-11-06 10:37:17 -08006423 return true;
6424}
6425
6426Call::Stats PeerConnection::GetCallStats() {
6427 if (!worker_thread()->IsCurrent()) {
6428 return worker_thread()->Invoke<Call::Stats>(
6429 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6430 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006431 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006432 if (call_) {
6433 return call_->GetStats();
6434 } else {
6435 return Call::Stats();
6436 }
6437}
6438
Zhi Huange830e682018-03-30 10:48:35 -07006439bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006440 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006441 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006442 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6443 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006444 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006445 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006446 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006447 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6448 sctp_factory_->CreateSctpTransport(dtls_transport);
6449 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006450 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006451 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006452 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006453 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006454 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006455 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6456 // another thread. Would be nice if there was a helper class similar to
6457 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6458 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006459 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006460 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006461 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006462 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006463 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006464 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6465 std::move(cricket_sctp_transport));
6466 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006467 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006468}
6469
6470void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006471 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006472 sctp_transport_->Clear();
6473 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006474 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006475 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006476}
6477
6478void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006479 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006480 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006481 // Note: Cannot use rtc::Bind here because it will grab a reference to
6482 // PeerConnection and potentially cause PeerConnection to live longer than
6483 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6484 // be destroyed before PeerConnection is destroyed, and at that point all
6485 // pending tasks will be cleared.
6486 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6487 OnSctpTransportReadyToSendData_s(true);
6488 });
6489}
6490
6491void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006492 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006493 sctp_ready_to_send_data_ = ready;
6494 SignalSctpReadyToSendData(ready);
6495}
6496
6497void PeerConnection::OnSctpTransportDataReceived_n(
6498 const cricket::ReceiveDataParams& params,
6499 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006500 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006501 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006502 // Note: Cannot use rtc::Bind here because it will grab a reference to
6503 // PeerConnection and potentially cause PeerConnection to live longer than
6504 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6505 // be destroyed before PeerConnection is destroyed, and at that point all
6506 // pending tasks will be cleared.
6507 sctp_invoker_->AsyncInvoke<void>(
6508 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6509 OnSctpTransportDataReceived_s(params, payload);
6510 });
6511}
6512
6513void PeerConnection::OnSctpTransportDataReceived_s(
6514 const cricket::ReceiveDataParams& params,
6515 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006516 RTC_DCHECK_RUN_ON(signaling_thread());
6517 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006518 SignalSctpDataReceived(params, payload);
6519 }
6520}
6521
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006522void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
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 sctp_invoker_->AsyncInvoke<void>(
6526 RTC_FROM_HERE, signaling_thread(),
6527 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006528 &SignalSctpClosingProcedureStartedRemotely, sid));
6529}
6530
6531void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006532 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006533 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006534 sctp_invoker_->AsyncInvoke<void>(
6535 RTC_FROM_HERE, signaling_thread(),
6536 rtc::Bind(&sigslot::signal1<int>::operator(),
6537 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006538}
6539
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006540bool PeerConnection::SetupMediaTransportForDataChannels_n(
6541 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006542 media_transport_ =
6543 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006544 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006545 RTC_LOG(LS_ERROR)
6546 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006547 return false;
6548 }
6549
6550 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6551 media_transport_->SetDataSink(this);
6552 media_transport_data_mid_ = mid;
6553 transport_controller_->SignalMediaTransportStateChanged.connect(
6554 this, &PeerConnection::OnMediaTransportStateChanged_n);
6555 // Check the initial state right away, in case transport is already writable.
6556 OnMediaTransportStateChanged_n();
6557 return true;
6558}
6559
6560void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6561 if (!media_transport_) {
6562 return;
6563 }
6564 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6565 media_transport_data_mid_.reset();
6566 media_transport_->SetDataSink(nullptr);
6567 media_transport_invoker_ = nullptr;
6568 media_transport_ = nullptr;
6569}
6570
6571void PeerConnection::OnMediaTransportStateChanged_n() {
6572 if (!media_transport_data_mid_ ||
6573 transport_controller_->GetMediaTransportState(
6574 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6575 return;
6576 }
6577 media_transport_invoker_->AsyncInvoke<void>(
6578 RTC_FROM_HERE, signaling_thread(), [this] {
6579 RTC_DCHECK_RUN_ON(signaling_thread());
6580 media_transport_ready_to_send_data_ = true;
6581 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6582 });
6583}
6584
Steve Anton75737c02017-11-06 10:37:17 -08006585// Returns false if bundle is enabled and rtcp_mux is disabled.
6586bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6587 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6588 if (!bundle_enabled)
6589 return true;
6590
6591 const cricket::ContentGroup* bundle_group =
6592 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6593 RTC_DCHECK(bundle_group != NULL);
6594
6595 const cricket::ContentInfos& contents = desc->contents();
6596 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6597 citer != contents.end(); ++citer) {
6598 const cricket::ContentInfo* content = (&*citer);
6599 RTC_DCHECK(content != NULL);
6600 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006601 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006602 if (!HasRtcpMuxEnabled(content))
6603 return false;
6604 }
6605 }
6606 // RTCP-MUX is enabled in all the contents.
6607 return true;
6608}
6609
6610bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006611 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006612}
6613
Steve Anton06817cd2018-12-18 15:55:30 -08006614static RTCError ValidateMids(const cricket::SessionDescription& description) {
6615 std::set<std::string> mids;
6616 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006617 if (content.name.empty()) {
6618 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6619 "A media section is missing a MID attribute.");
6620 }
Steve Anton06817cd2018-12-18 15:55:30 -08006621 if (!mids.insert(content.name).second) {
6622 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6623 "Duplicate a=mid value '" + content.name + "'.");
6624 }
6625 }
6626 return RTCError::OK();
6627}
6628
Steve Anton8a006912017-12-04 15:25:56 -08006629RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006630 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006631 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006632 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006633 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006634 }
6635
6636 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006637 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006638 }
6639
Steve Anton3828c062017-12-06 10:34:51 -08006640 SdpType type = sdesc->GetType();
6641 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6642 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006643 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006644 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006645 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006646 }
6647
Steve Anton06817cd2018-12-18 15:55:30 -08006648 RTCError error = ValidateMids(*sdesc->description());
6649 if (!error.ok()) {
6650 return error;
6651 }
6652
Steve Anton75737c02017-11-06 10:37:17 -08006653 // Verify crypto settings.
6654 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006655 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6656 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006657 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006658 if (!crypto_error.ok()) {
6659 return crypto_error;
6660 }
Steve Anton75737c02017-11-06 10:37:17 -08006661 }
6662
6663 // Verify ice-ufrag and ice-pwd.
6664 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006665 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6666 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006667 }
6668
6669 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6671 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006672 }
6673
6674 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6675 // m-lines that do not rtcp-mux enabled.
6676
6677 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006678 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006679 // With an answer we want to compare the new answer session description with
6680 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006681 const cricket::SessionDescription* offer_desc =
6682 (source == cricket::CS_LOCAL) ? remote_description()->description()
6683 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006684 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6685 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6686 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006687 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6688 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006689 }
6690 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006691 // The re-offers should respect the order of m= sections in current
6692 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006693 // With a re-offer, either the current local or current remote descriptions
6694 // could be the most up to date, so we would like to check against both of
6695 // them if they exist. It could be the case that one of them has a 0 port
6696 // for a media section, but the other does not. This is important to check
6697 // against in the case that we are recycling an m= section.
6698 const cricket::SessionDescription* current_desc = nullptr;
6699 const cricket::SessionDescription* secondary_current_desc = nullptr;
6700 if (local_description()) {
6701 current_desc = local_description()->description();
6702 if (remote_description()) {
6703 secondary_current_desc = remote_description()->description();
6704 }
6705 } else if (remote_description()) {
6706 current_desc = remote_description()->description();
6707 }
Steve Anton75737c02017-11-06 10:37:17 -08006708 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006709 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6710 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006711 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6712 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006713 }
6714 }
6715
Steve Antonba42e992018-04-09 14:10:01 -07006716 if (IsUnifiedPlan()) {
6717 // Ensure that each audio and video media section has at most one
6718 // "StreamParams". This will return an error if receiving a session
6719 // description from a "Plan B" endpoint which adds multiple tracks of the
6720 // same type. With Unified Plan, there can only be at most one track per
6721 // media section.
6722 for (const ContentInfo& content : sdesc->description()->contents()) {
6723 const MediaContentDescription& desc = *content.description;
6724 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6725 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6726 desc.streams().size() > 1u) {
6727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6728 "Media section has more than one track specified "
6729 "with a=ssrc lines which is not supported with "
6730 "Unified Plan.");
6731 }
6732 }
6733 }
6734
Steve Anton8a006912017-12-04 15:25:56 -08006735 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006736}
6737
Steve Anton3828c062017-12-06 10:34:51 -08006738bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006739 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006740 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006741 return (state == PeerConnectionInterface::kStable) ||
6742 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006743 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006744 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006745 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6746 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6747 }
6748}
6749
Steve Anton3828c062017-12-06 10:34:51 -08006750bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006751 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006752 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006753 return (state == PeerConnectionInterface::kStable) ||
6754 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006755 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006756 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006757 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6758 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6759 }
6760}
6761
Steve Antonf8470812017-12-04 10:46:21 -08006762const char* PeerConnection::SessionErrorToString(SessionError error) const {
6763 switch (error) {
6764 case SessionError::kNone:
6765 return "ERROR_NONE";
6766 case SessionError::kContent:
6767 return "ERROR_CONTENT";
6768 case SessionError::kTransport:
6769 return "ERROR_TRANSPORT";
6770 }
6771 RTC_NOTREACHED();
6772 return "";
6773}
6774
Steve Anton75737c02017-11-06 10:37:17 -08006775std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006776 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006777 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6778 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006779 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006780}
6781
Steve Anton8e20f172018-03-06 10:55:04 -08006782void PeerConnection::ReportSdpFormatReceived(
6783 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006784 int num_audio_mlines = 0;
6785 int num_video_mlines = 0;
6786 int num_audio_tracks = 0;
6787 int num_video_tracks = 0;
6788 for (const ContentInfo& content : remote_offer.description()->contents()) {
6789 cricket::MediaType media_type = content.media_description()->type();
6790 int num_tracks = std::max(
6791 1, static_cast<int>(content.media_description()->streams().size()));
6792 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6793 num_audio_mlines += 1;
6794 num_audio_tracks += num_tracks;
6795 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6796 num_video_mlines += 1;
6797 num_video_tracks += num_tracks;
6798 }
6799 }
6800 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6801 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6802 format = kSdpFormatReceivedComplexUnifiedPlan;
6803 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6804 format = kSdpFormatReceivedComplexPlanB;
6805 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6806 format = kSdpFormatReceivedSimple;
6807 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006808 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6809 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006810}
6811
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006812void PeerConnection::NoteUsageEvent(UsageEvent event) {
6813 RTC_DCHECK_RUN_ON(signaling_thread());
6814 usage_event_accumulator_ |= static_cast<int>(event);
6815}
6816
6817void PeerConnection::ReportUsagePattern() const {
6818 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006819 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6820 usage_event_accumulator_,
6821 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006822 const int bad_bits =
6823 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6824 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6825 const int good_bits =
6826 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6827 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6828 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6829 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6830 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006831 // If called after close(), we can't report, because observer may have
6832 // been deallocated, and therefore pointer is null. Write to log instead.
6833 if (observer_) {
6834 Observer()->OnInterestingUsage(usage_event_accumulator_);
6835 } else {
6836 RTC_LOG(LS_INFO) << "Interesting usage signature "
6837 << usage_event_accumulator_
6838 << " observed after observer shutdown";
6839 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006840 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006841}
6842
Steve Anton0ffaaa22018-02-23 10:31:30 -08006843void PeerConnection::ReportNegotiatedSdpSemantics(
6844 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006845 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006846 switch (answer.description()->msid_signaling()) {
6847 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006848 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006849 break;
6850 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006851 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006852 break;
6853 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006854 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006855 break;
6856 case cricket::kMsidSignalingMediaSection |
6857 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006858 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006859 break;
6860 default:
6861 RTC_NOTREACHED();
6862 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006863 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6864 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006865}
6866
Steve Anton75737c02017-11-06 10:37:17 -08006867// We need to check the local/remote description for the Transport instead of
6868// the session, because a new Transport added during renegotiation may have
6869// them unset while the session has them set from the previous negotiation.
6870// Not doing so may trigger the auto generation of transport description and
6871// mess up DTLS identity information, ICE credential, etc.
6872bool PeerConnection::ReadyToUseRemoteCandidate(
6873 const IceCandidateInterface* candidate,
6874 const SessionDescriptionInterface* remote_desc,
6875 bool* valid) {
6876 *valid = true;
6877
6878 const SessionDescriptionInterface* current_remote_desc =
6879 remote_desc ? remote_desc : remote_description();
6880
6881 if (!current_remote_desc) {
6882 return false;
6883 }
6884
Guido Urdaneta41633172019-05-23 20:12:29 +02006885 RTCErrorOr<const cricket::ContentInfo*> result =
6886 FindContentInfo(current_remote_desc, candidate);
6887 if (!result.ok()) {
6888 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6889 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006890
6891 *valid = false;
6892 return false;
6893 }
6894
Guido Urdaneta41633172019-05-23 20:12:29 +02006895 std::string transport_name = GetTransportName(result.value()->name);
6896 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006897}
6898
6899bool PeerConnection::SrtpRequired() const {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006900 return !configuration_.use_datagram_transport &&
6901 (dtls_enabled_ ||
6902 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006903}
6904
6905void PeerConnection::OnTransportControllerGatheringState(
6906 cricket::IceGatheringState state) {
6907 RTC_DCHECK(signaling_thread()->IsCurrent());
6908 if (state == cricket::kIceGatheringGathering) {
6909 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6910 } else if (state == cricket::kIceGatheringComplete) {
6911 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6912 }
6913}
6914
6915void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006916 std::map<std::string, std::set<cricket::MediaType>>
6917 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006918 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006919 if (transceiver->internal()->channel()) {
6920 const std::string& transport_name =
6921 transceiver->internal()->channel()->transport_name();
6922 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006923 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006924 }
Steve Anton75737c02017-11-06 10:37:17 -08006925 }
6926 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006927 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6928 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006929 }
Zhi Huange830e682018-03-30 10:48:35 -07006930
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006931 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006932 if (transport_name) {
6933 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006934 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006935 }
Zhi Huange830e682018-03-30 10:48:35 -07006936
Steve Antonc7b964c2018-02-01 14:39:45 -08006937 for (const auto& entry : media_types_by_transport_name) {
6938 const std::string& transport_name = entry.first;
6939 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006940 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006941 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006942 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006943 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006944 }
6945 }
6946}
6947// Walk through the ConnectionInfos to gather best connection usage
6948// for IPv4 and IPv6.
6949void PeerConnection::ReportBestConnectionState(
6950 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006951 for (const cricket::TransportChannelStats& channel_stats :
6952 stats.channel_stats) {
6953 for (const cricket::ConnectionInfo& connection_info :
6954 channel_stats.connection_infos) {
6955 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006956 continue;
6957 }
6958
Steve Antonc7b964c2018-02-01 14:39:45 -08006959 const cricket::Candidate& local = connection_info.local_candidate;
6960 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006961
6962 // Increment the counter for IceCandidatePairType.
6963 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6964 (local.type() == RELAY_PORT_TYPE &&
6965 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006966 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6967 GetIceCandidatePairCounter(local, remote),
6968 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006969 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006970 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6971 GetIceCandidatePairCounter(local, remote),
6972 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006973 } else {
6974 RTC_CHECK(0);
6975 }
Steve Anton75737c02017-11-06 10:37:17 -08006976
6977 // Increment the counter for IP type.
6978 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006979 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6980 kBestConnections_IPv4,
6981 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006982 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006983 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6984 kBestConnections_IPv6,
6985 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006986 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006987 RTC_CHECK(!local.address().hostname().empty() &&
6988 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006989 }
6990
6991 return;
6992 }
6993 }
6994}
6995
6996void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006997 const cricket::TransportStats& stats,
6998 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006999 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7000 return;
7001 }
7002
7003 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7004 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7005 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7006 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7007 return;
7008 }
7009
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007010 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7011 for (cricket::MediaType media_type : media_types) {
7012 switch (media_type) {
7013 case cricket::MEDIA_TYPE_AUDIO:
7014 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7015 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7016 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7017 break;
7018 case cricket::MEDIA_TYPE_VIDEO:
7019 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7020 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7021 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7022 break;
7023 case cricket::MEDIA_TYPE_DATA:
7024 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7025 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7026 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7027 break;
7028 default:
7029 RTC_NOTREACHED();
7030 continue;
7031 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007032 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007033 }
7034
7035 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7036 for (cricket::MediaType media_type : media_types) {
7037 switch (media_type) {
7038 case cricket::MEDIA_TYPE_AUDIO:
7039 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7040 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7041 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7042 break;
7043 case cricket::MEDIA_TYPE_VIDEO:
7044 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7045 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7046 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7047 break;
7048 case cricket::MEDIA_TYPE_DATA:
7049 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7050 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7051 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7052 break;
7053 default:
7054 RTC_NOTREACHED();
7055 continue;
7056 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007057 }
Steve Anton75737c02017-11-06 10:37:17 -08007058 }
7059}
7060
7061void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007062 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007063 RTC_DCHECK(call_);
7064 call_->OnSentPacket(sent_packet);
7065}
7066
7067const std::string PeerConnection::GetTransportName(
7068 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007069 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007070 if (channel) {
7071 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007072 }
Steve Anton6fec8802017-12-04 10:37:29 -08007073 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007074 RTC_DCHECK(sctp_mid_);
7075 if (content_name == *sctp_mid_) {
7076 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007077 }
7078 }
7079 // Return an empty string if failed to retrieve the transport name.
7080 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007081}
7082
Steve Anton6fec8802017-12-04 10:37:29 -08007083void PeerConnection::DestroyTransceiverChannel(
7084 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7085 transceiver) {
7086 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007087
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007088 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007089 if (channel) {
7090 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007091 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007092 }
7093}
7094
7095void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007096 if (rtp_data_channel_) {
7097 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007098 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007099 rtp_data_channel_ = nullptr;
7100 }
7101
7102 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7103 // grab a reference to this PeerConnection. If this is called from the
7104 // PeerConnection destructor, the RefCountedObject vtable will have already
7105 // been destroyed (since it is a subclass of PeerConnection) and using
7106 // rtc::Bind will cause "Pure virtual function called" error to appear.
7107
7108 if (sctp_transport_) {
7109 OnDataChannelDestroyed();
7110 network_thread()->Invoke<void>(RTC_FROM_HERE,
7111 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007112 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007113 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007114
7115 if (media_transport_) {
7116 OnDataChannelDestroyed();
7117 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7118 RTC_DCHECK_RUN_ON(network_thread());
7119 TeardownMediaTransportForDataChannels_n();
7120 });
7121 }
Steve Anton6fec8802017-12-04 10:37:29 -08007122}
7123
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007124void PeerConnection::DestroyChannelInterface(
7125 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007126 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007127 switch (channel->media_type()) {
7128 case cricket::MEDIA_TYPE_AUDIO:
7129 channel_manager()->DestroyVoiceChannel(
7130 static_cast<cricket::VoiceChannel*>(channel));
7131 break;
7132 case cricket::MEDIA_TYPE_VIDEO:
7133 channel_manager()->DestroyVideoChannel(
7134 static_cast<cricket::VideoChannel*>(channel));
7135 break;
7136 case cricket::MEDIA_TYPE_DATA:
7137 channel_manager()->DestroyRtpDataChannel(
7138 static_cast<cricket::RtpDataChannel*>(channel));
7139 break;
7140 default:
7141 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7142 break;
7143 }
Zhi Huange830e682018-03-30 10:48:35 -07007144}
Steve Anton6fec8802017-12-04 10:37:29 -08007145
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007146bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007147 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007148 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007149 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007150 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007151 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007152 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007153 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007154 auto base_channel = GetChannel(mid);
7155 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007156 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007157 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007158 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007159 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007160 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007161
Karl Wiberg5966c502019-02-21 23:55:09 +01007162 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007163 // Only pass media transport to call object if media transport is used
7164 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007165 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007166 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007167
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007168 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007169}
7170
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007171void PeerConnection::OnSetStreams() {
7172 RTC_DCHECK_RUN_ON(signaling_thread());
7173 if (IsUnifiedPlan())
7174 UpdateNegotiationNeeded();
7175}
7176
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007177PeerConnectionObserver* PeerConnection::Observer() const {
7178 // In earlier production code, the pointer was not cleared on close,
7179 // which might have led to undefined behavior if the observer was not
7180 // deallocated, or strange crashes if it was.
7181 // We use CHECK in order to catch such behavior if it exists.
7182 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7183 RTC_CHECK(observer_);
7184 return observer_;
7185}
7186
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007187CryptoOptions PeerConnection::GetCryptoOptions() {
7188 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7189 // after it has been removed.
7190 return configuration_.crypto_options.has_value()
7191 ? *configuration_.crypto_options
7192 : factory_->options().crypto_options;
7193}
7194
Harald Alvestrand89061872018-01-02 14:08:34 +01007195void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007196 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007197 if (stats_collector_) {
7198 stats_collector_->ClearCachedStatsReport();
7199 }
7200}
7201
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007202void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007203 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7204 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007205}
7206
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007207void PeerConnection::UpdateNegotiationNeeded() {
7208 RTC_DCHECK_RUN_ON(signaling_thread());
7209 if (!IsUnifiedPlan()) {
7210 Observer()->OnRenegotiationNeeded();
7211 return;
7212 }
7213
7214 // If connection's [[IsClosed]] slot is true, abort these steps.
7215 if (IsClosed())
7216 return;
7217
7218 // If connection's signaling state is not "stable", abort these steps.
7219 if (signaling_state() != kStable)
7220 return;
7221
7222 // NOTE
7223 // The negotiation-needed flag will be updated once the state transitions to
7224 // "stable", as part of the steps for setting an RTCSessionDescription.
7225
7226 // If the result of checking if negotiation is needed is false, clear the
7227 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7228 // to false, and abort these steps.
7229 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7230 if (!is_negotiation_needed) {
7231 is_negotiation_needed_ = false;
7232 return;
7233 }
7234
7235 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7236 // steps.
7237 if (is_negotiation_needed_)
7238 return;
7239
7240 // Set connection's [[NegotiationNeeded]] slot to true.
7241 is_negotiation_needed_ = true;
7242
7243 // Queue a task that runs the following steps:
7244 // If connection's [[IsClosed]] slot is true, abort these steps.
7245 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7246 // Fire an event named negotiationneeded at connection.
7247 Observer()->OnRenegotiationNeeded();
7248}
7249
7250bool PeerConnection::CheckIfNegotiationIsNeeded() {
7251 RTC_DCHECK_RUN_ON(signaling_thread());
7252 // 1. If any implementation-specific negotiation is required, as described at
7253 // the start of this section, return true.
7254
7255 // 2. Let description be connection.[[CurrentLocalDescription]].
7256 const SessionDescriptionInterface* description = current_local_description();
7257 if (!description)
7258 return true;
7259
7260 // 3. If connection has created any RTCDataChannels, and no m= section in
7261 // description has been negotiated yet for data, return true.
7262 if (!sctp_data_channels_.empty()) {
7263 if (!cricket::GetFirstDataContent(description->description()->contents()))
7264 return true;
7265 }
7266
7267 // 4. For each transceiver in connection's set of transceivers, perform the
7268 // following checks:
7269 for (const auto& transceiver : transceivers_) {
7270 const ContentInfo* current_local_msection =
7271 FindTransceiverMSection(transceiver.get(), description);
7272
7273 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7274 transceiver.get(), current_remote_description());
7275
7276 // 4.3 If transceiver is stopped and is associated with an m= section,
7277 // but the associated m= section is not yet rejected in
7278 // connection.[[CurrentLocalDescription]] or
7279 // connection.[[CurrentRemoteDescription]], return true.
7280 if (transceiver->stopped()) {
7281 if (current_local_msection && !current_local_msection->rejected &&
7282 ((current_remote_msection && !current_remote_msection->rejected) ||
7283 !current_remote_msection)) {
7284 return true;
7285 }
7286 continue;
7287 }
7288
7289 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7290 // section in description, return true.
7291 if (!current_local_msection)
7292 return true;
7293
7294 const MediaContentDescription* current_local_media_description =
7295 current_local_msection->media_description();
7296 // 4.2 If transceiver isn't stopped and is associated with an m= section
7297 // in description then perform the following checks:
7298
7299 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7300 // associated m= section in description either doesn't contain a single
7301 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7302 // m= section, or the MSID values themselves, differ from what is in
7303 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7304 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7305 if (current_local_media_description->streams().size() == 0)
7306 return true;
7307
7308 std::vector<std::string> msection_msids;
7309 for (const auto& stream : current_local_media_description->streams()) {
7310 for (const std::string& msid : stream.stream_ids())
7311 msection_msids.push_back(msid);
7312 }
7313
7314 std::vector<std::string> transceiver_msids =
7315 transceiver->sender()->stream_ids();
7316 if (msection_msids.size() != transceiver_msids.size())
7317 return true;
7318
7319 absl::c_sort(transceiver_msids);
7320 absl::c_sort(msection_msids);
7321 if (transceiver_msids != msection_msids)
7322 return true;
7323 }
7324
7325 // 4.2.2 If description is of type "offer", and the direction of the
7326 // associated m= section in neither connection.[[CurrentLocalDescription]]
7327 // nor connection.[[CurrentRemoteDescription]] matches
7328 // transceiver.[[Direction]], return true.
7329 if (description->GetType() == SdpType::kOffer) {
7330 if (!current_remote_description())
7331 return true;
7332
7333 if (!current_remote_msection)
7334 return true;
7335
7336 RtpTransceiverDirection current_local_direction =
7337 current_local_media_description->direction();
7338 RtpTransceiverDirection current_remote_direction =
7339 current_remote_msection->media_description()->direction();
7340 if (transceiver->direction() != current_local_direction &&
7341 transceiver->direction() !=
7342 RtpTransceiverDirectionReversed(current_remote_direction)) {
7343 return true;
7344 }
7345 }
7346
7347 // 4.2.3 If description is of type "answer", and the direction of the
7348 // associated m= section in the description does not match
7349 // transceiver.[[Direction]] intersected with the offered direction (as
7350 // described in [JSEP] (section 5.3.1.)), return true.
7351 if (description->GetType() == SdpType::kAnswer) {
7352 if (!remote_description())
7353 return true;
7354
7355 const ContentInfo* offered_remote_msection =
7356 FindTransceiverMSection(transceiver.get(), remote_description());
7357
7358 RtpTransceiverDirection offered_direction =
7359 offered_remote_msection
7360 ? offered_remote_msection->media_description()->direction()
7361 : RtpTransceiverDirection::kInactive;
7362
7363 if (current_local_media_description->direction() !=
7364 (RtpTransceiverDirectionIntersection(
7365 transceiver->direction(),
7366 RtpTransceiverDirectionReversed(offered_direction)))) {
7367 return true;
7368 }
7369 }
7370 }
7371
7372 // If all the preceding checks were performed and true was not returned,
7373 // nothing remains to be negotiated; return false.
7374 return false;
7375}
7376
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007377} // namespace webrtc